Skip to main content

lean_ctx_ext/core/hotspots/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Hotspots: files that change often, are changed by merges and reverted,
3//! and are large (Local Read §39, report format `hotspots-v1`).
4//!
5//! A report comes from one of two producers:
6//! - **Weave** writes `.leanctx/hotspots.json` (`hotspots-v1`) into the work
7//!   tree; it sees merges across every branch and merge request, so its
8//!   report wins whenever the file is present and valid.
9//! - **git**: otherwise the report is computed here from the local history
10//!   (the last [`DEFAULT_COMMITS`] non-merge commits and the last
11//!   [`DEFAULT_MERGES`] merge commits reachable from `HEAD`).
12//!
13//! The same report drives `lean-ctx hotspots` (refactor plan, kind
14//! `hotspots.report`) and the short hint a `ctx_read` / `ctx_compose` reply
15//! carries for a hotspot file. Everything is a function of the history, the
16//! work tree and the Weave file: no timestamps or counters (#498).
17
18use std::collections::{HashMap, HashSet};
19use std::io::Read;
20use std::path::{Path, PathBuf};
21use std::sync::{Arc, LazyLock};
22use std::time::{Duration, Instant, SystemTime};
23
24use serde::Serialize;
25use serde_json::Value;
26use tokio::sync::RwLock;
27
28use crate::core::bounded_lock;
29
30#[cfg(test)]
31mod tests;
32
33/// The report format both producers write.
34pub const SCHEMA: &str = "hotspots-v1";
35/// Where Weave puts its report, relative to the work tree root.
36pub const WEAVE_FILE: &str = ".leanctx/hotspots.json";
37/// The stable first line of every hint suffix (#498).
38pub const HINT_HEADER: &str = "--- Hotspot ---";
39/// A file is named in a read hint from this score on.
40pub const HINT_MIN_SCORE: u32 = 50;
41/// Non-merge commits a local report reads.
42pub const DEFAULT_COMMITS: usize = 1000;
43/// Merge commits a local report reads (combined diffs are costly).
44pub const DEFAULT_MERGES: usize = 200;
45/// A file needs at least this many commits to be a local hotspot.
46pub const MIN_CHURN: u32 = 3;
47/// Entries a report lists by default, and at most.
48pub const DEFAULT_LIMIT: usize = 20;
49pub const MAX_LIMIT: usize = 200;
50/// The largest Weave file read, and the most entries kept from it.
51const MAX_WEAVE_BYTES: u64 = 1024 * 1024;
52const MAX_WEAVE_ENTRIES: usize = 2000;
53/// Longest `refactor_hint`, `repo` and `path` kept.
54const MAX_HINT_CHARS: usize = 200;
55const MAX_REPO_CHARS: usize = 200;
56const MAX_PATH_CHARS: usize = 512;
57/// Files a compose hint names at most.
58const MAX_SUFFIX_FILES: usize = 8;
59/// A file larger than this is not sized (and not listed).
60const MAX_SIZED_BYTES: u64 = 16 * 1024 * 1024;
61/// The size from which a split is planned, and the merge changes from
62/// which isolating the regions parallel branches both edit is.
63const SPLIT_LINES: u32 = 800;
64const CONFLICT_ACTION_MIN: u32 = 2;
65/// A cached local report is recomputed for a new `HEAD` at most this often.
66const RECOMPUTE_INTERVAL: Duration = Duration::from_secs(600);
67/// The longest a history read may take before it is given up.
68const GIT_TIMEOUT: Duration = Duration::from_secs(30);
69/// Longest a read waits for `git rev-parse HEAD` before it skips the hint.
70const HEAD_TIMEOUT: Duration = Duration::from_secs(2);
71/// How long a looked-up `HEAD` is reused before git runs again.
72const HEAD_TTL: Duration = Duration::from_secs(10);
73/// The hint caches are held for a map lookup or insert only; a wait this
74/// long means something is wrong, and the read goes without a hint.
75const LOCK_BUDGET: Duration = Duration::from_millis(200);
76/// From this score a hint names the band `75–100`, below it `50–74`.
77const HIGH_BAND: u32 = 75;
78
79/// Lockfiles change with every dependency bump; they are no refactor target.
80const LOCKFILES: &[&str] = &[
81    "Cargo.lock",
82    "package-lock.json",
83    "pnpm-lock.yaml",
84    "yarn.lock",
85    "go.sum",
86    "poetry.lock",
87    "composer.lock",
88    "Gemfile.lock",
89    "uv.lock",
90    "bun.lockb",
91];
92
93/// One file of a `hotspots-v1` report.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
95pub struct Entry {
96    /// Relative to the work tree root, forward slashes.
97    pub path: String,
98    /// Commits that changed the file.
99    pub churn: u32,
100    /// Merges that changed the file relative to every parent (the field
101    /// keeps its `hotspots-v1` name; not every one was a textual conflict).
102    pub conflicts: u32,
103    /// Revert commits that changed the file: subject `Revert "<title>"`
104    /// and a body line `This reverts commit <sha>.` (see `is_revert`).
105    pub reverts: u32,
106    /// Lines of the file.
107    pub size: u32,
108    /// 0–100; 100 is the report's hottest file.
109    pub score: u32,
110    /// One short refactor suggestion, or `null`.
111    pub refactor_hint: Option<String>,
112}
113
114/// A `hotspots-v1` report.
115#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
116pub struct Report {
117    pub schema: &'static str,
118    /// The repository as its producer names it (Weave: the project path; a
119    /// local report: the work tree's directory name), or `null`.
120    pub repo: Option<String>,
121    /// The commit the report was computed from, or `null`.
122    pub generated_from: Option<String>,
123    /// Hottest first: score, then path.
124    pub entries: Vec<Entry>,
125}
126
127/// Which producer a report came from.
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
129#[serde(rename_all = "lowercase")]
130pub enum Source {
131    Git,
132    Weave,
133}
134
135/// The state of the Weave file when a report was loaded.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum WeaveFile {
138    Absent,
139    Used,
140    /// Present but not a `hotspots-v1` report; the reason is fixed text.
141    Invalid(String),
142}
143
144impl WeaveFile {
145    pub fn as_str(&self) -> &'static str {
146        match self {
147            Self::Absent => "absent",
148            Self::Used => "used",
149            Self::Invalid(_) => "invalid",
150        }
151    }
152}
153
154/// How much local history a git report reads.
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
156pub struct Window {
157    pub commits: usize,
158    pub merges: usize,
159}
160
161impl Default for Window {
162    fn default() -> Self {
163        Self {
164            commits: DEFAULT_COMMITS,
165            merges: DEFAULT_MERGES,
166        }
167    }
168}
169
170/// A report with where it came from.
171#[derive(Debug, Clone)]
172pub struct Loaded {
173    pub root: PathBuf,
174    pub source: Source,
175    pub weave_file: WeaveFile,
176    /// The history read; `None` for a Weave report.
177    pub window: Option<Window>,
178    pub report: Report,
179}
180
181/// One step of a file's refactor plan.
182#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
183pub struct Action {
184    /// `split_file`, `isolate_conflicts`, `add_regression_tests` or
185    /// `keep_changes_small`.
186    pub action: &'static str,
187    pub reason: String,
188}
189
190/// The refactor plan of `entry`, most important step first: derived from its
191/// numbers only, so a Weave and a local report plan alike.
192pub fn plan_for(entry: &Entry) -> Vec<Action> {
193    let mut plan = Vec::new();
194    if entry.conflicts >= CONFLICT_ACTION_MIN {
195        plan.push(Action {
196            action: "isolate_conflicts",
197            reason: format!(
198                "{} merges changed it against every parent: move the regions parallel \
199                 branches both edit (registration lists, match arms, shared tables) into \
200                 separate files",
201                entry.conflicts
202            ),
203        });
204    }
205    if entry.reverts > 0 {
206        plan.push(Action {
207            action: "add_regression_tests",
208            reason: format!(
209                "{} {}: cover the reverted behaviour with tests before the next change",
210                entry.reverts,
211                plural(entry.reverts, "revert", "reverts")
212            ),
213        });
214    }
215    if entry.size >= SPLIT_LINES {
216        plan.push(Action {
217            action: "split_file",
218            reason: format!(
219                "{} lines: split it along its responsibilities so a change touches a smaller file",
220                entry.size
221            ),
222        });
223    }
224    if plan.is_empty() {
225        plan.push(Action {
226            action: "keep_changes_small",
227            reason: format!(
228                "{} commits: changed often; keep each change small and covered by tests",
229                entry.churn
230            ),
231        });
232    }
233    plan
234}
235
236fn plural<'a>(n: u32, one: &'a str, many: &'a str) -> &'a str {
237    if n == 1 { one } else { many }
238}
239
240/// The nearest ancestor of `path` (itself included) that holds `.git`.
241pub fn repo_root(path: &Path) -> Option<PathBuf> {
242    let start = if path.is_dir() { path } else { path.parent()? };
243    start
244        .ancestors()
245        .find(|dir| dir.join(".git").exists())
246        .map(Path::to_path_buf)
247}
248
249// ---------------------------------------------------------------------------
250// Local report from git history
251// ---------------------------------------------------------------------------
252
253/// Run `git <args>` in `root`: no shell, no prompt, no system config, no
254/// fsmonitor hook, external diff or lazy fetch, at most [`GIT_TIMEOUT`]. Every argument
255/// is a constant of this module or a number; the caller passes revisions
256/// after `--end-of-options`. Output is read as bytes and decoded lossily, so
257/// a commit message in another encoding cannot empty the report.
258fn git(root: &Path, args: &[&str]) -> Result<String, String> {
259    git_within(root, args, GIT_TIMEOUT)
260}
261
262/// [`git`] with its own time limit.
263fn git_within(root: &Path, args: &[&str], timeout: Duration) -> Result<String, String> {
264    use std::process::{Command, Stdio};
265    let mut child = Command::new("git")
266        .args([
267            "-c",
268            "core.quotePath=false",
269            "-c",
270            "core.fsmonitor=false",
271            "-c",
272            "diff.external=",
273            "-c",
274            "log.showSignature=false",
275            "-c",
276            "protocol.allow=never",
277        ])
278        .args(args)
279        .current_dir(root)
280        .env("GIT_CONFIG_NOSYSTEM", "1")
281        .env("GIT_TERMINAL_PROMPT", "0")
282        .env("GIT_OPTIONAL_LOCKS", "0")
283        .env("GIT_NO_LAZY_FETCH", "1")
284        .env("GIT_ASKPASS", "")
285        .env("SSH_ASKPASS", "")
286        .env_remove("GIT_EXTERNAL_DIFF")
287        .stdin(Stdio::null())
288        .stdout(Stdio::piped())
289        .stderr(Stdio::null())
290        .spawn()
291        .map_err(|_| "git could not be run".to_owned())?;
292    let mut pipe = child.stdout.take();
293    let reader = std::thread::spawn(move || {
294        let mut buf = Vec::new();
295        if let Some(p) = pipe.as_mut() {
296            let _ = p.read_to_end(&mut buf);
297        }
298        buf
299    });
300    let start = Instant::now();
301    let status = loop {
302        match child.try_wait() {
303            Ok(Some(status)) => break status,
304            Ok(None) if start.elapsed() >= timeout => {
305                let _ = child.kill();
306                let _ = child.wait();
307                let _ = reader.join();
308                return Err("git took too long to read the history".to_owned());
309            }
310            Ok(None) => std::thread::sleep(Duration::from_millis(20)),
311            Err(_) => return Err("git could not be run".to_owned()),
312        }
313    };
314    let out = reader.join().unwrap_or_default();
315    if !status.success() {
316        return Err("git could not read the history".to_owned());
317    }
318    Ok(String::from_utf8_lossy(&out).into_owned())
319}
320
321/// Per-file counts from the history.
322#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
323pub(crate) struct Counts {
324    pub churn: u32,
325    pub conflicts: u32,
326    pub reverts: u32,
327}
328
329/// The paths a `git log --name-only` line names (quoted paths are skipped).
330fn path_line(line: &str) -> Option<&str> {
331    let line = line.trim_end_matches('\r');
332    (!line.is_empty() && !line.starts_with('"')).then_some(line)
333}
334
335/// Whether a commit is a revert, in Weave's postland form (the form
336/// `git revert` writes): the subject is `Revert "<title>"` and a body line
337/// is `This reverts commit <sha>.` with a hex commit id of 7 to 64 digits.
338/// Both must hold; a subject alone does not make a revert.
339pub(crate) fn is_revert(subject: &str, body: &str) -> bool {
340    let subject = subject.trim_end_matches('\r');
341    let titled = subject
342        .strip_prefix("Revert \"")
343        .and_then(|rest| rest.strip_suffix('"'))
344        .is_some_and(|title| !title.is_empty());
345    titled
346        && body.lines().any(|line| {
347            line.trim_end_matches('\r')
348                .strip_prefix("This reverts commit ")
349                .and_then(|rest| rest.strip_suffix('.'))
350                .is_some_and(|sha| {
351                    (7..=64).contains(&sha.len()) && sha.bytes().all(|b| b.is_ascii_hexdigit())
352                })
353        })
354}
355
356/// Fold `git log --no-merges --name-only --format=%x1e%s%x1f%b%x1f` into
357/// `counts`: per record the subject, the body, then the changed paths.
358pub(crate) fn fold_commits(log: &str, counts: &mut HashMap<String, Counts>) {
359    for record in log.split('\u{1e}').skip(1) {
360        let mut parts = record.splitn(3, '\u{1f}');
361        let subject = parts.next().unwrap_or_default();
362        let body = parts.next().unwrap_or_default();
363        let names = parts.next().unwrap_or_default();
364        let revert = is_revert(subject, body);
365        let mut seen: HashSet<&str> = HashSet::new();
366        for path in names.lines().filter_map(path_line) {
367            if !seen.insert(path) {
368                continue;
369            }
370            let c = counts.entry(path.to_owned()).or_default();
371            c.churn = c.churn.saturating_add(1);
372            if revert {
373                c.reverts = c.reverts.saturating_add(1);
374            }
375        }
376    }
377}
378
379/// Fold `git log --merges --cc --name-only --format=%x1e` into `counts`.
380pub(crate) fn fold_merges(log: &str, counts: &mut HashMap<String, Counts>) {
381    for record in log.split('\u{1e}').skip(1) {
382        let mut seen: HashSet<&str> = HashSet::new();
383        for path in record.lines().filter_map(path_line) {
384            if !seen.insert(path) {
385                continue;
386            }
387            let c = counts.entry(path.to_owned()).or_default();
388            c.conflicts = c.conflicts.saturating_add(1);
389        }
390    }
391}
392
393fn is_lockfile(path: &str) -> bool {
394    let name = path.rsplit('/').next().unwrap_or(path);
395    LOCKFILES.contains(&name)
396        || Path::new(name)
397            .extension()
398            .is_some_and(|ext| ext.eq_ignore_ascii_case("lock"))
399}
400
401/// Lines of the text file `rel` under `root`; `None` for a missing, binary
402/// or very large file, a symlink, or a path that leaves `root` (`root` is
403/// canonical). Counted in chunks, never read whole.
404fn line_count(root: &Path, rel: &str) -> Option<u32> {
405    let path = root.join(rel);
406    let meta = std::fs::symlink_metadata(&path).ok()?;
407    if !meta.file_type().is_file() || meta.len() > MAX_SIZED_BYTES {
408        return None;
409    }
410    // A symlinked directory on the way must not lead out of the work tree.
411    if !std::fs::canonicalize(&path).ok()?.starts_with(root) {
412        return None;
413    }
414    let mut file = std::fs::File::open(&path).ok()?;
415    let mut buf = [0u8; 8192];
416    let (mut newlines, mut last, mut first) = (0usize, None, true);
417    loop {
418        let n = file.read(&mut buf).ok()?;
419        if n == 0 {
420            break;
421        }
422        let chunk = &buf[..n];
423        if first && chunk.contains(&0) {
424            return None;
425        }
426        first = false;
427        newlines += bytecount::count(chunk, b'\n');
428        last = chunk.last().copied();
429    }
430    let lines = newlines + usize::from(last.is_some_and(|b| b != b'\n'));
431    Some(u32::try_from(lines).unwrap_or(u32::MAX))
432}
433
434/// The raw weight of a file: `churn × (1 + conflicts + reverts) × ⌊log2(size + 2)⌋ + 1`,
435/// in integers so every platform ranks alike.
436pub(crate) fn weight(c: Counts, size: u32) -> u64 {
437    let size_factor = u64::from((u64::from(size) + 2).ilog2() + 1);
438    u64::from(c.churn) * (1 + u64::from(c.conflicts) + u64::from(c.reverts)) * size_factor
439}
440
441/// Entries of `counts` for files that exist under `root` now, sorted hottest
442/// first, at most `limit`, each scored against the hottest *emitted* entry:
443/// a file left out (deleted, binary, a lockfile, past `limit`) never sets the
444/// scale, so it cannot push the others below [`HINT_MIN_SCORE`].
445pub(crate) fn rank(root: &Path, counts: &HashMap<String, Counts>, limit: usize) -> Vec<Entry> {
446    let Ok(root) = std::fs::canonicalize(root) else {
447        return Vec::new();
448    };
449    let mut rows: Vec<(u64, Entry)> = counts
450        .iter()
451        .filter(|(path, c)| {
452            c.churn >= MIN_CHURN && !is_lockfile(path) && !path.starts_with(".leanctx/")
453        })
454        .filter_map(|(path, c)| {
455            let size = line_count(&root, path)?;
456            Some((
457                weight(*c, size),
458                Entry {
459                    path: path.clone(),
460                    churn: c.churn,
461                    conflicts: c.conflicts,
462                    reverts: c.reverts,
463                    size,
464                    score: 0,
465                    refactor_hint: None,
466                },
467            ))
468        })
469        .collect();
470    rows.sort_by(|(wa, a), (wb, b)| wb.cmp(wa).then_with(|| a.path.cmp(&b.path)));
471    rows.truncate(limit);
472    let max = rows.iter().map(|(w, _)| *w).max().unwrap_or(0).max(1);
473    rows.into_iter()
474        .map(|(w, mut e)| {
475            let score = (w * 100 + max / 2) / max;
476            e.score = u32::try_from(score).unwrap_or(100).clamp(1, 100);
477            e.refactor_hint = plan_for(&e).first().map(|a| a.reason.clone());
478            e
479        })
480        .collect()
481}
482
483/// The local report of the work tree at `root`, from its git history.
484pub fn compute(root: &Path, window: Window, limit: usize) -> Result<Report, String> {
485    let commits = window.commits.clamp(1, 100_000).to_string();
486    let merges = window.merges.min(100_000).to_string();
487    let mut counts: HashMap<String, Counts> = HashMap::new();
488    let log = git(
489        root,
490        &[
491            "log",
492            "--no-merges",
493            "--name-only",
494            "--no-ext-diff",
495            "--no-textconv",
496            "--format=%x1e%s%x1f%b%x1f",
497            "-n",
498            &commits,
499            "--end-of-options",
500            "HEAD",
501            "--",
502        ],
503    )?;
504    fold_commits(&log, &mut counts);
505    if window.merges > 0 {
506        let log = git(
507            root,
508            &[
509                "log",
510                "--merges",
511                "--cc",
512                "--name-only",
513                "--no-ext-diff",
514                "--no-textconv",
515                "--format=%x1e",
516                "-n",
517                &merges,
518                "--end-of-options",
519                "HEAD",
520                "--",
521            ],
522        )?;
523        fold_merges(&log, &mut counts);
524    }
525    let head = git(root, &["rev-parse", "--verify", "--end-of-options", "HEAD"]).ok();
526    Ok(Report {
527        schema: SCHEMA,
528        repo: root
529            .file_name()
530            .map(|n| clean_text(&n.to_string_lossy(), MAX_REPO_CHARS)),
531        generated_from: head.as_deref().map(str::trim).and_then(commit_id),
532        entries: rank(root, &counts, limit.clamp(1, MAX_LIMIT)),
533    })
534}
535
536// ---------------------------------------------------------------------------
537// Weave report (`.leanctx/hotspots.json`)
538// ---------------------------------------------------------------------------
539
540/// Characters that reorder or hide text (bidi controls, zero-width marks).
541fn is_invisible(c: char) -> bool {
542    matches!(
543        c,
544        '\u{061c}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}'
545    )
546}
547
548/// Control characters become spaces and bidi or zero-width characters are
549/// dropped; cut to `max` chars on a char boundary.
550pub(crate) fn clean_text(text: &str, max: usize) -> String {
551    let cleaned: String = text
552        .chars()
553        .filter(|c| !is_invisible(*c))
554        .map(|c| if c.is_control() { ' ' } else { c })
555        .collect();
556    let cleaned = cleaned.trim();
557    if cleaned.chars().count() <= max {
558        return cleaned.to_owned();
559    }
560    let cut: String = cleaned.chars().take(max.saturating_sub(1)).collect();
561    format!("{cut}…")
562}
563
564/// A 40- or 64-hex commit id, lowercased.
565fn commit_id(text: &str) -> Option<String> {
566    let ok = matches!(text.len(), 40 | 64) && text.bytes().all(|b| b.is_ascii_hexdigit());
567    ok.then(|| text.to_ascii_lowercase())
568}
569
570/// A relative path inside the work tree, forward slashes, no `..`.
571fn safe_path(text: &str) -> Option<String> {
572    let ok = !text.is_empty()
573        && text.chars().count() <= MAX_PATH_CHARS
574        && !text.starts_with('/')
575        && !text.contains('\\')
576        && !text.chars().any(char::is_control)
577        && !text.contains(':')
578        && text
579            .split('/')
580            .all(|seg| !seg.is_empty() && seg != "." && seg != "..");
581    ok.then(|| text.to_owned())
582}
583
584fn count(value: &Value) -> Option<u32> {
585    value.as_u64().and_then(|n| u32::try_from(n).ok())
586}
587
588/// One Weave entry, or `None` when it breaks the format (left out).
589fn weave_entry(value: &Value) -> Option<Entry> {
590    let path = safe_path(value.get("path")?.as_str()?)?;
591    let score = count(value.get("score")?)?;
592    if score > 100 {
593        return None;
594    }
595    let refactor_hint = match value.get("refactor_hint") {
596        None | Some(Value::Null) => None,
597        Some(Value::String(text)) => {
598            let text = clean_text(text, MAX_HINT_CHARS);
599            (!text.is_empty()).then_some(text)
600        }
601        Some(_) => return None,
602    };
603    Some(Entry {
604        path,
605        churn: count(value.get("churn")?)?,
606        conflicts: count(value.get("conflicts")?)?,
607        reverts: count(value.get("reverts")?)?,
608        size: count(value.get("size")?)?,
609        score,
610        refactor_hint,
611    })
612}
613
614/// A Weave report from its file text. Checked, not repaired: another
615/// `schema` or `entries` that is not a list refuses the file; an entry that
616/// breaks the format, or repeats a path, is left out.
617pub fn parse_weave(text: &str) -> Result<Report, String> {
618    let value: Value = serde_json::from_str(text).map_err(|_| "the file is not JSON".to_owned())?;
619    if value.get("schema").and_then(Value::as_str) != Some(SCHEMA) {
620        return Err(format!("the file is not a {SCHEMA} report"));
621    }
622    let entries = value
623        .get("entries")
624        .and_then(Value::as_array)
625        .ok_or_else(|| "the report has no entries list".to_owned())?;
626    let repo = value
627        .get("repo")
628        .and_then(Value::as_str)
629        .map(|r| clean_text(r, MAX_REPO_CHARS))
630        .filter(|r| !r.is_empty());
631    let generated_from = value
632        .get("generated_from")
633        .and_then(Value::as_str)
634        .and_then(commit_id);
635    let mut seen: HashSet<String> = HashSet::new();
636    let mut kept: Vec<Entry> = entries
637        .iter()
638        .filter_map(weave_entry)
639        .filter(|e| seen.insert(e.path.clone()))
640        .take(MAX_WEAVE_ENTRIES)
641        .collect();
642    kept.sort_by(|a, b| b.score.cmp(&a.score).then_with(|| a.path.cmp(&b.path)));
643    Ok(Report {
644        schema: SCHEMA,
645        repo,
646        generated_from,
647        entries: kept,
648    })
649}
650
651/// The Weave file of `root`: absent, a report, or invalid with its reason.
652pub fn load_weave(root: &Path) -> Result<Option<Report>, String> {
653    let path = root.join(WEAVE_FILE);
654    let Ok(meta) = std::fs::symlink_metadata(&path) else {
655        return Ok(None);
656    };
657    if !meta.is_file() {
658        return Err("the file is not a regular file".to_owned());
659    }
660    if meta.len() > MAX_WEAVE_BYTES {
661        return Err("the file is larger than 1 MiB".to_owned());
662    }
663    let text = std::fs::read_to_string(&path).map_err(|_| "the file is not UTF-8".to_owned())?;
664    parse_weave(&text).map(Some)
665}
666
667/// The report for the work tree at `root`: Weave's when its file is valid,
668/// else computed from the git history; at most `limit` entries.
669pub fn load(root: &Path, window: Window, limit: usize) -> Result<Loaded, String> {
670    let limit = limit.clamp(1, MAX_LIMIT);
671    let weave_file = match load_weave(root) {
672        Ok(Some(mut report)) => {
673            report.entries.truncate(limit);
674            return Ok(Loaded {
675                root: root.to_path_buf(),
676                source: Source::Weave,
677                weave_file: WeaveFile::Used,
678                window: None,
679                report,
680            });
681        }
682        Ok(None) => WeaveFile::Absent,
683        Err(reason) => WeaveFile::Invalid(reason),
684    };
685    if !root.join(".git").exists() {
686        return Err("the project is not a git work tree".to_owned());
687    }
688    Ok(Loaded {
689        root: root.to_path_buf(),
690        source: Source::Git,
691        weave_file,
692        window: Some(window),
693        report: compute(root, window, limit)?,
694    })
695}
696
697// ---------------------------------------------------------------------------
698// Read hints
699// ---------------------------------------------------------------------------
700
701/// The hint line of `entry`: its path, its score band and the ids of its
702/// planned actions. Exact counts and the repo's `refactor_hint` stay out:
703/// the line changes only when the band or the plan does, not with every
704/// commit (#498), and no text from the repository reaches a read.
705pub fn hint_line(entry: &Entry) -> String {
706    let band = if entry.score >= HIGH_BAND {
707        "75–100"
708    } else {
709        "50–74"
710    };
711    let actions: Vec<&str> = plan_for(entry).iter().map(|a| a.action).collect();
712    format!(
713        "{}: hotspot, score {band}; plan: {}",
714        entry.path,
715        actions.join(", ")
716    )
717}
718
719/// The suffix naming the hotspots among `rel_paths` (deduplicated, in the
720/// report's order): empty when none scores [`HINT_MIN_SCORE`] or more.
721pub fn suffix_for_paths(report: &Report, rel_paths: &[&str]) -> String {
722    let hits: Vec<&Entry> = report
723        .entries
724        .iter()
725        .filter(|e| e.score >= HINT_MIN_SCORE && rel_paths.contains(&e.path.as_str()))
726        .take(MAX_SUFFIX_FILES)
727        .collect();
728    if hits.is_empty() {
729        return String::new();
730    }
731    let lines: Vec<String> = hits.into_iter().map(hint_line).collect();
732    format!(
733        "\n\n{HINT_HEADER}\n{}\nRefactor plan: lean-ctx hotspots",
734        lines.join("\n")
735    )
736}
737
738#[derive(Default)]
739struct Slot {
740    /// The `HEAD` the last attempt ran for, successful or not.
741    head: Option<String>,
742    report: Option<Arc<Report>>,
743    /// When the last attempt finished; a failed one throttles too.
744    attempted_at: Option<Instant>,
745    computing: bool,
746    /// The last `HEAD` looked up for reads, and when.
747    seen_head: Option<(Option<String>, Instant)>,
748}
749
750struct WeaveSlot {
751    stamp: (u64, Option<SystemTime>),
752    report: Option<Arc<Report>>,
753}
754
755type Slots<T> = LazyLock<Arc<RwLock<HashMap<PathBuf, T>>>>;
756static GIT_SLOTS: Slots<Slot> = LazyLock::new(|| Arc::new(RwLock::new(HashMap::new())));
757static WEAVE_SLOTS: Slots<WeaveSlot> = LazyLock::new(|| Arc::new(RwLock::new(HashMap::new())));
758
759/// Weave's report of `root`, read again only when the file changed. The
760/// file is read and parsed outside the lock.
761fn cached_weave(root: &Path) -> Option<Arc<Report>> {
762    let meta = std::fs::symlink_metadata(root.join(WEAVE_FILE)).ok()?;
763    let stamp = (meta.len(), meta.modified().ok());
764    {
765        let slots = bounded_lock::read_for(&WEAVE_SLOTS, "hotspot weave cache", LOCK_BUDGET)?;
766        if let Some(slot) = slots.get(root)
767            && slot.stamp == stamp
768        {
769            return slot.report.clone();
770        }
771    }
772    let report = load_weave(root).ok().flatten().map(Arc::new);
773    if let Some(mut slots) =
774        bounded_lock::write_for(&WEAVE_SLOTS, "hotspot weave cache", LOCK_BUDGET)
775    {
776        slots.insert(
777            root.to_path_buf(),
778            WeaveSlot {
779                stamp,
780                report: report.clone(),
781            },
782        );
783    }
784    report
785}
786
787/// Whether `slot` needs no new attempt for `head`: one already ran for this
788/// `HEAD` (even a failed one), or the last finished within
789/// [`RECOMPUTE_INTERVAL`].
790fn settled(slot: &Slot, head: Option<&String>) -> bool {
791    slot.computing
792        || slot
793            .attempted_at
794            .is_some_and(|at| slot.head.as_ref() == head || at.elapsed() < RECOMPUTE_INTERVAL)
795}
796
797/// The local report of `root` for hints: the last one computed, refreshed on
798/// a background thread when `HEAD` moved (at most every
799/// [`RECOMPUTE_INTERVAL`], failures included). `None` until the first one
800/// is ready. git runs outside the lock.
801fn cached_git(root: &Path) -> Option<Arc<Report>> {
802    let recent = {
803        let slots = bounded_lock::read_for(&GIT_SLOTS, "hotspot git cache", LOCK_BUDGET)?;
804        slots
805            .get(root)
806            .and_then(|s| s.seen_head.clone())
807            .filter(|(_, at)| at.elapsed() < HEAD_TTL)
808    };
809    let looked_up = recent.is_none();
810    // The hardened git() with a short limit, outside the lock.
811    let head = match recent {
812        Some((head, _)) => head,
813        None => git_within(
814            root,
815            &["rev-parse", "--verify", "--end-of-options", "HEAD"],
816            HEAD_TIMEOUT,
817        )
818        .ok()
819        .map(|h| h.trim().to_owned()),
820    };
821    let mut slots = bounded_lock::write_for(&GIT_SLOTS, "hotspot git cache", LOCK_BUDGET)?;
822    let slot = slots.entry(root.to_path_buf()).or_default();
823    if looked_up {
824        slot.seen_head = Some((head.clone(), Instant::now()));
825    }
826    if !settled(slot, head.as_ref()) {
827        slot.computing = true;
828        let owned = root.to_path_buf();
829        let attempt_head = head.clone();
830        crate::core::policy::runtime::spawn_for_project(owned.clone(), move || {
831            let report = compute(&owned, Window::default(), MAX_LIMIT).ok();
832            // A missed lock budget must not leave the slot marked as computing.
833            let mut lock = None;
834            for _ in 0..25 {
835                lock = bounded_lock::write_for(&GIT_SLOTS, "hotspot git cache", LOCK_BUDGET);
836                if lock.is_some() {
837                    break;
838                }
839            }
840            if let Some(mut slots) = lock {
841                let slot = slots.entry(owned).or_default();
842                slot.computing = false;
843                slot.attempted_at = Some(Instant::now());
844                slot.head = attempt_head;
845                if let Some(report) = report {
846                    slot.report = Some(Arc::new(report));
847                }
848            }
849        });
850    }
851    slot.report.clone()
852}
853
854/// The report hints use for the work tree at `root`.
855fn report_for_hints(root: &Path) -> Option<Arc<Report>> {
856    cached_weave(root).or_else(|| cached_git(root))
857}
858
859/// The hint suffix for a read of `file` (absolute, or relative to the
860/// process directory): empty while a gateway policy is active, outside a git
861/// work tree, or when the file is no hotspot.
862pub fn suffix_for_read(file: &str) -> String {
863    if crate::core::policy::runtime::is_active() {
864        return String::new();
865    }
866    let path = Path::new(file);
867    let Some(root) = repo_root(path) else {
868        return String::new();
869    };
870    let Some(rel) = crate::core::decisions::relative_path(&root, path) else {
871        return String::new();
872    };
873    report_for_hints(&root).map_or_else(String::new, |report| {
874        suffix_for_paths(&report, &[rel.as_str()])
875    })
876}
877
878/// The hint suffix for a `ctx_compose` answer rooted at `root`: hotspots
879/// among the files its text names.
880pub fn suffix_for_compose(root: &Path, text: &str) -> String {
881    if crate::core::policy::runtime::is_active() {
882        return String::new();
883    }
884    let Some(repo) = repo_root(root) else {
885        return String::new();
886    };
887    let named = crate::core::decisions::paths_named_in(root, text);
888    if named.is_empty() {
889        return String::new();
890    }
891    let rel: Vec<String> = named
892        .iter()
893        .filter_map(|p| crate::core::decisions::relative_path(&repo, &root.join(p)))
894        .collect();
895    let rel: Vec<&str> = rel.iter().map(String::as_str).collect();
896    report_for_hints(&repo).map_or_else(String::new, |report| suffix_for_paths(&report, &rel))
897}