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