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