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