Skip to main content

fallow_engine/
churn.rs

1//! Git churn analysis for hotspot detection.
2//!
3//! Shells out to `git log` to collect per-file change history, then computes
4//! recency-weighted churn scores and trend indicators.
5
6use rustc_hash::FxHashMap;
7use std::io::Read as _;
8use std::path::{Component, Path, PathBuf};
9use std::process::{Command, Output};
10use std::sync::OnceLock;
11
12use fallow_types::path_guard::CacheTarget;
13use serde::Deserialize;
14
15use crate::changed_files::git_path_from_bytes;
16
17pub use fallow_types::churn::ChurnTrend;
18
19/// Function pointer signature used by `set_spawn_hook` to intercept the
20/// `git log --numstat` subprocess. Lets the CLI route long-running git
21/// log calls through its `ScopedChild` registry so SIGINT / SIGTERM
22/// reap the subprocess instead of leaving it running after the parent
23/// exits. See `crates/cli/src/signal/` and issue #477.
24pub type ChurnSpawnHook = fn(&mut Command) -> std::io::Result<Output>;
25
26static SPAWN_HOOK: OnceLock<ChurnSpawnHook> = OnceLock::new();
27
28fn git_command(cwd: &Path) -> Command {
29    crate::git_env::git_command(cwd)
30}
31
32/// Install a spawn-hook that wraps the `git log` subprocess. Idempotent;
33/// subsequent calls are no-ops. Called once from the CLI's `main()` to
34/// route through the signal registry; defaults to `Command::output`
35/// when not set so the function-pointer indirection stays free for tests
36/// and embedders that don't care.
37pub fn set_spawn_hook(hook: ChurnSpawnHook) {
38    let _ = SPAWN_HOOK.set(hook);
39}
40
41fn spawn_output(command: &mut Command) -> std::io::Result<Output> {
42    if let Some(hook) = SPAWN_HOOK.get() {
43        hook(command)
44    } else {
45        command.output()
46    }
47}
48
49/// Number of seconds in one day.
50const SECS_PER_DAY: f64 = 86_400.0;
51
52/// Recency weight half-life in days. A commit from 90 days ago counts half
53/// as much as today's commit; 180 days ago counts 25%.
54const HALF_LIFE_DAYS: f64 = 90.0;
55
56/// Schema discriminator a `--churn-file` document must declare.
57const CHURN_FILE_SCHEMA: &str = "fallow-churn/v1";
58
59/// Upper bound on imported churn events. A file past this size is a sign of a
60/// pathological export (whole-history dump of a giant monorepo) rather than a
61/// useful hotspot window; parsing is rejected so we never allocate unbounded
62/// state from a single untrusted file. Mirrors the diff parser's
63/// `MAX_ADDED_LINES` guard in the CLI.
64const MAX_CHURN_EVENTS: usize = 5_000_000;
65
66/// Upper bound on the serialized churn import before JSON deserialization.
67const MAX_CHURN_FILE_BYTES: usize = 256 * 1024 * 1024;
68
69/// Reject an imported `timestamp` more than this many seconds in the future
70/// (one year). A unix-seconds commit time is never legitimately this far ahead
71/// even with clock skew, so a value past it is almost always a millisecond
72/// timestamp (~52000 years out) or corruption. Caught loudly because the
73/// recency decay uses `saturating_sub`, so a future timestamp would otherwise
74/// clamp to age 0, give every commit full weight, and silently collapse the
75/// recency signal that distinguishes recent from old churn.
76const MAX_FUTURE_TIMESTAMP_SECS: u64 = 365 * 24 * 60 * 60;
77
78/// Unit of a relative churn window.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum ChurnWindowUnit {
81    /// Fixed 24-hour days.
82    Days,
83    /// Fixed 7-day weeks.
84    Weeks,
85    /// Calendar months in UTC.
86    Months,
87    /// Calendar years in UTC.
88    Years,
89}
90
91impl ChurnWindowUnit {
92    /// Single-letter token used in the churn cache key.
93    const fn token(self) -> char {
94        match self {
95            Self::Days => 'd',
96            Self::Weeks => 'w',
97            Self::Months => 'm',
98            Self::Years => 'y',
99        }
100    }
101}
102
103/// The span of history churn analysis covers.
104///
105/// A relative window is stored as its duration rather than as the wall-clock
106/// string git resolves, so the same token always keys the same cache entry
107/// while the cutoff it resolves to moves with the run clock.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub enum ChurnWindow {
110    /// A span measured back from the run clock.
111    Relative {
112        /// How many `unit`s of history to cover.
113        count: u64,
114        /// The unit `count` is measured in.
115        unit: ChurnWindowUnit,
116    },
117    /// An absolute ISO `YYYY-MM-DD` date, read as UTC midnight.
118    Date(String),
119    /// No window: imported churn covers whatever the exporter selected.
120    Imported,
121}
122
123impl ChurnWindow {
124    /// Stable cache key for this window. Absolute for a date, the duration
125    /// token (`"1y"`, `"90d"`) for a relative span.
126    #[must_use]
127    fn cache_token(&self) -> String {
128        match self {
129            Self::Relative { count, unit } => format!("{count}{}", unit.token()),
130            Self::Date(date) => date.clone(),
131            Self::Imported => String::new(),
132        }
133    }
134
135    /// The oldest commit timestamp this window includes, resolved against
136    /// `clock`. `None` for imported churn, which has no cutoff to apply.
137    #[must_use]
138    fn cutoff_secs(&self, clock: &crate::clock::AnalysisClock) -> Option<u64> {
139        match self {
140            Self::Relative { count, unit } => Some(match unit {
141                ChurnWindowUnit::Days => clock.minus_days(*count),
142                ChurnWindowUnit::Weeks => clock.minus_days(count.saturating_mul(7)),
143                ChurnWindowUnit::Months => clock.minus_months(*count),
144                ChurnWindowUnit::Years => clock.minus_years(*count),
145            }),
146            Self::Date(date) => crate::clock::utc_midnight_epoch(date),
147            Self::Imported => None,
148        }
149    }
150}
151
152/// Parsed `--since` window plus the label reports print for it.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub struct SinceDuration {
155    /// History span to analyze.
156    pub window: ChurnWindow,
157    /// Human-readable display string (e.g., `"6 months"`).
158    pub display: String,
159}
160
161impl SinceDuration {
162    /// A relative window of `count` `unit`s, labelled for report headers.
163    #[must_use]
164    pub fn relative(count: u64, unit: ChurnWindowUnit, display: impl Into<String>) -> Self {
165        Self {
166            window: ChurnWindow::Relative { count, unit },
167            display: display.into(),
168        }
169    }
170}
171
172/// Per-author commit aggregation for a single file.
173///
174/// Authors are interned via [`ChurnResult::author_pool`] indices to keep
175/// per-file maps small and the bitcode cache compact.
176#[derive(Debug, Clone, Copy, PartialEq)]
177pub struct AuthorContribution {
178    /// Total commits by this author touching this file in the analysis window.
179    pub commits: u32,
180    /// Recency-weighted commit sum (exponential decay, half-life 90 days).
181    pub weighted_commits: f64,
182    /// Earliest commit timestamp by this author (epoch seconds).
183    pub first_commit_ts: u64,
184    /// Latest commit timestamp by this author (epoch seconds).
185    pub last_commit_ts: u64,
186}
187
188/// Per-file churn data collected from git history.
189#[derive(Debug, Clone)]
190pub struct FileChurn {
191    /// Absolute file path.
192    pub path: PathBuf,
193    /// Total number of commits touching this file in the analysis window.
194    pub commits: u32,
195    /// Recency-weighted commit count (exponential decay, half-life 90 days).
196    pub weighted_commits: f64,
197    /// Total lines added across all commits.
198    pub lines_added: u32,
199    /// Total lines deleted across all commits.
200    pub lines_deleted: u32,
201    /// Churn trend: accelerating, stable, or cooling.
202    pub trend: ChurnTrend,
203    /// Per-author contributions keyed by interned author index.
204    /// Indices reference [`ChurnResult::author_pool`].
205    pub authors: FxHashMap<u32, AuthorContribution>,
206}
207
208/// Result of churn analysis.
209#[derive(Debug, Clone)]
210pub struct ChurnResult {
211    /// Per-file churn data, keyed by absolute path.
212    pub files: FxHashMap<PathBuf, FileChurn>,
213    /// Whether the repository is a shallow clone.
214    pub shallow_clone: bool,
215    /// Author email pool. Per-file [`AuthorContribution`] entries reference
216    /// authors by their index into this vector.
217    pub author_pool: Vec<String>,
218    /// The instant recency weighting and staleness were measured against.
219    /// Ownership and routing reuse it so every churn-derived number in one run
220    /// agrees on "now".
221    pub clock: crate::clock::AnalysisClock,
222    /// Bytes of `git log` output that this run read. Zero when the churn
223    /// cache or a churn file supplied all the history.
224    pub git_log_bytes: u64,
225    /// Every commit in the history window with the files it changed, sorted
226    /// by committer timestamp and then by id. The history window can be
227    /// wider than the window of [`files`](Self::files), see
228    /// [`analyze_churn_cached_with_history`]. Imported events without a
229    /// `commit` id are not in this list.
230    pub commits: Vec<ChurnCommit>,
231}
232
233/// One commit in the churn history window and the files it changed.
234#[derive(Debug, Clone, PartialEq, Eq)]
235pub struct ChurnCommit {
236    /// Commit id (`%H`), or the opaque `commit` value of an imported event.
237    pub sha: String,
238    /// Committer timestamp (epoch seconds).
239    pub committed_at: u64,
240    /// Changed files, sorted by path.
241    pub files: Vec<ChurnCommitFile>,
242}
243
244/// One file that a [`ChurnCommit`] changed.
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub struct ChurnCommitFile {
247    /// Absolute file path.
248    pub path: PathBuf,
249    /// Lines added plus lines deleted in this file in this commit.
250    pub lines_changed: u32,
251}
252
253/// Parse a `--since` value into a git-compatible duration.
254///
255/// Accepts:
256/// - Durations: `6m`, `6months`, `90d`, `90days`, `1y`, `1year`, `2w`, `2weeks`
257/// - ISO dates: `2025-06-01`
258///
259/// # Errors
260///
261/// Returns an error if the input is not a recognized duration format or ISO date,
262/// the numeric part is invalid, or the duration is zero.
263pub fn parse_since(input: &str) -> Result<SinceDuration, String> {
264    if is_iso_date(input) {
265        return Ok(SinceDuration {
266            window: ChurnWindow::Date(input.to_string()),
267            display: input.to_string(),
268        });
269    }
270
271    let (num_str, unit) = split_number_unit(input)?;
272    let num: u64 = num_str
273        .parse()
274        .map_err(|_| format!("invalid number in --since: {input}"))?;
275
276    if num == 0 {
277        return Err("--since duration must be greater than 0".to_string());
278    }
279
280    let (unit, label) = match unit {
281        "d" | "day" | "days" => (ChurnWindowUnit::Days, "day"),
282        "w" | "week" | "weeks" => (ChurnWindowUnit::Weeks, "week"),
283        "m" | "month" | "months" => (ChurnWindowUnit::Months, "month"),
284        "y" | "year" | "years" => (ChurnWindowUnit::Years, "year"),
285        _ => {
286            return Err(format!(
287                "unknown duration unit '{unit}' in --since. Use d/w/m/y (e.g., 6m, 90d, 1y)"
288            ));
289        }
290    };
291    let plural = if num == 1 { "" } else { "s" };
292    Ok(SinceDuration::relative(
293        num,
294        unit,
295        format!("{num} {label}{plural}"),
296    ))
297}
298
299/// A `fallow-churn/v1` import document: a normalized, VCS-agnostic stand-in for
300/// `git log --numstat` output. Unknown fields are ignored (no
301/// `deny_unknown_fields`) so wrappers may carry extra metadata.
302#[derive(Debug, Deserialize)]
303struct ChurnFileDoc {
304    schema: String,
305    #[serde(default)]
306    events: Vec<ChurnFileEvent>,
307}
308
309/// One per-(commit, file) change event, the natural shape of a `<vcs> log
310/// --numstat` row. The optional `commit` id groups events into commits, which
311/// change coupling and change dispersion need. An event without it still
312/// feeds per-file churn.
313#[derive(Debug, Deserialize)]
314struct ChurnFileEvent {
315    /// Opaque commit id. Events with the same id belong to one commit.
316    #[serde(default)]
317    commit: Option<String>,
318    /// Repo-root-relative, forward-slash path. Joined to `root`.
319    path: String,
320    /// Commit time, unix SECONDS UTC (not milliseconds).
321    timestamp: u64,
322    /// Opaque author identity (email recommended); absent contributes no
323    /// ownership signal. fallow does NOT apply mailmap to imported authors.
324    #[serde(default)]
325    author: Option<String>,
326    /// Lines added in this file in this commit.
327    added: u32,
328    /// Lines deleted in this file in this commit.
329    deleted: u32,
330}
331
332/// Build churn data from a normalized `fallow-churn/v1` JSON import instead of
333/// `git log`. Lets projects on a non-git VCS (Yandex Arc, Mercurial, Perforce)
334/// feed change history into hotspot / ownership / bus-factor analysis: a small
335/// wrapper translates the VCS log into the contract and fallow runs all the
336/// usual recency-weighting, trend, and ownership logic on the imported events.
337///
338/// `root` is the project root that relative event paths are joined to (matching
339/// how the git path joins numstat paths), so the churn keys line up with the
340/// analyzed files. Returns a human-readable error (the CLI maps it to exit code
341/// 2) on an oversized or missing file, malformed JSON, wrong `schema`, an
342/// invalid repo-relative event path, a far-future timestamp, line totals above
343/// `u32::MAX`, or an event count past `MAX_CHURN_EVENTS`. An empty `events`
344/// array is valid (no hotspots), not an error. Never runs `git`.
345pub(crate) fn analyze_churn_from_file(path: &Path, root: &Path) -> Result<ChurnResult, String> {
346    let raw = read_churn_file_with_limit(path, MAX_CHURN_FILE_BYTES)?;
347    let doc: ChurnFileDoc = serde_json::from_str(&raw)
348        .map_err(|e| format!("failed to parse churn file {}: {e}", path.display()))?;
349    if doc.schema != CHURN_FILE_SCHEMA {
350        return Err(format!(
351            "churn file {} declares schema \"{}\", expected \"{CHURN_FILE_SCHEMA}\"",
352            path.display(),
353            doc.schema
354        ));
355    }
356    if doc.events.len() > MAX_CHURN_EVENTS {
357        return Err(format!(
358            "churn file {} has {} events, exceeding the {MAX_CHURN_EVENTS} limit",
359            path.display(),
360            doc.events.len()
361        ));
362    }
363
364    let state = churn_event_state_from_doc(&doc, path, root)?;
365    Ok(build_churn_result(
366        state,
367        false,
368        crate::clock::AnalysisClock::for_repo(root),
369    ))
370}
371
372fn read_churn_file_with_limit(path: &Path, limit: usize) -> Result<String, String> {
373    let file = std::fs::File::open(path)
374        .map_err(|e| format!("failed to read churn file {}: {e}", path.display()))?;
375    let mut bytes = Vec::new();
376    file.take(limit as u64 + 1)
377        .read_to_end(&mut bytes)
378        .map_err(|e| format!("failed to read churn file {}: {e}", path.display()))?;
379    if bytes.len() > limit {
380        return Err(format!(
381            "churn file {} is at least {} bytes, exceeding the {limit} byte limit",
382            path.display(),
383            bytes.len()
384        ));
385    }
386    String::from_utf8(bytes)
387        .map_err(|e| format!("failed to read churn file {} as UTF-8: {e}", path.display()))
388}
389
390/// Validate and fold a parsed `fallow-churn/v1` document into event state.
391///
392/// Rejects invalid paths, far-future (likely millisecond) timestamps, and line
393/// totals outside the public `u32` contract. Interns authors into the pool
394/// exactly as the git-log path does.
395fn churn_event_state_from_doc(
396    doc: &ChurnFileDoc,
397    path: &Path,
398    root: &Path,
399) -> Result<ChurnEventState, String> {
400    let mut builder = ChurnFileImportBuilder::new(path, root, churn_file_future_limit());
401
402    for event in &doc.events {
403        builder.push_event(event)?;
404    }
405
406    Ok(builder.finish())
407}
408
409/// The ceiling above which an imported event timestamp is rejected as
410/// implausible (almost always seconds-versus-milliseconds confusion).
411///
412/// This deliberately reads the wall clock rather than the run's
413/// [`crate::clock::AnalysisClock`]. The limit gates *acceptance* of an import,
414/// never a scored value, so it cannot move `weighted_commits` or `stale_days`
415/// the way a wall-clock "now" in the scoring path would. Pinning it to the run
416/// clock would instead make the gate reject real data: the run clock is HEAD's
417/// committer timestamp, so analyzing an older checkout while importing churn
418/// that covers today would drop every recent event. Wall-clock drift here is
419/// also one-directional, since a timestamp accepted today stays accepted on
420/// every later run.
421fn churn_file_future_limit() -> u64 {
422    let now_secs = std::time::SystemTime::now()
423        .duration_since(std::time::UNIX_EPOCH)
424        .unwrap_or_default()
425        .as_secs();
426    now_secs.saturating_add(MAX_FUTURE_TIMESTAMP_SECS)
427}
428
429struct ChurnFileImportBuilder<'a> {
430    path: &'a Path,
431    root: &'a Path,
432    future_limit: u64,
433    files: FxHashMap<PathBuf, FileEvents>,
434    totals: FxHashMap<PathBuf, (u64, u64)>,
435    author_pool: Vec<String>,
436    author_index: FxHashMap<String, u32>,
437    commit_pool: Vec<String>,
438    commit_index: FxHashMap<String, u32>,
439}
440
441impl<'a> ChurnFileImportBuilder<'a> {
442    fn new(path: &'a Path, root: &'a Path, future_limit: u64) -> Self {
443        Self {
444            path,
445            root,
446            future_limit,
447            files: FxHashMap::default(),
448            totals: FxHashMap::default(),
449            author_pool: Vec::new(),
450            author_index: FxHashMap::default(),
451            commit_pool: Vec::new(),
452            commit_index: FxHashMap::default(),
453        }
454    }
455
456    fn push_event(&mut self, event: &ChurnFileEvent) -> Result<(), String> {
457        let rel = normalize_churn_event_path(self.path, &event.path)?;
458        validate_churn_event_timestamp(self.path, event.timestamp, self.future_limit, &rel)?;
459
460        let abs_path = self.root.join(&rel);
461        let totals = self.totals.entry(abs_path.clone()).or_default();
462        totals.0 += u64::from(event.added);
463        totals.1 += u64::from(event.deleted);
464        if totals.0 > u64::from(u32::MAX) || totals.1 > u64::from(u32::MAX) {
465            return Err(format!(
466                "churn file {} has line totals for \"{rel}\" exceeding the u32 limit \
467                 (added {}, deleted {})",
468                self.path.display(),
469                totals.0,
470                totals.1
471            ));
472        }
473        let author_idx = self.intern_author(event.author.as_deref());
474        let commit_idx = event
475            .commit
476            .as_deref()
477            .map(str::trim)
478            .filter(|commit| !commit.is_empty())
479            .map(|commit| intern_author(commit, &mut self.commit_pool, &mut self.commit_index));
480        self.files
481            .entry(abs_path)
482            .or_insert_with(|| FileEvents { events: Vec::new() })
483            .events
484            .push(CachedCommitEvent {
485                timestamp: event.timestamp,
486                committed_at: event.timestamp,
487                lines_added: event.added,
488                lines_deleted: event.deleted,
489                author_idx,
490                commit_idx,
491            });
492        Ok(())
493    }
494
495    fn intern_author(&mut self, author: Option<&str>) -> Option<u32> {
496        author
497            .map(str::trim)
498            .filter(|email| !email.is_empty())
499            .map(|email| intern_author(email, &mut self.author_pool, &mut self.author_index))
500    }
501
502    fn finish(self) -> ChurnEventState {
503        ChurnEventState {
504            files: self.files,
505            author_pool: self.author_pool,
506            commit_pool: self.commit_pool,
507            git_log_bytes: 0,
508        }
509    }
510}
511
512fn normalize_churn_event_path(path: &Path, event_path: &str) -> Result<String, String> {
513    let normalized = event_path.replace('\\', "/");
514    let rel = normalized.trim();
515    if rel.is_empty() {
516        return Err(format!(
517            "churn file {} has an event with an empty path",
518            path.display()
519        ));
520    }
521    let bytes = rel.as_bytes();
522    let has_drive_prefix = bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':';
523    let has_empty_component = rel.split('/').any(str::is_empty);
524    let components_are_normal = Path::new(rel)
525        .components()
526        .all(|component| matches!(component, Component::Normal(_)));
527    if rel.starts_with('/') || has_drive_prefix || has_empty_component || !components_are_normal {
528        return Err(format!(
529            "churn file {} has an invalid repo-relative event path \"{event_path}\"",
530            path.display()
531        ));
532    }
533    Ok(rel.to_string())
534}
535
536fn validate_churn_event_timestamp(
537    path: &Path,
538    timestamp: u64,
539    future_limit: u64,
540    rel: &str,
541) -> Result<(), String> {
542    if timestamp <= future_limit {
543        return Ok(());
544    }
545
546    Err(format!(
547        "churn file {} has event timestamp {} for \"{rel}\" more than a year in the \
548         future; timestamps must be unix SECONDS (not milliseconds), UTC",
549        path.display(),
550        timestamp
551    ))
552}
553
554/// Check if the repository is a shallow clone.
555#[must_use]
556fn is_shallow_clone(root: &Path) -> bool {
557    let mut command = git_command(root);
558    command
559        .args(["rev-parse", "--is-shallow-repository"])
560        .current_dir(root);
561    command.output().is_ok_and(|o| {
562        String::from_utf8_lossy(&o.stdout)
563            .trim()
564            .eq_ignore_ascii_case("true")
565    })
566}
567
568/// Check if the directory is inside a git repository.
569#[must_use]
570pub fn is_git_repo(root: &Path) -> bool {
571    let mut command = git_command(root);
572    command.args(["rev-parse", "--git-dir"]).current_dir(root);
573    command.output().is_ok_and(|output| output.status.success())
574}
575
576/// Maximum size of a churn cache file (64 MB). The incremental cache stores
577/// per-commit events, so it needs more headroom than the old aggregate rows.
578const MAX_CHURN_CACHE_SIZE: usize = 64 * 1024 * 1024;
579
580/// Cache schema version. Bump when the on-disk shape of [`ChurnCache`]
581/// changes so older payloads are rejected on load. Version 5 stores paths in
582/// their platform-native byte representation instead of lossy UTF-8 strings.
583/// Version 6 keys on the window token instead of a wall-clock-resolved git
584/// date string and stores each event's committer timestamp so a warm load can
585/// prune to the same cutoff `git log --after` applies on a cold run.
586/// Version 7 scopes the log to the project root, so entries written from a
587/// subdirectory root with toplevel-relative paths are rejected.
588/// Version 8 stores the commit id of each event, so change coupling can
589/// rebuild the file set of each commit from the cache.
590const CHURN_CACHE_VERSION: u8 = 8;
591
592/// Serializable per-commit event for the disk cache.
593#[derive(Clone, bitcode::Encode, bitcode::Decode)]
594struct CachedCommitEvent {
595    timestamp: u64,
596    /// Committer timestamp. `git log --after` filters on this, while recency
597    /// weighting stays on the author timestamp, so a rebased commit lands in
598    /// the same window warm and cold without its age changing.
599    committed_at: u64,
600    lines_added: u32,
601    lines_deleted: u32,
602    author_idx: Option<u32>,
603    /// Index into the commit pool. `None` for an imported event without a
604    /// commit id.
605    commit_idx: Option<u32>,
606}
607
608/// Serializable per-file churn entry for the disk cache.
609#[derive(Clone, bitcode::Encode, bitcode::Decode)]
610struct CachedFileChurn {
611    path: Vec<u8>,
612    events: Vec<CachedCommitEvent>,
613}
614
615/// Cached churn data keyed by last indexed SHA and since string.
616#[derive(Clone, bitcode::Encode, bitcode::Decode)]
617struct ChurnCache {
618    /// Schema version; must equal [`CHURN_CACHE_VERSION`] to be accepted.
619    version: u8,
620    last_indexed_sha: String,
621    /// [`ChurnWindow::cache_token`] of the window this entry was built for.
622    window_token: String,
623    files: Vec<CachedFileChurn>,
624    shallow_clone: bool,
625    /// Author email pool referenced by [`CachedCommitEvent::author_idx`].
626    author_pool: Vec<String>,
627    /// Commit id pool referenced by [`CachedCommitEvent::commit_idx`].
628    commit_pool: Vec<String>,
629}
630
631/// Per-file commit events retained in memory while building or updating churn.
632struct FileEvents {
633    events: Vec<CachedCommitEvent>,
634}
635
636/// Event-level churn state. Unlike [`ChurnResult`], this preserves commit
637/// timestamps so a cache can merge new commits and recompute trend/recency.
638struct ChurnEventState {
639    files: FxHashMap<PathBuf, FileEvents>,
640    author_pool: Vec<String>,
641    /// Commit id pool referenced by [`CachedCommitEvent::commit_idx`].
642    commit_pool: Vec<String>,
643    /// Bytes of `git log` output that built this state in this run. Zero for
644    /// state restored from the churn cache or read from a churn file.
645    git_log_bytes: u64,
646}
647
648/// Get the full HEAD SHA for cache keying.
649fn get_head_sha(root: &Path) -> Option<String> {
650    crate::repo_refs::head_sha(root).ok().flatten()
651}
652
653/// Check whether `ancestor` is still reachable from `descendant`.
654fn is_ancestor(root: &Path, ancestor: &str, descendant: &str) -> bool {
655    let mut command = git_command(root);
656    command
657        .args(["merge-base", "--is-ancestor", ancestor, descendant])
658        .current_dir(root);
659    command.status().is_ok_and(|s| s.success())
660}
661
662/// Read the churn cache file. Returns `None` when the file is missing, too
663/// large, unreadable, or written by another cache version.
664fn read_churn_cache(cache_dir: &Path) -> Option<ChurnCache> {
665    let cache_file = cache_dir.join("churn.bin");
666    let data = std::fs::read(&cache_file).ok()?;
667    if data.len() > MAX_CHURN_CACHE_SIZE {
668        return None;
669    }
670    let cache: ChurnCache = bitcode::decode(&data).ok()?;
671    (cache.version == CHURN_CACHE_VERSION).then_some(cache)
672}
673
674/// Try to load churn data from disk cache. Returns `None` on cache miss
675/// or version mismatch.
676#[cfg(test)]
677fn load_churn_cache(cache_dir: &Path, window_token: &str) -> Option<ChurnCache> {
678    read_churn_cache(cache_dir).filter(|cache| cache.window_token == window_token)
679}
680
681/// True when `outer` includes every commit that `inner` includes at `clock`.
682fn window_covers(
683    outer: &ChurnWindow,
684    inner: &ChurnWindow,
685    clock: &crate::clock::AnalysisClock,
686) -> bool {
687    if outer == inner {
688        return true;
689    }
690    match (outer.cutoff_secs(clock), inner.cutoff_secs(clock)) {
691        (Some(outer_cutoff), Some(inner_cutoff)) => outer_cutoff <= inner_cutoff,
692        _ => false,
693    }
694}
695
696/// Load a cache entry whose window covers `window`, plus the window that the
697/// entry was built for.
698///
699/// One cache file serves several windows. Health reads a 12 month history
700/// while target churn reads 6 months. A narrower request prunes the wider
701/// entry to its own cutoff, which gives the same events as a cold
702/// `git log --after`, so the commands do not overwrite each other's entry.
703fn load_covering_churn_cache(
704    cache_dir: &Path,
705    window: &ChurnWindow,
706    clock: &crate::clock::AnalysisClock,
707) -> Option<(ChurnCache, SinceDuration)> {
708    let cache = read_churn_cache(cache_dir)?;
709    let cached = parse_since(&cache.window_token).ok()?;
710    window_covers(&cached.window, window, clock).then_some((cache, cached))
711}
712
713/// Save churn data to disk cache, unless a symlink leaves the `target` base.
714fn save_churn_cache(
715    target: CacheTarget<'_>,
716    last_indexed_sha: &str,
717    window_token: &str,
718    state: &ChurnEventState,
719    shallow_clone: bool,
720) {
721    let files: Vec<CachedFileChurn> = state
722        .files
723        .iter()
724        .map(|f| CachedFileChurn {
725            path: path_to_cache_bytes(f.0),
726            events: f.1.events.clone(),
727        })
728        .collect();
729    let cache = ChurnCache {
730        version: CHURN_CACHE_VERSION,
731        last_indexed_sha: last_indexed_sha.to_string(),
732        window_token: window_token.to_string(),
733        files,
734        shallow_clone,
735        author_pool: state.author_pool.clone(),
736        commit_pool: state.commit_pool.clone(),
737    };
738    let _ = target.write_file("churn.bin", &bitcode::encode(&cache));
739}
740
741/// Analyze churn with disk caching. Uses cached result when HEAD SHA and
742/// since duration match. If HEAD advanced from the cached SHA, runs an
743/// incremental `git log <cached>..HEAD --numstat` scan and merges it.
744///
745/// Returns `(ChurnResult, bool)` where the bool indicates whether reusable
746/// cache state was used.
747/// Returns `None` if git analysis fails.
748pub fn analyze_churn_cached(
749    root: &Path,
750    since: &SinceDuration,
751    cache_dir: &Path,
752    no_cache: bool,
753) -> Option<(ChurnResult, bool)> {
754    analyze_churn_cached_with_history(root, since, since, cache_dir, no_cache)
755}
756
757/// Analyze churn with disk caching over two windows.
758///
759/// [`ChurnResult::files`] covers `since`, which is the hotspot window.
760/// [`ChurnResult::commits`] covers `history`, which change coupling and
761/// change dispersion read. One `git log` pass over the wider window feeds
762/// both. When `since` is the wider window, it is used for both.
763///
764/// Returns `None` if git analysis fails.
765pub fn analyze_churn_cached_with_history(
766    root: &Path,
767    since: &SinceDuration,
768    history: &SinceDuration,
769    cache_dir: &Path,
770    no_cache: bool,
771) -> Option<(ChurnResult, bool)> {
772    let head_sha = get_head_sha(root)?;
773    let clock = crate::clock::AnalysisClock::for_repo(root);
774    let history = if window_covers(&history.window, &since.window, &clock) {
775        history
776    } else {
777        since
778    };
779    let files_cutoff = since.window.cutoff_secs(&clock);
780
781    if !no_cache
782        && let Some((state, shallow_clone)) =
783            try_reuse_churn_cache(root, history, cache_dir, &head_sha, &clock)
784    {
785        return Some((
786            build_windowed_churn_result(state, files_cutoff, shallow_clone, clock),
787            true,
788        ));
789    }
790
791    let (state, shallow_clone) =
792        analyze_fresh_churn(root, history, cache_dir, no_cache, &head_sha, &clock)?;
793    Some((
794        build_windowed_churn_result(state, files_cutoff, shallow_clone, clock),
795        false,
796    ))
797}
798
799fn try_reuse_churn_cache(
800    root: &Path,
801    since: &SinceDuration,
802    cache_dir: &Path,
803    head_sha: &str,
804    clock: &crate::clock::AnalysisClock,
805) -> Option<(ChurnEventState, bool)> {
806    let (cache, cached_since) = load_covering_churn_cache(cache_dir, &since.window, clock)?;
807    let cutoff = since.window.cutoff_secs(clock);
808    if cache.last_indexed_sha == head_sha {
809        let shallow_clone = cache.shallow_clone;
810        return Some((cache.into_event_state(cutoff), shallow_clone));
811    }
812
813    if !is_ancestor(root, &cache.last_indexed_sha, head_sha) {
814        return None;
815    }
816
817    // Extend the entry over its own window, so a narrower request does not
818    // shrink the entry that a wider request saved.
819    let (mut state, shallow_clone) =
820        extend_churn_cache(root, &cached_since, cache_dir, head_sha, cache, clock)?;
821    state.retain_window(cutoff);
822    Some((state, shallow_clone))
823}
824
825fn extend_churn_cache(
826    root: &Path,
827    since: &SinceDuration,
828    cache_dir: &Path,
829    head_sha: &str,
830    cache: ChurnCache,
831    clock: &crate::clock::AnalysisClock,
832) -> Option<(ChurnEventState, bool)> {
833    let shallow_clone = is_shallow_clone(root);
834    let range = format!("{}..HEAD", cache.last_indexed_sha);
835    let delta = analyze_churn_events(root, since, Some(&range), clock)?;
836    let mut state = cache.into_event_state(since.window.cutoff_secs(clock));
837    merge_churn_states(&mut state, delta);
838    save_churn_cache(
839        CacheTarget::new(root, cache_dir),
840        head_sha,
841        &since.window.cache_token(),
842        &state,
843        shallow_clone,
844    );
845    Some((state, shallow_clone))
846}
847
848fn analyze_fresh_churn(
849    root: &Path,
850    since: &SinceDuration,
851    cache_dir: &Path,
852    no_cache: bool,
853    head_sha: &str,
854    clock: &crate::clock::AnalysisClock,
855) -> Option<(ChurnEventState, bool)> {
856    let shallow_clone = is_shallow_clone(root);
857    let state = analyze_churn_events(root, since, None, clock)?;
858    if !no_cache {
859        save_churn_cache(
860            CacheTarget::new(root, cache_dir),
861            head_sha,
862            &since.window.cache_token(),
863            &state,
864            shallow_clone,
865        );
866    }
867
868    Some((state, shallow_clone))
869}
870
871impl ChurnCache {
872    /// Rehydrate the cached events, dropping everything the current window no
873    /// longer covers.
874    ///
875    /// The cache only ever appends, so an entry minted months ago still holds
876    /// commits a cold `git log --after` would exclude today. Without this prune
877    /// a warm run reports more history than a cold run over the same commit,
878    /// which is exactly the cache-transparency invariant fallow asserts
879    /// elsewhere.
880    fn into_event_state(self, cutoff_secs: Option<u64>) -> ChurnEventState {
881        let files = self
882            .files
883            .into_iter()
884            .filter_map(|entry| {
885                let path = path_from_cache_bytes(&entry.path)?;
886                Some((
887                    path,
888                    FileEvents {
889                        events: entry.events,
890                    },
891                ))
892            })
893            .collect();
894        let mut state = ChurnEventState {
895            files,
896            author_pool: self.author_pool,
897            commit_pool: self.commit_pool,
898            git_log_bytes: 0,
899        };
900        state.retain_window(cutoff_secs);
901        state
902    }
903}
904
905impl ChurnEventState {
906    /// Drop every event older than `cutoff_secs` (committer time), and every
907    /// file that has no event left. `None` keeps everything.
908    fn retain_window(&mut self, cutoff_secs: Option<u64>) {
909        let Some(cutoff) = cutoff_secs else {
910            return;
911        };
912        self.files.retain(|_, file| {
913            file.events.retain(|event| event.committed_at >= cutoff);
914            !file.events.is_empty()
915        });
916    }
917}
918
919#[cfg(unix)]
920fn path_to_cache_bytes(path: &Path) -> Vec<u8> {
921    use std::os::unix::ffi::OsStrExt;
922
923    path.as_os_str().as_bytes().to_vec()
924}
925
926#[cfg(unix)]
927#[expect(
928    clippy::unnecessary_wraps,
929    reason = "Windows rejects truncated UTF-16 bytes through this shared fallible contract"
930)]
931fn path_from_cache_bytes(path: &[u8]) -> Option<PathBuf> {
932    use std::ffi::OsStr;
933    use std::os::unix::ffi::OsStrExt;
934
935    Some(PathBuf::from(OsStr::from_bytes(path)))
936}
937
938#[cfg(windows)]
939fn path_to_cache_bytes(path: &Path) -> Vec<u8> {
940    use std::os::windows::ffi::OsStrExt;
941
942    path.as_os_str()
943        .encode_wide()
944        .flat_map(u16::to_le_bytes)
945        .collect()
946}
947
948#[cfg(windows)]
949fn path_from_cache_bytes(path: &[u8]) -> Option<PathBuf> {
950    use std::ffi::OsString;
951    use std::os::windows::ffi::OsStringExt;
952
953    let (chunks, remainder) = path.as_chunks::<2>();
954    if !remainder.is_empty() {
955        return None;
956    }
957    let wide: Vec<u16> = chunks
958        .iter()
959        .map(|&pair| u16::from_le_bytes(pair))
960        .collect();
961    Some(PathBuf::from(OsString::from_wide(&wide)))
962}
963
964/// Run `git log --numstat` and return event-level churn state.
965///
966/// The window is passed as an absolute `--after=@<epoch>` resolved against the
967/// run clock rather than as a phrase git re-resolves against the wall clock, so
968/// two runs over one commit see the same window boundary.
969fn analyze_churn_events(
970    root: &Path,
971    since: &SinceDuration,
972    revision_range: Option<&str>,
973    clock: &crate::clock::AnalysisClock,
974) -> Option<ChurnEventState> {
975    let mut command = git_command(root);
976    command.arg("log");
977    if let Some(range) = revision_range {
978        command.arg(range);
979    }
980    command
981        .args([
982            "--numstat",
983            "--no-merges",
984            "--no-renames",
985            "--use-mailmap",
986            "-z",
987            "--format=format:%at|%ct|%H|%ae%x00",
988        ])
989        .current_dir(root);
990    if let Some(cutoff) = since.window.cutoff_secs(clock) {
991        command.arg(format!("--after=@{cutoff}"));
992    }
993    // numstat paths are relative to the git toplevel. When the project root
994    // is a subdirectory, `--relative` rewrites them relative to the root, and
995    // the `.` pathspec skips commits and files outside it. Both are no-ops at
996    // the toplevel.
997    command.args(["--relative", "--", "."]);
998
999    let output = match spawn_output(&mut command) {
1000        Ok(o) => o,
1001        Err(e) => {
1002            tracing::warn!("hotspot analysis skipped: failed to run git: {e}");
1003            return None;
1004        }
1005    };
1006
1007    if !output.status.success() {
1008        let stderr = String::from_utf8_lossy(&output.stderr);
1009        tracing::warn!("hotspot analysis skipped: git log failed: {stderr}");
1010        return None;
1011    }
1012
1013    let mut state = parse_git_log_events_z(&output.stdout, root, clock.epoch_secs());
1014    state.git_log_bytes = output.stdout.len() as u64;
1015    Some(state)
1016}
1017
1018/// Intern every value of `delta` into `base` and map each old `delta` index to
1019/// its index in `base`.
1020fn remap_pool(base: &mut Vec<String>, delta: Vec<String>) -> FxHashMap<u32, u32> {
1021    let mut base_index: FxHashMap<String, u32> = base
1022        .iter()
1023        .enumerate()
1024        .filter_map(|(idx, value)| u32::try_from(idx).ok().map(|idx| (value.clone(), idx)))
1025        .collect();
1026    let mut mapping: FxHashMap<u32, u32> = FxHashMap::default();
1027    for (old_idx, value) in delta.into_iter().enumerate() {
1028        let Ok(old_idx) = u32::try_from(old_idx) else {
1029            continue;
1030        };
1031        mapping.insert(old_idx, intern_author(&value, base, &mut base_index));
1032    }
1033    mapping
1034}
1035
1036/// Merge new churn events into cached event state.
1037fn merge_churn_states(base: &mut ChurnEventState, delta: ChurnEventState) {
1038    base.git_log_bytes += delta.git_log_bytes;
1039    let author_mapping = remap_pool(&mut base.author_pool, delta.author_pool);
1040    let commit_mapping = remap_pool(&mut base.commit_pool, delta.commit_pool);
1041
1042    for (path, mut file) in delta.files {
1043        for event in &mut file.events {
1044            event.author_idx = event
1045                .author_idx
1046                .and_then(|idx| author_mapping.get(&idx).copied());
1047            event.commit_idx = event
1048                .commit_idx
1049                .and_then(|idx| commit_mapping.get(&idx).copied());
1050        }
1051        base.files
1052            .entry(path)
1053            .and_modify(|existing| existing.events.append(&mut file.events))
1054            .or_insert(file);
1055    }
1056}
1057
1058/// `now_secs` is the run clock's epoch, not the wall clock: it is the fallback
1059/// timestamp for a numstat record that arrives before any commit header, so
1060/// truncated or malformed git output still scores against the pinned instant.
1061fn parse_git_log_events_z(stdout: &[u8], root: &Path, now_secs: u64) -> ChurnEventState {
1062    let mut parser = GitLogEventParser::new(root, now_secs);
1063    for record in stdout.split(|byte| *byte == 0) {
1064        let record = record.strip_prefix(b"\n").unwrap_or(record);
1065        if record.is_empty() {
1066            continue;
1067        }
1068        if record.contains(&b'\t') {
1069            parser.record_numstat_bytes(record);
1070        } else {
1071            parser.consume_header(&String::from_utf8_lossy(record));
1072        }
1073    }
1074    parser.finish()
1075}
1076
1077struct GitLogEventParser<'a> {
1078    root: &'a Path,
1079    now_secs: u64,
1080    files: FxHashMap<PathBuf, FileEvents>,
1081    author_pool: Vec<String>,
1082    author_index: FxHashMap<String, u32>,
1083    commit_pool: Vec<String>,
1084    commit_index: FxHashMap<String, u32>,
1085    current_timestamp: Option<u64>,
1086    current_committed_at: Option<u64>,
1087    current_author_idx: Option<u32>,
1088    current_commit_idx: Option<u32>,
1089}
1090
1091impl<'a> GitLogEventParser<'a> {
1092    fn new(root: &'a Path, now_secs: u64) -> Self {
1093        Self {
1094            root,
1095            now_secs,
1096            files: FxHashMap::default(),
1097            author_pool: Vec::new(),
1098            author_index: FxHashMap::default(),
1099            commit_pool: Vec::new(),
1100            commit_index: FxHashMap::default(),
1101            current_timestamp: None,
1102            current_committed_at: None,
1103            current_author_idx: None,
1104            current_commit_idx: None,
1105        }
1106    }
1107
1108    /// Numstat rows always hold a tab, so a tab-free record is a commit header,
1109    /// a legacy bare timestamp, or noise.
1110    fn consume_header(&mut self, line: &str) {
1111        let line = line.trim();
1112        if line.is_empty() || self.record_commit_header(line) {
1113            return;
1114        }
1115        self.record_legacy_timestamp(line);
1116    }
1117
1118    /// Parse a `%at|%ct|%H|%ae` commit header. The older `%at|%ct|%ae` and
1119    /// `%at|%ae` headers are still accepted so a fixture or an embedder pinned
1120    /// to an older format keeps parsing. A header without `%H` gives events
1121    /// without a commit id, and a missing committer timestamp falls back to the
1122    /// author one.
1123    fn record_commit_header(&mut self, line: &str) -> bool {
1124        let Some((ts_str, rest)) = line.split_once('|') else {
1125            return false;
1126        };
1127        let Ok(ts) = ts_str.parse::<u64>() else {
1128            return false;
1129        };
1130        let (committed_at, rest) = match rest.split_once('|') {
1131            Some((committer_str, rest)) => (committer_str.parse::<u64>().unwrap_or(ts), rest),
1132            None => (ts, rest),
1133        };
1134        let (sha, email) = match rest.split_once('|') {
1135            Some((sha, email)) if is_commit_id(sha) => (Some(sha), email),
1136            _ => (None, rest),
1137        };
1138
1139        self.current_timestamp = Some(ts);
1140        self.current_committed_at = Some(committed_at);
1141        self.current_author_idx = Some(intern_author(
1142            email,
1143            &mut self.author_pool,
1144            &mut self.author_index,
1145        ));
1146        self.current_commit_idx =
1147            sha.map(|sha| intern_author(sha, &mut self.commit_pool, &mut self.commit_index));
1148        true
1149    }
1150
1151    fn record_legacy_timestamp(&mut self, line: &str) -> bool {
1152        let Ok(ts) = line.parse::<u64>() else {
1153            return false;
1154        };
1155
1156        self.current_timestamp = Some(ts);
1157        self.current_committed_at = Some(ts);
1158        self.current_author_idx = None;
1159        self.current_commit_idx = None;
1160        true
1161    }
1162
1163    fn record_numstat_bytes(&mut self, record: &[u8]) {
1164        let Some(first_tab) = record.iter().position(|byte| *byte == b'\t') else {
1165            return;
1166        };
1167        let Some(second_tab_offset) = record[first_tab + 1..]
1168            .iter()
1169            .position(|byte| *byte == b'\t')
1170        else {
1171            return;
1172        };
1173        let second_tab = first_tab + 1 + second_tab_offset;
1174        let Some(added) = std::str::from_utf8(&record[..first_tab])
1175            .ok()
1176            .and_then(|value| value.parse().ok())
1177        else {
1178            return;
1179        };
1180        let Some(deleted) = std::str::from_utf8(&record[first_tab + 1..second_tab])
1181            .ok()
1182            .and_then(|value| value.parse().ok())
1183        else {
1184            return;
1185        };
1186        let path = git_path_from_bytes(&record[second_tab + 1..]);
1187        self.record_numstat_path(added, deleted, path);
1188    }
1189
1190    fn record_numstat_path(&mut self, added: u32, deleted: u32, path: PathBuf) {
1191        let ts = self.current_timestamp.unwrap_or(self.now_secs);
1192        self.files
1193            .entry(self.root.join(path))
1194            .or_insert_with(|| FileEvents { events: Vec::new() })
1195            .events
1196            .push(CachedCommitEvent {
1197                timestamp: ts,
1198                committed_at: self.current_committed_at.unwrap_or(ts),
1199                lines_added: added,
1200                lines_deleted: deleted,
1201                author_idx: self.current_author_idx,
1202                commit_idx: self.current_commit_idx,
1203            });
1204    }
1205
1206    fn finish(self) -> ChurnEventState {
1207        ChurnEventState {
1208            files: self.files,
1209            author_pool: self.author_pool,
1210            commit_pool: self.commit_pool,
1211            git_log_bytes: 0,
1212        }
1213    }
1214}
1215
1216/// True for a full SHA-1 (40) or SHA-256 (64) hexadecimal commit id.
1217fn is_commit_id(value: &str) -> bool {
1218    matches!(value.len(), 40 | 64) && value.bytes().all(|byte| byte.is_ascii_hexdigit())
1219}
1220
1221/// Aggregate one file's raw commit events into a [`FileChurn`], applying
1222/// recency weighting, trend detection, and per-author accumulation.
1223#[expect(
1224    clippy::cast_possible_truncation,
1225    reason = "commit count per file is bounded by git history depth"
1226)]
1227fn aggregate_file_churn(path: PathBuf, file: FileEvents, now_secs: u64) -> FileChurn {
1228    let mut timestamps = Vec::with_capacity(file.events.len());
1229    let mut weighted_commits = 0.0;
1230    let mut lines_added = 0_u32;
1231    let mut lines_deleted = 0_u32;
1232    let mut authors: FxHashMap<u32, AuthorContribution> = FxHashMap::default();
1233
1234    for event in file.events {
1235        timestamps.push(event.timestamp);
1236        let age_days = (now_secs.saturating_sub(event.timestamp)) as f64 / SECS_PER_DAY;
1237        let weight = 0.5_f64.powf(age_days / HALF_LIFE_DAYS);
1238        weighted_commits += weight;
1239        lines_added = lines_added.saturating_add(event.lines_added);
1240        lines_deleted = lines_deleted.saturating_add(event.lines_deleted);
1241        accumulate_author(&mut authors, event.author_idx, weight, event.timestamp);
1242    }
1243
1244    let commits = timestamps.len() as u32;
1245    let trend = compute_trend(&timestamps);
1246    for c in authors.values_mut() {
1247        c.weighted_commits = (c.weighted_commits * 100.0).round() / 100.0;
1248    }
1249    FileChurn {
1250        path,
1251        commits,
1252        weighted_commits: (weighted_commits * 100.0).round() / 100.0,
1253        lines_added,
1254        lines_deleted,
1255        trend,
1256        authors,
1257    }
1258}
1259
1260/// Fold a single commit's author contribution into the per-author map.
1261fn accumulate_author(
1262    authors: &mut FxHashMap<u32, AuthorContribution>,
1263    author_idx: Option<u32>,
1264    weight: f64,
1265    timestamp: u64,
1266) {
1267    let Some(idx) = author_idx else {
1268        return;
1269    };
1270    authors
1271        .entry(idx)
1272        .and_modify(|c| {
1273            c.commits += 1;
1274            c.weighted_commits += weight;
1275            c.first_commit_ts = c.first_commit_ts.min(timestamp);
1276            c.last_commit_ts = c.last_commit_ts.max(timestamp);
1277        })
1278        .or_insert(AuthorContribution {
1279            commits: 1,
1280            weighted_commits: weight,
1281            first_commit_ts: timestamp,
1282            last_commit_ts: timestamp,
1283        });
1284}
1285
1286/// Convert event-level churn state into the public aggregate result.
1287///
1288/// Recency weighting is measured against `clock`, not the system clock, so the
1289/// same commit yields the same `weighted_commits` on every run.
1290fn build_churn_result(
1291    state: ChurnEventState,
1292    shallow_clone: bool,
1293    clock: crate::clock::AnalysisClock,
1294) -> ChurnResult {
1295    build_windowed_churn_result(state, None, shallow_clone, clock)
1296}
1297
1298/// Like [`build_churn_result`], but the per-file aggregates only count events
1299/// at or after `files_cutoff`. The commit list keeps the full state.
1300fn build_windowed_churn_result(
1301    mut state: ChurnEventState,
1302    files_cutoff: Option<u64>,
1303    shallow_clone: bool,
1304    clock: crate::clock::AnalysisClock,
1305) -> ChurnResult {
1306    let commits = collect_churn_commits(&state);
1307    state.retain_window(files_cutoff);
1308    let now_secs = clock.epoch_secs();
1309
1310    let files = state
1311        .files
1312        .into_iter()
1313        .map(|(path, file)| {
1314            let churn = aggregate_file_churn(path.clone(), file, now_secs);
1315            (path, churn)
1316        })
1317        .collect();
1318
1319    ChurnResult {
1320        files,
1321        shallow_clone,
1322        author_pool: state.author_pool,
1323        clock,
1324        git_log_bytes: state.git_log_bytes,
1325        commits,
1326    }
1327}
1328
1329/// Group the events of `state` by commit id. Each commit lists its files
1330/// sorted by path, and the commits are sorted by committer time, then id.
1331fn collect_churn_commits(state: &ChurnEventState) -> Vec<ChurnCommit> {
1332    let mut by_idx: FxHashMap<u32, ChurnCommit> = FxHashMap::default();
1333    for (path, file) in &state.files {
1334        for event in &file.events {
1335            let Some(idx) = event.commit_idx else {
1336                continue;
1337            };
1338            let Some(sha) = state.commit_pool.get(idx as usize) else {
1339                continue;
1340            };
1341            by_idx
1342                .entry(idx)
1343                .or_insert_with(|| ChurnCommit {
1344                    sha: sha.clone(),
1345                    committed_at: event.committed_at,
1346                    files: Vec::new(),
1347                })
1348                .files
1349                .push(ChurnCommitFile {
1350                    path: path.clone(),
1351                    lines_changed: event.lines_added.saturating_add(event.lines_deleted),
1352                });
1353        }
1354    }
1355    let mut commits: Vec<ChurnCommit> = by_idx
1356        .into_values()
1357        .map(|mut commit| {
1358            commit.files.sort_by(|a, b| a.path.cmp(&b.path));
1359            commit.files.dedup_by(|later, kept| {
1360                if later.path != kept.path {
1361                    return false;
1362                }
1363                kept.lines_changed = kept.lines_changed.saturating_add(later.lines_changed);
1364                true
1365            });
1366            commit
1367        })
1368        .collect();
1369    commits.sort_by(|a, b| {
1370        a.committed_at
1371            .cmp(&b.committed_at)
1372            .then_with(|| a.sha.cmp(&b.sha))
1373    });
1374    commits
1375}
1376
1377/// Intern an author email into the pool, returning its stable index.
1378fn intern_author(email: &str, pool: &mut Vec<String>, index: &mut FxHashMap<String, u32>) -> u32 {
1379    if let Some(&idx) = index.get(email) {
1380        return idx;
1381    }
1382    #[expect(
1383        clippy::cast_possible_truncation,
1384        reason = "author count is bounded by git history; u32 is far above any realistic ceiling"
1385    )]
1386    let idx = pool.len() as u32;
1387    let owned = email.to_string();
1388    index.insert(owned.clone(), idx);
1389    pool.push(owned);
1390    idx
1391}
1392
1393/// Compute churn trend by splitting commits into two temporal halves.
1394///
1395/// Finds the midpoint between the oldest and newest commit timestamps,
1396/// then compares commit counts in each half:
1397/// - Recent > 1.5× older → Accelerating
1398/// - Recent < 0.67× older → Cooling
1399/// - Otherwise → Stable
1400fn compute_trend(timestamps: &[u64]) -> ChurnTrend {
1401    if timestamps.len() < 2 {
1402        return ChurnTrend::Stable;
1403    }
1404
1405    let min_ts = timestamps.iter().copied().min().unwrap_or(0);
1406    let max_ts = timestamps.iter().copied().max().unwrap_or(0);
1407
1408    if max_ts == min_ts {
1409        return ChurnTrend::Stable;
1410    }
1411
1412    let midpoint = min_ts + (max_ts - min_ts) / 2;
1413    let recent = timestamps.iter().filter(|&&ts| ts > midpoint).count() as f64;
1414    let older = timestamps.iter().filter(|&&ts| ts <= midpoint).count() as f64;
1415
1416    if older < 1.0 {
1417        return ChurnTrend::Stable;
1418    }
1419
1420    let ratio = recent / older;
1421    if ratio > 1.5 {
1422        ChurnTrend::Accelerating
1423    } else if ratio < 0.67 {
1424        ChurnTrend::Cooling
1425    } else {
1426        ChurnTrend::Stable
1427    }
1428}
1429
1430fn is_iso_date(input: &str) -> bool {
1431    input.len() == 10
1432        && input.as_bytes().get(4) == Some(&b'-')
1433        && input.as_bytes().get(7) == Some(&b'-')
1434        && input[..4].bytes().all(|b| b.is_ascii_digit())
1435        && input[5..7].bytes().all(|b| b.is_ascii_digit())
1436        && input[8..10].bytes().all(|b| b.is_ascii_digit())
1437}
1438
1439fn split_number_unit(input: &str) -> Result<(&str, &str), String> {
1440    let pos = input.find(|c: char| !c.is_ascii_digit()).ok_or_else(|| {
1441        format!("--since requires a unit suffix (e.g., 6m, 90d, 1y), got: {input}")
1442    })?;
1443    if pos == 0 {
1444        return Err(format!(
1445            "--since must start with a number (e.g., 6m, 90d, 1y), got: {input}"
1446        ));
1447    }
1448    Ok((&input[..pos], &input[pos..]))
1449}
1450
1451#[cfg(test)]
1452mod tests {
1453    use super::*;
1454
1455    /// Analyze git churn for the files in `root`. `None` means no git or no repository.
1456    #[cfg(unix)]
1457    fn analyze_churn(root: &Path, since: &SinceDuration) -> Option<ChurnResult> {
1458        let clock = crate::clock::AnalysisClock::for_repo(root);
1459        let shallow = is_shallow_clone(root);
1460        let state = analyze_churn_events(root, since, None, &clock)?;
1461        Some(build_churn_result(state, shallow, clock))
1462    }
1463
1464    #[test]
1465    fn parse_since_months_short() {
1466        let d = parse_since("6m").unwrap();
1467        assert_eq!(
1468            d.window,
1469            ChurnWindow::Relative {
1470                count: 6,
1471                unit: ChurnWindowUnit::Months
1472            }
1473        );
1474        assert_eq!(d.display, "6 months");
1475    }
1476
1477    #[test]
1478    fn parse_since_months_long() {
1479        let d = parse_since("6months").unwrap();
1480        assert_eq!(
1481            d.window,
1482            ChurnWindow::Relative {
1483                count: 6,
1484                unit: ChurnWindowUnit::Months
1485            }
1486        );
1487        assert_eq!(d.display, "6 months");
1488    }
1489
1490    #[test]
1491    fn parse_since_days() {
1492        let d = parse_since("90d").unwrap();
1493        assert_eq!(
1494            d.window,
1495            ChurnWindow::Relative {
1496                count: 90,
1497                unit: ChurnWindowUnit::Days
1498            }
1499        );
1500        assert_eq!(d.display, "90 days");
1501    }
1502
1503    #[test]
1504    fn parse_since_year_singular() {
1505        let d = parse_since("1y").unwrap();
1506        assert_eq!(
1507            d.window,
1508            ChurnWindow::Relative {
1509                count: 1,
1510                unit: ChurnWindowUnit::Years
1511            }
1512        );
1513        assert_eq!(d.display, "1 year");
1514    }
1515
1516    #[test]
1517    fn parse_since_years_plural() {
1518        let d = parse_since("2years").unwrap();
1519        assert_eq!(
1520            d.window,
1521            ChurnWindow::Relative {
1522                count: 2,
1523                unit: ChurnWindowUnit::Years
1524            }
1525        );
1526        assert_eq!(d.display, "2 years");
1527    }
1528
1529    #[test]
1530    fn parse_since_weeks() {
1531        let d = parse_since("2w").unwrap();
1532        assert_eq!(
1533            d.window,
1534            ChurnWindow::Relative {
1535                count: 2,
1536                unit: ChurnWindowUnit::Weeks
1537            }
1538        );
1539        assert_eq!(d.display, "2 weeks");
1540    }
1541
1542    #[test]
1543    fn parse_since_iso_date() {
1544        let d = parse_since("2025-06-01").unwrap();
1545        assert_eq!(d.window, ChurnWindow::Date("2025-06-01".to_string()));
1546        assert_eq!(d.display, "2025-06-01");
1547    }
1548
1549    #[test]
1550    fn parse_since_month_singular() {
1551        let d = parse_since("1month").unwrap();
1552        assert_eq!(d.display, "1 month");
1553    }
1554
1555    #[test]
1556    fn parse_since_day_singular() {
1557        let d = parse_since("1day").unwrap();
1558        assert_eq!(d.display, "1 day");
1559    }
1560
1561    #[test]
1562    fn parse_since_zero_rejected() {
1563        assert!(parse_since("0m").is_err());
1564    }
1565
1566    #[test]
1567    fn parse_since_no_unit_rejected() {
1568        assert!(parse_since("90").is_err());
1569    }
1570
1571    #[test]
1572    fn parse_since_unknown_unit_rejected() {
1573        assert!(parse_since("6x").is_err());
1574    }
1575
1576    #[test]
1577    fn parse_since_no_number_rejected() {
1578        assert!(parse_since("months").is_err());
1579    }
1580
1581    #[test]
1582    fn trend_empty_is_stable() {
1583        assert_eq!(compute_trend(&[]), ChurnTrend::Stable);
1584    }
1585
1586    #[test]
1587    fn trend_single_commit_is_stable() {
1588        assert_eq!(compute_trend(&[100]), ChurnTrend::Stable);
1589    }
1590
1591    #[test]
1592    fn trend_accelerating() {
1593        let timestamps = vec![100, 200, 800, 850, 900, 950, 1000];
1594        assert_eq!(compute_trend(&timestamps), ChurnTrend::Accelerating);
1595    }
1596
1597    #[test]
1598    fn trend_cooling() {
1599        let timestamps = vec![100, 150, 200, 250, 300, 900, 1000];
1600        assert_eq!(compute_trend(&timestamps), ChurnTrend::Cooling);
1601    }
1602
1603    #[test]
1604    fn trend_stable_even_distribution() {
1605        let timestamps = vec![100, 200, 300, 700, 800, 900];
1606        assert_eq!(compute_trend(&timestamps), ChurnTrend::Stable);
1607    }
1608
1609    #[test]
1610    fn trend_same_timestamp_is_stable() {
1611        let timestamps = vec![500, 500, 500];
1612        assert_eq!(compute_trend(&timestamps), ChurnTrend::Stable);
1613    }
1614
1615    #[test]
1616    fn iso_date_valid() {
1617        assert!(is_iso_date("2025-06-01"));
1618        assert!(is_iso_date("2025-12-31"));
1619    }
1620
1621    #[test]
1622    fn iso_date_with_time_rejected() {
1623        assert!(!is_iso_date("2025-06-01T00:00:00"));
1624    }
1625
1626    #[test]
1627    fn iso_date_invalid() {
1628        assert!(!is_iso_date("6months"));
1629        assert!(!is_iso_date("2025"));
1630        assert!(!is_iso_date("not-a-date"));
1631        assert!(!is_iso_date("abcd-ef-gh"));
1632    }
1633
1634    #[test]
1635    fn trend_display() {
1636        assert_eq!(ChurnTrend::Accelerating.to_string(), "accelerating");
1637        assert_eq!(ChurnTrend::Stable.to_string(), "stable");
1638        assert_eq!(ChurnTrend::Cooling.to_string(), "cooling");
1639    }
1640
1641    #[test]
1642    fn trend_boundary_1_5x_ratio() {
1643        let timestamps = vec![100, 200, 600, 800, 1000];
1644        assert_eq!(compute_trend(&timestamps), ChurnTrend::Stable);
1645    }
1646
1647    #[test]
1648    fn trend_just_above_1_5x() {
1649        let timestamps = vec![100, 600, 800, 1000];
1650        assert_eq!(compute_trend(&timestamps), ChurnTrend::Accelerating);
1651    }
1652
1653    #[test]
1654    fn trend_boundary_0_67x_ratio() {
1655        let timestamps = vec![100, 200, 300, 600, 1000];
1656        assert_eq!(compute_trend(&timestamps), ChurnTrend::Cooling);
1657    }
1658
1659    #[test]
1660    fn trend_two_timestamps_different() {
1661        let timestamps = vec![100, 200];
1662        assert_eq!(compute_trend(&timestamps), ChurnTrend::Stable);
1663    }
1664
1665    #[test]
1666    fn parse_since_week_singular() {
1667        let d = parse_since("1week").unwrap();
1668        assert_eq!(
1669            d.window,
1670            ChurnWindow::Relative {
1671                count: 1,
1672                unit: ChurnWindowUnit::Weeks
1673            }
1674        );
1675        assert_eq!(d.display, "1 week");
1676    }
1677
1678    #[test]
1679    fn parse_since_weeks_long() {
1680        let d = parse_since("3weeks").unwrap();
1681        assert_eq!(
1682            d.window,
1683            ChurnWindow::Relative {
1684                count: 3,
1685                unit: ChurnWindowUnit::Weeks
1686            }
1687        );
1688        assert_eq!(d.display, "3 weeks");
1689    }
1690
1691    #[test]
1692    fn parse_since_days_long() {
1693        let d = parse_since("30days").unwrap();
1694        assert_eq!(
1695            d.window,
1696            ChurnWindow::Relative {
1697                count: 30,
1698                unit: ChurnWindowUnit::Days
1699            }
1700        );
1701        assert_eq!(d.display, "30 days");
1702    }
1703
1704    #[test]
1705    fn parse_since_year_long() {
1706        let d = parse_since("1year").unwrap();
1707        assert_eq!(
1708            d.window,
1709            ChurnWindow::Relative {
1710                count: 1,
1711                unit: ChurnWindowUnit::Years
1712            }
1713        );
1714        assert_eq!(d.display, "1 year");
1715    }
1716
1717    #[test]
1718    fn parse_since_overflow_number_rejected() {
1719        let result = parse_since("99999999999999999999d");
1720        assert!(result.is_err());
1721        let err = result.unwrap_err();
1722        assert!(err.contains("invalid number"));
1723    }
1724
1725    #[test]
1726    fn parse_since_zero_days_rejected() {
1727        assert!(parse_since("0d").is_err());
1728    }
1729
1730    #[test]
1731    fn parse_since_zero_weeks_rejected() {
1732        assert!(parse_since("0w").is_err());
1733    }
1734
1735    #[test]
1736    fn parse_since_zero_years_rejected() {
1737        assert!(parse_since("0y").is_err());
1738    }
1739
1740    #[test]
1741    fn iso_date_wrong_separator_positions() {
1742        assert!(!is_iso_date("20-25-0601"));
1743        assert!(!is_iso_date("202506-01-"));
1744    }
1745
1746    #[test]
1747    fn iso_date_too_short() {
1748        assert!(!is_iso_date("2025-06-0"));
1749    }
1750
1751    #[test]
1752    fn iso_date_letters_in_day() {
1753        assert!(!is_iso_date("2025-06-ab"));
1754    }
1755
1756    #[test]
1757    fn iso_date_letters_in_month() {
1758        assert!(!is_iso_date("2025-ab-01"));
1759    }
1760
1761    #[test]
1762    fn split_number_unit_valid() {
1763        let (num, unit) = split_number_unit("42days").unwrap();
1764        assert_eq!(num, "42");
1765        assert_eq!(unit, "days");
1766    }
1767
1768    #[test]
1769    fn split_number_unit_single_digit() {
1770        let (num, unit) = split_number_unit("1m").unwrap();
1771        assert_eq!(num, "1");
1772        assert_eq!(unit, "m");
1773    }
1774
1775    #[test]
1776    fn split_number_unit_no_digits() {
1777        let err = split_number_unit("abc").unwrap_err();
1778        assert!(err.contains("must start with a number"));
1779    }
1780
1781    #[test]
1782    fn split_number_unit_no_unit() {
1783        let err = split_number_unit("123").unwrap_err();
1784        assert!(err.contains("requires a unit suffix"));
1785    }
1786
1787    #[test]
1788    fn trend_serde_serialization() {
1789        assert_eq!(
1790            serde_json::to_string(&ChurnTrend::Accelerating).unwrap(),
1791            "\"accelerating\""
1792        );
1793        assert_eq!(
1794            serde_json::to_string(&ChurnTrend::Stable).unwrap(),
1795            "\"stable\""
1796        );
1797        assert_eq!(
1798            serde_json::to_string(&ChurnTrend::Cooling).unwrap(),
1799            "\"cooling\""
1800        );
1801    }
1802
1803    #[test]
1804    fn intern_author_returns_existing_index() {
1805        let mut pool = Vec::new();
1806        let mut index = FxHashMap::default();
1807        let i1 = intern_author("alice@x", &mut pool, &mut index);
1808        let i2 = intern_author("alice@x", &mut pool, &mut index);
1809        assert_eq!(i1, i2);
1810        assert_eq!(pool.len(), 1);
1811    }
1812
1813    #[test]
1814    fn intern_author_assigns_sequential_indices() {
1815        let mut pool = Vec::new();
1816        let mut index = FxHashMap::default();
1817        assert_eq!(intern_author("alice@x", &mut pool, &mut index), 0);
1818        assert_eq!(intern_author("bob@x", &mut pool, &mut index), 1);
1819        assert_eq!(intern_author("carol@x", &mut pool, &mut index), 2);
1820        assert_eq!(intern_author("alice@x", &mut pool, &mut index), 0);
1821    }
1822
1823    fn git(root: &Path, args: &[&str]) {
1824        let status = super::git_command(root)
1825            .args(args)
1826            .current_dir(root)
1827            .status()
1828            .expect("run git");
1829        assert!(status.success(), "git {args:?} failed");
1830    }
1831
1832    fn write(root: &Path, path: &str, contents: &str) {
1833        let path = root.join(path);
1834        std::fs::create_dir_all(path.parent().expect("test path has parent")).unwrap();
1835        std::fs::write(path, contents).unwrap();
1836    }
1837
1838    #[cfg(unix)]
1839    #[test]
1840    fn churn_preserves_special_filenames() {
1841        let repo = tempfile::tempdir().expect("create repo");
1842        let root = repo.path();
1843        git(root, &["init", "--quiet"]);
1844        git(root, &["config", "user.email", "churn@example.test"]);
1845        git(root, &["config", "user.name", "Churn Test"]);
1846        git(root, &["config", "commit.gpgsign", "false"]);
1847
1848        let special_files = [
1849            "src/line\nbreak.ts",
1850            "src/space name.ts",
1851            "src/quote\"name.ts",
1852            "src/back\\slash.ts",
1853            "src/unicode-λ.ts",
1854        ]
1855        .map(|path| root.join(path));
1856        std::fs::create_dir_all(root.join("src")).expect("source dir");
1857        for special in &special_files {
1858            std::fs::write(special, "export const value = 1;\n").expect("special fixture");
1859        }
1860        git(root, &["add", "."]);
1861        git(root, &["commit", "--quiet", "-m", "initial"]);
1862
1863        let since = parse_since("1y").expect("valid duration");
1864        let churn = analyze_churn(root, &since).expect("churn result");
1865        for special in special_files {
1866            assert!(
1867                churn.files.contains_key(&special),
1868                "missing {special:?}: {:?}",
1869                churn.files.keys()
1870            );
1871        }
1872    }
1873
1874    #[cfg(unix)]
1875    #[test]
1876    fn churn_cache_preserves_non_utf8_filenames() {
1877        use std::ffi::OsString;
1878        use std::os::unix::ffi::OsStringExt;
1879
1880        let invalid_path = PathBuf::from(OsString::from_vec(b"src/non-utf8-\xff.ts".to_vec()));
1881        let mut files = FxHashMap::default();
1882        files.insert(
1883            invalid_path.clone(),
1884            FileEvents {
1885                events: vec![CachedCommitEvent {
1886                    timestamp: 1,
1887                    committed_at: 1,
1888                    lines_added: 2,
1889                    lines_deleted: 1,
1890                    author_idx: None,
1891                    commit_idx: None,
1892                }],
1893            },
1894        );
1895        let state = ChurnEventState {
1896            files,
1897            author_pool: Vec::new(),
1898            commit_pool: Vec::new(),
1899            git_log_bytes: 0,
1900        };
1901        let cache_dir = tempfile::tempdir().expect("cache directory");
1902        let target = CacheTarget::inside(cache_dir.path());
1903        save_churn_cache(target, "abc123", "1y", &state, false);
1904        let warm = load_churn_cache(cache_dir.path(), "1y")
1905            .expect("warm churn cache")
1906            .into_event_state(None);
1907
1908        assert!(warm.files.contains_key(&invalid_path));
1909    }
1910
1911    #[test]
1912    fn churn_cache_rejects_pre_lossless_path_encoding_version() {
1913        let cache_dir = tempfile::tempdir().expect("cache directory");
1914        let cache = ChurnCache {
1915            version: 4,
1916            last_indexed_sha: "abc123".to_string(),
1917            window_token: "1y".to_string(),
1918            files: vec![CachedFileChurn {
1919                path: br#"/project/\"src/line\\nbreak.ts\""#.to_vec(),
1920                events: Vec::new(),
1921            }],
1922            shallow_clone: false,
1923            author_pool: Vec::new(),
1924            commit_pool: Vec::new(),
1925        };
1926        std::fs::write(cache_dir.path().join("churn.bin"), bitcode::encode(&cache))
1927            .expect("cache fixture");
1928
1929        assert!(load_churn_cache(cache_dir.path(), "1y").is_none());
1930    }
1931
1932    #[test]
1933    fn churn_cache_rejects_entries_without_commit_ids() {
1934        let cache_dir = tempfile::tempdir().expect("cache directory");
1935        let cache = ChurnCache {
1936            version: 7,
1937            last_indexed_sha: "abc123".to_string(),
1938            window_token: "1y".to_string(),
1939            files: Vec::new(),
1940            shallow_clone: false,
1941            author_pool: Vec::new(),
1942            commit_pool: Vec::new(),
1943        };
1944        std::fs::write(cache_dir.path().join("churn.bin"), bitcode::encode(&cache))
1945            .expect("cache fixture");
1946
1947        assert!(load_churn_cache(cache_dir.path(), "1y").is_none());
1948    }
1949
1950    #[test]
1951    fn commit_header_with_sha_records_the_commit_id() {
1952        let sha = "0123456789abcdef0123456789abcdef01234567";
1953        let header = format!("1700000000|1700000001|{sha}|alice@corp");
1954        let state = parse_git_log_events_z(
1955            &git_log_z(&[(header.as_str(), &["1\t2\tsrc/a.ts", "3\t0\tsrc/b.ts"])]),
1956            Path::new("/project"),
1957            1_700_000_100,
1958        );
1959        let result = build_churn_result(
1960            state,
1961            false,
1962            crate::clock::AnalysisClock::pinned(1_700_000_100),
1963        );
1964
1965        assert_eq!(result.author_pool, vec!["alice@corp".to_string()]);
1966        assert_eq!(result.commits.len(), 1);
1967        let commit = &result.commits[0];
1968        assert_eq!(commit.sha, sha);
1969        assert_eq!(commit.committed_at, 1_700_000_001);
1970        let files: Vec<(PathBuf, u32)> = commit
1971            .files
1972            .iter()
1973            .map(|file| (file.path.clone(), file.lines_changed))
1974            .collect();
1975        assert_eq!(
1976            files,
1977            vec![
1978                (PathBuf::from("/project/src/a.ts"), 3),
1979                (PathBuf::from("/project/src/b.ts"), 3),
1980            ]
1981        );
1982    }
1983
1984    #[test]
1985    fn commit_header_without_sha_keeps_the_email_and_no_commit() {
1986        let state = parse_git_log_events_z(
1987            &git_log_z(&[("1700000000|1700000000|alice@corp", &["1\t2\tsrc/a.ts"])]),
1988            Path::new("/project"),
1989            1_700_000_100,
1990        );
1991        let result = build_churn_result(
1992            state,
1993            false,
1994            crate::clock::AnalysisClock::pinned(1_700_000_100),
1995        );
1996
1997        assert_eq!(result.author_pool, vec!["alice@corp".to_string()]);
1998        assert!(result.commits.is_empty());
1999        assert_eq!(result.files.len(), 1);
2000    }
2001
2002    #[test]
2003    fn churn_file_commit_field_groups_events_into_commits() {
2004        let dir = tempfile::tempdir().unwrap();
2005        let path = write_churn_file(
2006            dir.path(),
2007            r#"{
2008              "schema": "fallow-churn/v1",
2009              "events": [
2010                { "commit": "c1", "path": "src/a.ts", "timestamp": 1700000000, "added": 1, "deleted": 0 },
2011                { "commit": "c1", "path": "src/b.ts", "timestamp": 1700000000, "added": 2, "deleted": 1 },
2012                { "commit": "c2", "path": "src/a.ts", "timestamp": 1700100000, "added": 4, "deleted": 0 },
2013                { "path": "src/c.ts", "timestamp": 1700100000, "added": 1, "deleted": 0 }
2014              ]
2015            }"#,
2016        );
2017        let result = analyze_churn_from_file(&path, Path::new("/project")).unwrap();
2018
2019        let commits: Vec<(String, usize)> = result
2020            .commits
2021            .iter()
2022            .map(|commit| (commit.sha.clone(), commit.files.len()))
2023            .collect();
2024        assert_eq!(commits, vec![("c1".to_string(), 2), ("c2".to_string(), 1)]);
2025        assert_eq!(
2026            result.files.len(),
2027            3,
2028            "an event without commit still counts"
2029        );
2030    }
2031
2032    #[test]
2033    fn cached_churn_merges_new_commits_after_head_advances() {
2034        let repo = tempfile::tempdir().expect("create repo");
2035        let root = repo.path();
2036        git(root, &["init"]);
2037        git(root, &["config", "user.email", "churn@example.test"]);
2038        git(root, &["config", "user.name", "Churn Test"]);
2039        git(root, &["config", "commit.gpgsign", "false"]);
2040
2041        write(root, "src/a.ts", "export const a = 1;\n");
2042        git(root, &["add", "."]);
2043        git(root, &["commit", "-m", "initial"]);
2044
2045        let since = parse_since("1y").unwrap();
2046        let cache = tempfile::tempdir().expect("create cache dir");
2047        let (cold, cold_hit) = analyze_churn_cached(root, &since, cache.path(), false).unwrap();
2048        assert!(!cold_hit);
2049        let file = root.join("src/a.ts");
2050        assert_eq!(cold.files[&file].commits, 1);
2051
2052        let (_warm, warm_hit) = analyze_churn_cached(root, &since, cache.path(), false).unwrap();
2053        assert!(warm_hit);
2054
2055        write(
2056            root,
2057            "src/a.ts",
2058            "export const a = 1;\nexport const b = 2;\n",
2059        );
2060        git(root, &["add", "."]);
2061        git(root, &["commit", "-m", "update a"]);
2062        let head = get_head_sha(root).unwrap();
2063
2064        let (incremental, incremental_hit) =
2065            analyze_churn_cached(root, &since, cache.path(), false).unwrap();
2066        assert!(incremental_hit);
2067        assert_eq!(incremental.files[&file].commits, 2);
2068
2069        let cache = load_churn_cache(cache.path(), &since.window.cache_token()).unwrap();
2070        assert_eq!(cache.last_indexed_sha, head);
2071    }
2072
2073    fn write_churn_file(dir: &std::path::Path, contents: &str) -> PathBuf {
2074        let path = dir.join("churn.json");
2075        std::fs::write(&path, contents).unwrap();
2076        path
2077    }
2078
2079    #[test]
2080    fn churn_file_happy_path() {
2081        let dir = tempfile::tempdir().unwrap();
2082        let root = Path::new("/project");
2083        let path = write_churn_file(
2084            dir.path(),
2085            r#"{
2086              "schema": "fallow-churn/v1",
2087              "events": [
2088                { "path": "src/a.ts", "timestamp": 1700000000, "author": "alice@corp", "added": 10, "deleted": 5 },
2089                { "path": "src/a.ts", "timestamp": 1700100000, "author": "bob@corp", "added": 3, "deleted": 2 }
2090              ]
2091            }"#,
2092        );
2093        let result = analyze_churn_from_file(&path, root).unwrap();
2094        let churn = &result.files[&PathBuf::from("/project/src/a.ts")];
2095        assert_eq!(churn.commits, 2);
2096        assert_eq!(churn.lines_added, 13);
2097        assert_eq!(churn.lines_deleted, 7);
2098        assert_eq!(churn.authors.len(), 2);
2099        assert!(result.author_pool.contains(&"alice@corp".to_string()));
2100        assert!(result.author_pool.contains(&"bob@corp".to_string()));
2101        assert!(!result.shallow_clone);
2102    }
2103
2104    #[test]
2105    fn churn_file_empty_events_is_valid() {
2106        let dir = tempfile::tempdir().unwrap();
2107        let path = write_churn_file(
2108            dir.path(),
2109            r#"{ "schema": "fallow-churn/v1", "events": [] }"#,
2110        );
2111        let result = analyze_churn_from_file(&path, Path::new("/project")).unwrap();
2112        assert!(result.files.is_empty());
2113        assert!(result.author_pool.is_empty());
2114    }
2115
2116    #[test]
2117    fn churn_file_missing_events_key_is_valid() {
2118        let dir = tempfile::tempdir().unwrap();
2119        let path = write_churn_file(dir.path(), r#"{ "schema": "fallow-churn/v1" }"#);
2120        let result = analyze_churn_from_file(&path, Path::new("/project")).unwrap();
2121        assert!(result.files.is_empty());
2122    }
2123
2124    #[test]
2125    fn churn_file_bad_schema_rejected() {
2126        let dir = tempfile::tempdir().unwrap();
2127        let path = write_churn_file(
2128            dir.path(),
2129            r#"{ "schema": "fallow-churn/v2", "events": [] }"#,
2130        );
2131        let err = analyze_churn_from_file(&path, Path::new("/project")).unwrap_err();
2132        assert!(err.contains("expected \"fallow-churn/v1\""), "{err}");
2133    }
2134
2135    #[test]
2136    fn churn_file_malformed_json_rejected() {
2137        let dir = tempfile::tempdir().unwrap();
2138        let path = write_churn_file(dir.path(), "{ not json");
2139        assert!(analyze_churn_from_file(&path, Path::new("/project")).is_err());
2140    }
2141
2142    #[test]
2143    fn churn_file_missing_file_rejected() {
2144        let err = analyze_churn_from_file(Path::new("/no/such/churn.json"), Path::new("/project"))
2145            .unwrap_err();
2146        assert!(err.contains("failed to read churn file"), "{err}");
2147    }
2148
2149    #[test]
2150    fn churn_file_reader_accepts_exact_limit() {
2151        let dir = tempfile::tempdir().unwrap();
2152        let path = write_churn_file(dir.path(), "12345678");
2153        assert_eq!(read_churn_file_with_limit(&path, 8).unwrap(), "12345678");
2154    }
2155
2156    #[test]
2157    fn churn_file_reader_rejects_limit_plus_one() {
2158        let dir = tempfile::tempdir().unwrap();
2159        let path = write_churn_file(dir.path(), "123456789");
2160        let err = read_churn_file_with_limit(&path, 8).unwrap_err();
2161        assert!(err.contains("at least 9 bytes"), "{err}");
2162        assert!(err.contains("8 byte limit"), "{err}");
2163    }
2164
2165    #[test]
2166    fn churn_file_empty_path_rejected() {
2167        let dir = tempfile::tempdir().unwrap();
2168        let path = write_churn_file(
2169            dir.path(),
2170            r#"{ "schema": "fallow-churn/v1", "events": [ { "path": "  ", "timestamp": 1700000000, "added": 1, "deleted": 0 } ] }"#,
2171        );
2172        let err = analyze_churn_from_file(&path, Path::new("/project")).unwrap_err();
2173        assert!(err.contains("empty path"), "{err}");
2174    }
2175
2176    #[test]
2177    fn churn_file_rejects_non_relative_paths() {
2178        let invalid = [
2179            "/tmp/a.ts",
2180            r"C:\tmp\a.ts",
2181            "../a.ts",
2182            "src/../../a.ts",
2183            "./src/a.ts",
2184            "//server/share/a.ts",
2185        ];
2186        for event_path in invalid {
2187            let dir = tempfile::tempdir().unwrap();
2188            let body = format!(
2189                r#"{{ "schema": "fallow-churn/v1", "events": [ {{ "path": {event_path:?}, "timestamp": 1700000000, "added": 1, "deleted": 0 }} ] }}"#
2190            );
2191            let path = write_churn_file(dir.path(), &body);
2192            let err = analyze_churn_from_file(&path, Path::new("/project")).unwrap_err();
2193            assert!(err.contains(event_path), "{event_path}: {err}");
2194            assert!(err.contains("repo-relative"), "{event_path}: {err}");
2195        }
2196    }
2197
2198    #[test]
2199    fn churn_file_accepts_unicode_and_spaces_in_path_components() {
2200        let dir = tempfile::tempdir().unwrap();
2201        let path = write_churn_file(
2202            dir.path(),
2203            r#"{ "schema": "fallow-churn/v1", "events": [ { "path": "src/ruimte map/naïef.ts", "timestamp": 1700000000, "added": 1, "deleted": 0 } ] }"#,
2204        );
2205        let result = analyze_churn_from_file(&path, Path::new("/project")).unwrap();
2206        assert!(
2207            result
2208                .files
2209                .contains_key(&PathBuf::from("/project/src/ruimte map/naïef.ts"))
2210        );
2211    }
2212
2213    #[test]
2214    fn churn_file_millisecond_timestamp_rejected() {
2215        let dir = tempfile::tempdir().unwrap();
2216        // 1700000000000 is milliseconds; ~52000 years in the future as seconds.
2217        let path = write_churn_file(
2218            dir.path(),
2219            r#"{ "schema": "fallow-churn/v1", "events": [ { "path": "src/a.ts", "timestamp": 1700000000000, "added": 1, "deleted": 0 } ] }"#,
2220        );
2221        let err = analyze_churn_from_file(&path, Path::new("/project")).unwrap_err();
2222        assert!(err.contains("milliseconds"), "{err}");
2223    }
2224
2225    #[test]
2226    fn churn_file_missing_author_contributes_no_signal() {
2227        let dir = tempfile::tempdir().unwrap();
2228        let path = write_churn_file(
2229            dir.path(),
2230            r#"{ "schema": "fallow-churn/v1", "events": [ { "path": "src/a.ts", "timestamp": 1700000000, "added": 1, "deleted": 0 } ] }"#,
2231        );
2232        let result = analyze_churn_from_file(&path, Path::new("/project")).unwrap();
2233        let churn = &result.files[&PathBuf::from("/project/src/a.ts")];
2234        assert_eq!(churn.commits, 1);
2235        assert!(churn.authors.is_empty());
2236        assert!(result.author_pool.is_empty());
2237    }
2238
2239    #[test]
2240    fn churn_file_empty_author_string_treated_as_absent() {
2241        let dir = tempfile::tempdir().unwrap();
2242        let path = write_churn_file(
2243            dir.path(),
2244            r#"{ "schema": "fallow-churn/v1", "events": [ { "path": "src/a.ts", "timestamp": 1700000000, "author": "  ", "added": 1, "deleted": 0 } ] }"#,
2245        );
2246        let result = analyze_churn_from_file(&path, Path::new("/project")).unwrap();
2247        assert!(result.author_pool.is_empty());
2248    }
2249
2250    #[test]
2251    fn churn_file_unknown_fields_ignored() {
2252        // Extra keys (including the reserved `commit`) are accepted and ignored,
2253        // so a wrapper carrying extra metadata stays forward-compatible.
2254        let dir = tempfile::tempdir().unwrap();
2255        let path = write_churn_file(
2256            dir.path(),
2257            r#"{ "schema": "fallow-churn/v1", "extra": true, "events": [ { "path": "src/a.ts", "timestamp": 1700000000, "author": "alice@corp", "added": 1, "deleted": 0, "commit": "abc123", "tz": "+0200" } ] }"#,
2258        );
2259        let result = analyze_churn_from_file(&path, Path::new("/project")).unwrap();
2260        assert_eq!(result.files[&PathBuf::from("/project/src/a.ts")].commits, 1);
2261    }
2262
2263    #[test]
2264    fn churn_file_backslash_paths_normalized() {
2265        let dir = tempfile::tempdir().unwrap();
2266        let path = write_churn_file(
2267            dir.path(),
2268            r#"{ "schema": "fallow-churn/v1", "events": [ { "path": "src\\a.ts", "timestamp": 1700000000, "added": 1, "deleted": 0 } ] }"#,
2269        );
2270        let result = analyze_churn_from_file(&path, Path::new("/project")).unwrap();
2271        assert!(
2272            result
2273                .files
2274                .contains_key(&PathBuf::from("/project/src/a.ts"))
2275        );
2276    }
2277
2278    #[test]
2279    fn churn_file_rejects_line_totals_above_u32() {
2280        let dir = tempfile::tempdir().unwrap();
2281        let path = write_churn_file(
2282            dir.path(),
2283            r#"{ "schema": "fallow-churn/v1", "events": [
2284                { "path": "src/a.ts", "timestamp": 1700000000, "added": 4294967295, "deleted": 0 },
2285                { "path": "src/a.ts", "timestamp": 1700000001, "added": 1, "deleted": 0 }
2286            ] }"#,
2287        );
2288        let err = analyze_churn_from_file(&path, Path::new("/project")).unwrap_err();
2289        assert!(err.contains("exceeding the u32 limit"), "{err}");
2290        assert!(err.contains("src/a.ts"), "{err}");
2291    }
2292
2293    #[test]
2294    fn churn_file_accepts_line_totals_at_u32_max() {
2295        let dir = tempfile::tempdir().unwrap();
2296        let path = write_churn_file(
2297            dir.path(),
2298            r#"{ "schema": "fallow-churn/v1", "events": [
2299                { "path": "src/a.ts", "timestamp": 1700000000, "added": 4294967294, "deleted": 4294967295 },
2300                { "path": "src/a.ts", "timestamp": 1700000001, "added": 1, "deleted": 0 }
2301            ] }"#,
2302        );
2303        let result = analyze_churn_from_file(&path, Path::new("/project")).unwrap();
2304        let churn = &result.files[&PathBuf::from("/project/src/a.ts")];
2305        assert_eq!(churn.lines_added, u32::MAX);
2306        assert_eq!(churn.lines_deleted, u32::MAX);
2307    }
2308
2309    /// A numstat row that arrives before any commit header (truncated or
2310    /// malformed git output) must fall back to the run clock, so the recorded
2311    /// timestamp, and therefore the file's weighted commits and staleness, is
2312    /// the same on every run over one commit instead of moving with wall time.
2313    #[test]
2314    fn headerless_numstat_falls_back_to_the_run_clock() {
2315        let root = Path::new("/project");
2316        let pinned = 1_700_000_000;
2317
2318        let state = parse_git_log_events_z(b"10\t5\tsrc/a.ts", root, pinned);
2319
2320        let events = &state.files[&PathBuf::from("/project/src/a.ts")].events;
2321        assert_eq!(events.len(), 1);
2322        assert_eq!(events[0].timestamp, pinned);
2323        assert_eq!(events[0].committed_at, pinned);
2324    }
2325
2326    /// The same truncated output parsed against two different run clocks must
2327    /// disagree only by those clocks: nothing in the fallback path may consult
2328    /// the system clock.
2329    #[test]
2330    fn headerless_numstat_tracks_only_the_supplied_clock() {
2331        let root = Path::new("/project");
2332        let record: &[u8] = b"1\t0\tsrc/a.ts";
2333
2334        let early = parse_git_log_events_z(record, root, 1_600_000_000);
2335        let late = parse_git_log_events_z(record, root, 1_700_000_000);
2336
2337        let key = PathBuf::from("/project/src/a.ts");
2338        assert_eq!(early.files[&key].events[0].timestamp, 1_600_000_000);
2339        assert_eq!(late.files[&key].events[0].timestamp, 1_700_000_000);
2340    }
2341
2342    /// A commit header still wins over the fallback: the clock only fills a gap.
2343    #[test]
2344    fn commit_header_timestamp_beats_the_run_clock_fallback() {
2345        let root = Path::new("/project");
2346        let record = b"1700000000|1700000500|dev@example.com\x002\t1\tsrc/a.ts";
2347
2348        let state = parse_git_log_events_z(record, root, 1_234_567_890);
2349
2350        let events = &state.files[&PathBuf::from("/project/src/a.ts")].events;
2351        assert_eq!(events[0].timestamp, 1_700_000_000);
2352        assert_eq!(events[0].committed_at, 1_700_000_500);
2353    }
2354
2355    /// The run clock for the ported `git log -z` scenarios below.
2356    const NOW: u64 = 1_750_000_000;
2357    const HEADER: &str = "1700000000|1700000000|dev@example.com";
2358
2359    /// Build the bytes that `git log --numstat -z --format=format:%at|%ct|%H|%ae%x00`
2360    /// prints: each commit is `header NUL LF`, then one NUL-terminated numstat
2361    /// record per file, and consecutive commits are split by one more NUL.
2362    fn git_log_z(commits: &[(&str, &[&str])]) -> Vec<u8> {
2363        let mut out = Vec::new();
2364        for (index, (header, rows)) in commits.iter().enumerate() {
2365            if index > 0 {
2366                out.push(0);
2367            }
2368            out.extend_from_slice(header.as_bytes());
2369            out.extend_from_slice(b"\0\n");
2370            for row in *rows {
2371                out.extend_from_slice(row.as_bytes());
2372                out.push(0);
2373            }
2374        }
2375        out
2376    }
2377
2378    fn churn_from_git_log_z(stdout: &[u8], root: &Path, now_secs: u64) -> ChurnResult {
2379        build_churn_result(
2380            parse_git_log_events_z(stdout, root, now_secs),
2381            false,
2382            crate::clock::AnalysisClock::pinned(now_secs),
2383        )
2384    }
2385
2386    fn churn_from_commits(commits: &[(&str, &[&str])]) -> ChurnResult {
2387        churn_from_git_log_z(&git_log_z(commits), Path::new("/project"), NOW)
2388    }
2389
2390    #[test]
2391    fn git_log_z_fixture_matches_real_git_output() {
2392        assert_eq!(
2393            git_log_z(&[
2394                ("1|2|a@b", &["1\t0\ta.ts"]),
2395                ("3|4|a@b", &["1\t0\ta.ts", "1\t0\tb c.ts"])
2396            ]),
2397            b"1|2|a@b\0\n1\t0\ta.ts\0\x003|4|a@b\0\n1\t0\ta.ts\x001\t0\tb c.ts\0".to_vec()
2398        );
2399    }
2400
2401    #[test]
2402    fn numstat_records_parse_counts_and_skip_binary_or_malformed_rows() {
2403        let root = Path::new("/project");
2404        type Expected = Option<(u32, u32, &'static str)>;
2405        let cases: &[(&str, Expected)] = &[
2406            ("10\t5\tsrc/file.ts", Some((10, 5, "src/file.ts"))),
2407            ("0\t0\tsrc/empty.ts", Some((0, 0, "src/empty.ts"))),
2408            (
2409                "3\t1\tpath with spaces/file.ts",
2410                Some((3, 1, "path with spaces/file.ts")),
2411            ),
2412            ("1\t0\tweird\tname.ts", Some((1, 0, "weird\tname.ts"))),
2413            (
2414                "4294967295\t8888\tsrc/big.ts",
2415                Some((u32::MAX, 8888, "src/big.ts")),
2416            ),
2417            ("4294967296\t0\tsrc/overflow.ts", None),
2418            ("-\t-\tsrc/image.png", None),
2419            ("-\t5\tsrc/file.ts", None),
2420            ("10\t-\tsrc/file.ts", None),
2421            ("10\t5", None),
2422        ];
2423        for (row, expected) in cases {
2424            let state = parse_git_log_events_z(&git_log_z(&[(HEADER, &[row])]), root, NOW);
2425            let Some((added, deleted, path)) = expected else {
2426                assert!(state.files.is_empty(), "{row:?} must not record churn");
2427                continue;
2428            };
2429            assert_eq!(state.files.len(), 1, "{row:?}");
2430            let events = &state.files[&root.join(path)].events;
2431            assert_eq!(events.len(), 1, "{row:?}");
2432            assert_eq!(events[0].lines_added, *added, "{row:?}");
2433            assert_eq!(events[0].lines_deleted, *deleted, "{row:?}");
2434        }
2435    }
2436
2437    #[test]
2438    fn git_log_z_aggregates_commits_and_lines_per_file() {
2439        let result = churn_from_commits(&[
2440            (
2441                HEADER,
2442                &["10\t5\tsrc/a.ts", "3\t1\tsrc/b.ts", "-\t-\timage.png"],
2443            ),
2444            ("1700100000|1700100000|dev@example.com", &["3\t2\tsrc/a.ts"]),
2445        ]);
2446        assert_eq!(result.files.len(), 2);
2447        let a = &result.files[&PathBuf::from("/project/src/a.ts")];
2448        assert_eq!((a.commits, a.lines_added, a.lines_deleted), (2, 13, 7));
2449        let b = &result.files[&PathBuf::from("/project/src/b.ts")];
2450        assert_eq!((b.commits, b.lines_added, b.lines_deleted), (1, 3, 1));
2451        assert!(
2452            !result
2453                .files
2454                .contains_key(&PathBuf::from("/project/image.png"))
2455        );
2456    }
2457
2458    #[test]
2459    fn git_log_z_empty_or_blank_output_records_nothing() {
2460        assert!(
2461            churn_from_git_log_z(b"", Path::new("/project"), NOW)
2462                .files
2463                .is_empty()
2464        );
2465        assert!(
2466            churn_from_git_log_z(b"\0\0\n\0  \0", Path::new("/project"), NOW)
2467                .files
2468                .is_empty()
2469        );
2470    }
2471
2472    #[test]
2473    fn git_log_z_blank_records_between_commits_are_ignored() {
2474        let stdout = b"  \0\n1700000000|1700000000|dev@example.com\0\n  \0\n10\t5\tsrc/a.ts\0\0";
2475        let result = churn_from_git_log_z(stdout, Path::new("/project"), NOW);
2476        assert_eq!(result.files.len(), 1);
2477        assert_eq!(result.files[&PathBuf::from("/project/src/a.ts")].commits, 1);
2478    }
2479
2480    #[test]
2481    fn git_log_z_paths_are_joined_to_the_root() {
2482        let root = Path::new("/my/project");
2483        let result =
2484            churn_from_git_log_z(&git_log_z(&[(HEADER, &["1\t0\tlib/utils.ts"])]), root, NOW);
2485        let key = PathBuf::from("/my/project/lib/utils.ts");
2486        assert_eq!(result.files[&key].path, key);
2487    }
2488
2489    #[test]
2490    fn git_log_z_weights_commits_by_age_against_the_run_clock() {
2491        let day = 86_400;
2492        let now = format!("{NOW}|{NOW}|dev@example.com");
2493        let half_life = format!("{0}|{0}|dev@example.com", NOW - 45 * day);
2494        let two_half_lives = format!("{0}|{0}|dev@example.com", NOW - 180 * day);
2495        let result = churn_from_commits(&[
2496            (&now, &["1\t0\tsrc/fresh.ts"]),
2497            (&half_life, &["1\t0\tsrc/half.ts"]),
2498            (&two_half_lives, &["1\t0\tsrc/old.ts"]),
2499        ]);
2500        let weight = |name: &str| {
2501            result.files[&PathBuf::from(format!("/project/src/{name}"))].weighted_commits
2502        };
2503        assert!((weight("fresh.ts") - 1.0).abs() < f64::EPSILON);
2504        // 0.5^(45/90) = 0.7071..., rounded to two decimals.
2505        assert!((weight("half.ts") - 0.71).abs() < f64::EPSILON);
2506        assert!((weight("old.ts") - 0.25).abs() < f64::EPSILON);
2507    }
2508
2509    #[test]
2510    fn git_log_z_headerless_numstat_weighs_as_a_commit_at_the_run_clock() {
2511        let result = churn_from_git_log_z(b"10\t5\tsrc/no_ts.ts\0", Path::new("/project"), NOW);
2512        let churn = &result.files[&PathBuf::from("/project/src/no_ts.ts")];
2513        assert_eq!(
2514            (churn.commits, churn.lines_added, churn.lines_deleted),
2515            (1, 10, 5)
2516        );
2517        assert!((churn.weighted_commits - 1.0).abs() < f64::EPSILON);
2518    }
2519
2520    #[test]
2521    fn git_log_z_trend_is_computed_per_file() {
2522        let result = churn_from_commits(&[
2523            (
2524                "1000|1000|dev@example.com",
2525                &["5\t1\tsrc/old.ts", "1\t0\tsrc/hot.ts"],
2526            ),
2527            ("1800|1800|dev@example.com", &["1\t0\tsrc/hot.ts"]),
2528            ("1900|1900|dev@example.com", &["1\t0\tsrc/hot.ts"]),
2529            ("1950|1950|dev@example.com", &["1\t0\tsrc/hot.ts"]),
2530            (
2531                "2000|2000|dev@example.com",
2532                &["3\t1\tsrc/old.ts", "1\t0\tsrc/hot.ts"],
2533            ),
2534        ]);
2535        let old = &result.files[&PathBuf::from("/project/src/old.ts")];
2536        let hot = &result.files[&PathBuf::from("/project/src/hot.ts")];
2537        assert_eq!(old.commits, 2);
2538        assert_eq!(old.trend, ChurnTrend::Stable);
2539        assert_eq!(hot.commits, 5);
2540        assert_eq!(hot.trend, ChurnTrend::Accelerating);
2541    }
2542
2543    #[test]
2544    fn git_log_z_interns_authors_and_aggregates_per_author() {
2545        let result = churn_from_commits(&[
2546            (
2547                "1700000000|1700000000|alice@example.com",
2548                &["1\t0\tsrc/index.ts"],
2549            ),
2550            (
2551                "1700100000|1700100000|bob@example.com",
2552                &["2\t0\tsrc/index.ts"],
2553            ),
2554            (
2555                "1700200000|1700200000|alice@example.com",
2556                &["1\t1\tsrc/index.ts"],
2557            ),
2558        ]);
2559        assert_eq!(
2560            result.author_pool,
2561            vec![
2562                "alice@example.com".to_string(),
2563                "bob@example.com".to_string()
2564            ]
2565        );
2566        let churn = &result.files[&PathBuf::from("/project/src/index.ts")];
2567        assert_eq!(churn.commits, 3);
2568        assert_eq!(churn.authors.len(), 2);
2569        let alice = &churn.authors[&0];
2570        assert_eq!(alice.commits, 2);
2571        assert_eq!(alice.first_commit_ts, 1_700_000_000);
2572        assert_eq!(alice.last_commit_ts, 1_700_200_000);
2573        let bob = &churn.authors[&1];
2574        assert_eq!(bob.commits, 1);
2575        assert_eq!(bob.first_commit_ts, 1_700_100_000);
2576    }
2577
2578    #[test]
2579    fn git_log_z_legacy_headers_still_parse() {
2580        let result = churn_from_commits(&[
2581            ("1700000000", &["10\t5\tsrc/bare.ts"]),
2582            ("1700100000|alice@example.com", &["1\t0\tsrc/two_field.ts"]),
2583        ]);
2584        assert_eq!(result.author_pool, vec!["alice@example.com".to_string()]);
2585        let bare = &result.files[&PathBuf::from("/project/src/bare.ts")];
2586        assert_eq!(bare.commits, 1);
2587        assert!(bare.authors.is_empty());
2588        let two_field = &result.files[&PathBuf::from("/project/src/two_field.ts")];
2589        assert_eq!(two_field.authors[&0].first_commit_ts, 1_700_100_000);
2590    }
2591
2592    #[test]
2593    fn churn_file_matches_git_log_z_parse() {
2594        // The same events fed via git numstat and via the JSON import must
2595        // produce identical aggregate churn: the import reuses
2596        // build_churn_result, so only the SOURCE differs.
2597        let dir = tempfile::tempdir().unwrap();
2598        let root = Path::new("/project");
2599        let path = write_churn_file(
2600            dir.path(),
2601            r#"{
2602              "schema": "fallow-churn/v1",
2603              "events": [
2604                { "path": "src/a.ts", "timestamp": 1700000000, "author": "alice@corp", "added": 10, "deleted": 5 },
2605                { "path": "src/b.ts", "timestamp": 1700000000, "author": "alice@corp", "added": 3, "deleted": 1 },
2606                { "path": "src/a.ts", "timestamp": 1700100000, "author": "bob@corp", "added": 3, "deleted": 2 }
2607              ]
2608            }"#,
2609        );
2610        let imported = analyze_churn_from_file(&path, root).unwrap();
2611        let git = churn_from_git_log_z(
2612            &git_log_z(&[
2613                (
2614                    "1700000000|1700000000|alice@corp",
2615                    &["10\t5\tsrc/a.ts", "3\t1\tsrc/b.ts"],
2616                ),
2617                ("1700100000|1700100000|bob@corp", &["3\t2\tsrc/a.ts"]),
2618            ]),
2619            root,
2620            imported.clock.epoch_secs(),
2621        );
2622
2623        assert_eq!(
2624            git.author_pool, imported.author_pool,
2625            "author pools diverge"
2626        );
2627        assert_eq!(git.files.len(), imported.files.len());
2628        for (file, git_churn) in &git.files {
2629            let imp = &imported.files[file];
2630            assert_eq!(git_churn.commits, imp.commits, "commits for {file:?}");
2631            assert_eq!(git_churn.lines_added, imp.lines_added, "added for {file:?}");
2632            assert_eq!(
2633                git_churn.lines_deleted, imp.lines_deleted,
2634                "deleted for {file:?}"
2635            );
2636            assert_eq!(git_churn.trend, imp.trend, "trend for {file:?}");
2637            assert_eq!(git_churn.authors, imp.authors, "authors for {file:?}");
2638            assert!(
2639                (git_churn.weighted_commits - imp.weighted_commits).abs() < f64::EPSILON,
2640                "weighted_commits for {file:?}: {} vs {}",
2641                git_churn.weighted_commits,
2642                imp.weighted_commits
2643            );
2644        }
2645    }
2646}