lean-ctx-engine-ext 3.12.12

LeanCTX | Engine extensions: the engine modules above the core (setup, reports, graph analysis, knowledge routing, sandboxing).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
// SPDX-License-Identifier: Apache-2.0
//! Hotspots: files that change often, are changed by merges and reverted,
//! and are large (Local Read ยง39, report format `hotspots-v1`).
//!
//! A report comes from one of two producers:
//! - **Weave** writes `.leanctx/hotspots.json` (`hotspots-v1`) into the work
//!   tree; it sees merges across every branch and merge request, so its
//!   report wins whenever the file is present and valid.
//! - **git**: otherwise the report is computed here from the local history
//!   (the last [`DEFAULT_COMMITS`] non-merge commits and the last
//!   [`DEFAULT_MERGES`] merge commits reachable from `HEAD`).
//!
//! The same report drives `lean-ctx hotspots` (refactor plan, kind
//! `hotspots.report`) and the short hint a `ctx_read` / `ctx_compose` reply
//! carries for a hotspot file. Everything is a function of the history, the
//! work tree and the Weave file: no timestamps or counters (#498).

use std::collections::{HashMap, HashSet};
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock};
use std::time::{Duration, Instant, SystemTime};

use serde::Serialize;
use serde_json::Value;
use tokio::sync::RwLock;

use crate::core::bounded_lock;

#[cfg(test)]
mod tests;

/// The report format both producers write.
pub const SCHEMA: &str = "hotspots-v1";
/// Where Weave puts its report, relative to the work tree root.
pub const WEAVE_FILE: &str = ".leanctx/hotspots.json";
/// The stable first line of every hint suffix (#498).
pub const HINT_HEADER: &str = "--- Hotspot ---";
/// A file is named in a read hint from this score on.
pub const HINT_MIN_SCORE: u32 = 50;
/// Non-merge commits a local report reads.
pub const DEFAULT_COMMITS: usize = 1000;
/// Merge commits a local report reads (combined diffs are costly).
pub const DEFAULT_MERGES: usize = 200;
/// A file needs at least this many commits to be a local hotspot.
pub const MIN_CHURN: u32 = 3;
/// Entries a report lists by default, and at most.
pub const DEFAULT_LIMIT: usize = 20;
pub const MAX_LIMIT: usize = 200;
/// The largest Weave file read, and the most entries kept from it.
const MAX_WEAVE_BYTES: u64 = 1024 * 1024;
const MAX_WEAVE_ENTRIES: usize = 2000;
/// Longest `refactor_hint`, `repo` and `path` kept.
const MAX_HINT_CHARS: usize = 200;
const MAX_REPO_CHARS: usize = 200;
const MAX_PATH_CHARS: usize = 512;
/// Files a compose hint names at most.
const MAX_SUFFIX_FILES: usize = 8;
/// A file larger than this is not sized (and not listed).
const MAX_SIZED_BYTES: u64 = 16 * 1024 * 1024;
/// The size from which a split is planned, and the merge changes from
/// which isolating the regions parallel branches both edit is.
const SPLIT_LINES: u32 = 800;
const CONFLICT_ACTION_MIN: u32 = 2;
/// A cached local report is recomputed for a new `HEAD` at most this often.
const RECOMPUTE_INTERVAL: Duration = Duration::from_secs(600);
/// The longest a history read may take before it is given up.
const GIT_TIMEOUT: Duration = Duration::from_secs(30);
/// Longest a read waits for `git rev-parse HEAD` before it skips the hint.
const HEAD_TIMEOUT: Duration = Duration::from_secs(2);
/// How long a looked-up `HEAD` is reused before git runs again.
const HEAD_TTL: Duration = Duration::from_secs(10);
/// The hint caches are held for a map lookup or insert only; a wait this
/// long means something is wrong, and the read goes without a hint.
const LOCK_BUDGET: Duration = Duration::from_millis(200);
/// From this score a hint names the band `75โ€“100`, below it `50โ€“74`.
const HIGH_BAND: u32 = 75;

/// Lockfiles change with every dependency bump; they are no refactor target.
const LOCKFILES: &[&str] = &[
    "Cargo.lock",
    "package-lock.json",
    "pnpm-lock.yaml",
    "yarn.lock",
    "go.sum",
    "poetry.lock",
    "composer.lock",
    "Gemfile.lock",
    "uv.lock",
    "bun.lockb",
];

/// One file of a `hotspots-v1` report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Entry {
    /// Relative to the work tree root, forward slashes.
    pub path: String,
    /// Commits that changed the file.
    pub churn: u32,
    /// Merges that changed the file relative to every parent (the field
    /// keeps its `hotspots-v1` name; not every one was a textual conflict).
    pub conflicts: u32,
    /// Revert commits that changed the file: subject `Revert "<title>"`
    /// and a body line `This reverts commit <sha>.` (see `is_revert`).
    pub reverts: u32,
    /// Lines of the file.
    pub size: u32,
    /// 0โ€“100; 100 is the report's hottest file.
    pub score: u32,
    /// One short refactor suggestion, or `null`.
    pub refactor_hint: Option<String>,
}

/// A `hotspots-v1` report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Report {
    pub schema: &'static str,
    /// The repository as its producer names it (Weave: the project path; a
    /// local report: the work tree's directory name), or `null`.
    pub repo: Option<String>,
    /// The commit the report was computed from, or `null`.
    pub generated_from: Option<String>,
    /// Hottest first: score, then path.
    pub entries: Vec<Entry>,
}

/// Which producer a report came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Source {
    Git,
    Weave,
}

/// The state of the Weave file when a report was loaded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WeaveFile {
    Absent,
    Used,
    /// Present but not a `hotspots-v1` report; the reason is fixed text.
    Invalid(String),
}

impl WeaveFile {
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Absent => "absent",
            Self::Used => "used",
            Self::Invalid(_) => "invalid",
        }
    }
}

/// How much local history a git report reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Window {
    pub commits: usize,
    pub merges: usize,
}

impl Default for Window {
    fn default() -> Self {
        Self {
            commits: DEFAULT_COMMITS,
            merges: DEFAULT_MERGES,
        }
    }
}

/// A report with where it came from.
#[derive(Debug, Clone)]
pub struct Loaded {
    pub root: PathBuf,
    pub source: Source,
    pub weave_file: WeaveFile,
    /// The history read; `None` for a Weave report.
    pub window: Option<Window>,
    pub report: Report,
}

/// One step of a file's refactor plan.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Action {
    /// `split_file`, `isolate_conflicts`, `add_regression_tests` or
    /// `keep_changes_small`.
    pub action: &'static str,
    pub reason: String,
}

/// The refactor plan of `entry`, most important step first: derived from its
/// numbers only, so a Weave and a local report plan alike.
pub fn plan_for(entry: &Entry) -> Vec<Action> {
    let mut plan = Vec::new();
    if entry.conflicts >= CONFLICT_ACTION_MIN {
        plan.push(Action {
            action: "isolate_conflicts",
            reason: format!(
                "{} merges changed it against every parent: move the regions parallel \
                 branches both edit (registration lists, match arms, shared tables) into \
                 separate files",
                entry.conflicts
            ),
        });
    }
    if entry.reverts > 0 {
        plan.push(Action {
            action: "add_regression_tests",
            reason: format!(
                "{} {}: cover the reverted behaviour with tests before the next change",
                entry.reverts,
                plural(entry.reverts, "revert", "reverts")
            ),
        });
    }
    if entry.size >= SPLIT_LINES {
        plan.push(Action {
            action: "split_file",
            reason: format!(
                "{} lines: split it along its responsibilities so a change touches a smaller file",
                entry.size
            ),
        });
    }
    if plan.is_empty() {
        plan.push(Action {
            action: "keep_changes_small",
            reason: format!(
                "{} commits: changed often; keep each change small and covered by tests",
                entry.churn
            ),
        });
    }
    plan
}

fn plural<'a>(n: u32, one: &'a str, many: &'a str) -> &'a str {
    if n == 1 { one } else { many }
}

/// The nearest ancestor of `path` (itself included) that holds `.git`.
pub fn repo_root(path: &Path) -> Option<PathBuf> {
    let start = if path.is_dir() { path } else { path.parent()? };
    start
        .ancestors()
        .find(|dir| dir.join(".git").exists())
        .map(Path::to_path_buf)
}

// ---------------------------------------------------------------------------
// Local report from git history
// ---------------------------------------------------------------------------

/// Run `git <args>` in `root`: no shell, no prompt, no system config, no
/// fsmonitor hook, external diff or lazy fetch, at most [`GIT_TIMEOUT`]. Every argument
/// is a constant of this module or a number; the caller passes revisions
/// after `--end-of-options`. Output is read as bytes and decoded lossily, so
/// a commit message in another encoding cannot empty the report.
fn git(root: &Path, args: &[&str]) -> Result<String, String> {
    git_within(root, args, GIT_TIMEOUT)
}

/// [`git`] with its own time limit.
fn git_within(root: &Path, args: &[&str], timeout: Duration) -> Result<String, String> {
    use std::process::{Command, Stdio};
    let mut child = Command::new("git")
        .args([
            "-c",
            "core.quotePath=false",
            "-c",
            "core.fsmonitor=false",
            "-c",
            "diff.external=",
            "-c",
            "log.showSignature=false",
            "-c",
            "protocol.allow=never",
        ])
        .args(args)
        .current_dir(root)
        .env("GIT_CONFIG_NOSYSTEM", "1")
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GIT_OPTIONAL_LOCKS", "0")
        .env("GIT_NO_LAZY_FETCH", "1")
        .env("GIT_ASKPASS", "")
        .env("SSH_ASKPASS", "")
        .env_remove("GIT_EXTERNAL_DIFF")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|_| "git could not be run".to_owned())?;
    let mut pipe = child.stdout.take();
    let reader = std::thread::spawn(move || {
        let mut buf = Vec::new();
        if let Some(p) = pipe.as_mut() {
            let _ = p.read_to_end(&mut buf);
        }
        buf
    });
    let start = Instant::now();
    let status = loop {
        match child.try_wait() {
            Ok(Some(status)) => break status,
            Ok(None) if start.elapsed() >= timeout => {
                let _ = child.kill();
                let _ = child.wait();
                let _ = reader.join();
                return Err("git took too long to read the history".to_owned());
            }
            Ok(None) => std::thread::sleep(Duration::from_millis(20)),
            Err(_) => return Err("git could not be run".to_owned()),
        }
    };
    let out = reader.join().unwrap_or_default();
    if !status.success() {
        return Err("git could not read the history".to_owned());
    }
    Ok(String::from_utf8_lossy(&out).into_owned())
}

/// Per-file counts from the history.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Counts {
    pub churn: u32,
    pub conflicts: u32,
    pub reverts: u32,
}

/// The paths a `git log --name-only` line names (quoted paths are skipped).
fn path_line(line: &str) -> Option<&str> {
    let line = line.trim_end_matches('\r');
    (!line.is_empty() && !line.starts_with('"')).then_some(line)
}

/// Whether a commit is a revert, in Weave's postland form (the form
/// `git revert` writes): the subject is `Revert "<title>"` and a body line
/// is `This reverts commit <sha>.` with a hex commit id of 7 to 64 digits.
/// Both must hold; a subject alone does not make a revert.
pub(crate) fn is_revert(subject: &str, body: &str) -> bool {
    let subject = subject.trim_end_matches('\r');
    let titled = subject
        .strip_prefix("Revert \"")
        .and_then(|rest| rest.strip_suffix('"'))
        .is_some_and(|title| !title.is_empty());
    titled
        && body.lines().any(|line| {
            line.trim_end_matches('\r')
                .strip_prefix("This reverts commit ")
                .and_then(|rest| rest.strip_suffix('.'))
                .is_some_and(|sha| {
                    (7..=64).contains(&sha.len()) && sha.bytes().all(|b| b.is_ascii_hexdigit())
                })
        })
}

/// Fold `git log --no-merges --name-only --format=%x1e%s%x1f%b%x1f` into
/// `counts`: per record the subject, the body, then the changed paths.
pub(crate) fn fold_commits(log: &str, counts: &mut HashMap<String, Counts>) {
    for record in log.split('\u{1e}').skip(1) {
        let mut parts = record.splitn(3, '\u{1f}');
        let subject = parts.next().unwrap_or_default();
        let body = parts.next().unwrap_or_default();
        let names = parts.next().unwrap_or_default();
        let revert = is_revert(subject, body);
        let mut seen: HashSet<&str> = HashSet::new();
        for path in names.lines().filter_map(path_line) {
            if !seen.insert(path) {
                continue;
            }
            let c = counts.entry(path.to_owned()).or_default();
            c.churn = c.churn.saturating_add(1);
            if revert {
                c.reverts = c.reverts.saturating_add(1);
            }
        }
    }
}

/// Fold `git log --merges --cc --name-only --format=%x1e` into `counts`.
pub(crate) fn fold_merges(log: &str, counts: &mut HashMap<String, Counts>) {
    for record in log.split('\u{1e}').skip(1) {
        let mut seen: HashSet<&str> = HashSet::new();
        for path in record.lines().filter_map(path_line) {
            if !seen.insert(path) {
                continue;
            }
            let c = counts.entry(path.to_owned()).or_default();
            c.conflicts = c.conflicts.saturating_add(1);
        }
    }
}

fn is_lockfile(path: &str) -> bool {
    let name = path.rsplit('/').next().unwrap_or(path);
    LOCKFILES.contains(&name)
        || Path::new(name)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("lock"))
}

/// Lines of the text file `rel` under `root`; `None` for a missing, binary
/// or very large file, a symlink, or a path that leaves `root` (`root` is
/// canonical). Counted in chunks, never read whole.
fn line_count(root: &Path, rel: &str) -> Option<u32> {
    let path = root.join(rel);
    let meta = std::fs::symlink_metadata(&path).ok()?;
    if !meta.file_type().is_file() || meta.len() > MAX_SIZED_BYTES {
        return None;
    }
    // A symlinked directory on the way must not lead out of the work tree.
    if !std::fs::canonicalize(&path).ok()?.starts_with(root) {
        return None;
    }
    let mut file = std::fs::File::open(&path).ok()?;
    let mut buf = [0u8; 8192];
    let (mut newlines, mut last, mut first) = (0usize, None, true);
    loop {
        let n = file.read(&mut buf).ok()?;
        if n == 0 {
            break;
        }
        let chunk = &buf[..n];
        if first && chunk.contains(&0) {
            return None;
        }
        first = false;
        newlines += bytecount::count(chunk, b'\n');
        last = chunk.last().copied();
    }
    let lines = newlines + usize::from(last.is_some_and(|b| b != b'\n'));
    Some(u32::try_from(lines).unwrap_or(u32::MAX))
}

/// The raw weight of a file: `churn ร— (1 + conflicts + reverts) ร— โŒŠlog2(size + 2)โŒ‹ + 1`,
/// in integers so every platform ranks alike.
pub(crate) fn weight(c: Counts, size: u32) -> u64 {
    let size_factor = u64::from((u64::from(size) + 2).ilog2() + 1);
    u64::from(c.churn) * (1 + u64::from(c.conflicts) + u64::from(c.reverts)) * size_factor
}

/// Entries of `counts` for files that exist under `root` now, sorted hottest
/// first, at most `limit`, each scored against the hottest *emitted* entry:
/// a file left out (deleted, binary, a lockfile, past `limit`) never sets the
/// scale, so it cannot push the others below [`HINT_MIN_SCORE`].
pub(crate) fn rank(root: &Path, counts: &HashMap<String, Counts>, limit: usize) -> Vec<Entry> {
    let Ok(root) = std::fs::canonicalize(root) else {
        return Vec::new();
    };
    let mut rows: Vec<(u64, Entry)> = counts
        .iter()
        .filter(|(path, c)| {
            c.churn >= MIN_CHURN && !is_lockfile(path) && !path.starts_with(".leanctx/")
        })
        .filter_map(|(path, c)| {
            let size = line_count(&root, path)?;
            Some((
                weight(*c, size),
                Entry {
                    path: path.clone(),
                    churn: c.churn,
                    conflicts: c.conflicts,
                    reverts: c.reverts,
                    size,
                    score: 0,
                    refactor_hint: None,
                },
            ))
        })
        .collect();
    rows.sort_by(|(wa, a), (wb, b)| wb.cmp(wa).then_with(|| a.path.cmp(&b.path)));
    rows.truncate(limit);
    let max = rows.iter().map(|(w, _)| *w).max().unwrap_or(0).max(1);
    rows.into_iter()
        .map(|(w, mut e)| {
            let score = (w * 100 + max / 2) / max;
            e.score = u32::try_from(score).unwrap_or(100).clamp(1, 100);
            e.refactor_hint = plan_for(&e).first().map(|a| a.reason.clone());
            e
        })
        .collect()
}

/// The local report of the work tree at `root`, from its git history.
pub fn compute(root: &Path, window: Window, limit: usize) -> Result<Report, String> {
    let commits = window.commits.clamp(1, 100_000).to_string();
    let merges = window.merges.min(100_000).to_string();
    let mut counts: HashMap<String, Counts> = HashMap::new();
    let log = git(
        root,
        &[
            "log",
            "--no-merges",
            "--name-only",
            "--no-ext-diff",
            "--no-textconv",
            "--format=%x1e%s%x1f%b%x1f",
            "-n",
            &commits,
            "--end-of-options",
            "HEAD",
            "--",
        ],
    )?;
    fold_commits(&log, &mut counts);
    if window.merges > 0 {
        let log = git(
            root,
            &[
                "log",
                "--merges",
                "--cc",
                "--name-only",
                "--no-ext-diff",
                "--no-textconv",
                "--format=%x1e",
                "-n",
                &merges,
                "--end-of-options",
                "HEAD",
                "--",
            ],
        )?;
        fold_merges(&log, &mut counts);
    }
    let head = git(root, &["rev-parse", "--verify", "--end-of-options", "HEAD"]).ok();
    Ok(Report {
        schema: SCHEMA,
        repo: root
            .file_name()
            .map(|n| clean_text(&n.to_string_lossy(), MAX_REPO_CHARS)),
        generated_from: head.as_deref().map(str::trim).and_then(commit_id),
        entries: rank(root, &counts, limit.clamp(1, MAX_LIMIT)),
    })
}

// ---------------------------------------------------------------------------
// Weave report (`.leanctx/hotspots.json`)
// ---------------------------------------------------------------------------

/// Characters that reorder or hide text (bidi controls, zero-width marks).
fn is_invisible(c: char) -> bool {
    matches!(
        c,
        '\u{061c}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}'
    )
}

/// Control characters become spaces and bidi or zero-width characters are
/// dropped; cut to `max` chars on a char boundary.
pub(crate) fn clean_text(text: &str, max: usize) -> String {
    let cleaned: String = text
        .chars()
        .filter(|c| !is_invisible(*c))
        .map(|c| if c.is_control() { ' ' } else { c })
        .collect();
    let cleaned = cleaned.trim();
    if cleaned.chars().count() <= max {
        return cleaned.to_owned();
    }
    let cut: String = cleaned.chars().take(max.saturating_sub(1)).collect();
    format!("{cut}โ€ฆ")
}

/// A 40- or 64-hex commit id, lowercased.
fn commit_id(text: &str) -> Option<String> {
    let ok = matches!(text.len(), 40 | 64) && text.bytes().all(|b| b.is_ascii_hexdigit());
    ok.then(|| text.to_ascii_lowercase())
}

/// A relative path inside the work tree, forward slashes, no `..`.
fn safe_path(text: &str) -> Option<String> {
    let ok = !text.is_empty()
        && text.chars().count() <= MAX_PATH_CHARS
        && !text.starts_with('/')
        && !text.contains('\\')
        && !text.chars().any(char::is_control)
        && !text.contains(':')
        && text
            .split('/')
            .all(|seg| !seg.is_empty() && seg != "." && seg != "..");
    ok.then(|| text.to_owned())
}

fn count(value: &Value) -> Option<u32> {
    value.as_u64().and_then(|n| u32::try_from(n).ok())
}

/// One Weave entry, or `None` when it breaks the format (left out).
fn weave_entry(value: &Value) -> Option<Entry> {
    let path = safe_path(value.get("path")?.as_str()?)?;
    let score = count(value.get("score")?)?;
    if score > 100 {
        return None;
    }
    let refactor_hint = match value.get("refactor_hint") {
        None | Some(Value::Null) => None,
        Some(Value::String(text)) => {
            let text = clean_text(text, MAX_HINT_CHARS);
            (!text.is_empty()).then_some(text)
        }
        Some(_) => return None,
    };
    Some(Entry {
        path,
        churn: count(value.get("churn")?)?,
        conflicts: count(value.get("conflicts")?)?,
        reverts: count(value.get("reverts")?)?,
        size: count(value.get("size")?)?,
        score,
        refactor_hint,
    })
}

/// A Weave report from its file text. Checked, not repaired: another
/// `schema` or `entries` that is not a list refuses the file; an entry that
/// breaks the format, or repeats a path, is left out.
pub fn parse_weave(text: &str) -> Result<Report, String> {
    let value: Value = serde_json::from_str(text).map_err(|_| "the file is not JSON".to_owned())?;
    if value.get("schema").and_then(Value::as_str) != Some(SCHEMA) {
        return Err(format!("the file is not a {SCHEMA} report"));
    }
    let entries = value
        .get("entries")
        .and_then(Value::as_array)
        .ok_or_else(|| "the report has no entries list".to_owned())?;
    let repo = value
        .get("repo")
        .and_then(Value::as_str)
        .map(|r| clean_text(r, MAX_REPO_CHARS))
        .filter(|r| !r.is_empty());
    let generated_from = value
        .get("generated_from")
        .and_then(Value::as_str)
        .and_then(commit_id);
    let mut seen: HashSet<String> = HashSet::new();
    let mut kept: Vec<Entry> = entries
        .iter()
        .filter_map(weave_entry)
        .filter(|e| seen.insert(e.path.clone()))
        .take(MAX_WEAVE_ENTRIES)
        .collect();
    kept.sort_by(|a, b| b.score.cmp(&a.score).then_with(|| a.path.cmp(&b.path)));
    Ok(Report {
        schema: SCHEMA,
        repo,
        generated_from,
        entries: kept,
    })
}

/// The Weave file of `root`: absent, a report, or invalid with its reason.
pub fn load_weave(root: &Path) -> Result<Option<Report>, String> {
    let path = root.join(WEAVE_FILE);
    let Ok(meta) = std::fs::symlink_metadata(&path) else {
        return Ok(None);
    };
    if !meta.is_file() {
        return Err("the file is not a regular file".to_owned());
    }
    if meta.len() > MAX_WEAVE_BYTES {
        return Err("the file is larger than 1 MiB".to_owned());
    }
    let text = std::fs::read_to_string(&path).map_err(|_| "the file is not UTF-8".to_owned())?;
    parse_weave(&text).map(Some)
}

/// The report for the work tree at `root`: Weave's when its file is valid,
/// else computed from the git history; at most `limit` entries.
pub fn load(root: &Path, window: Window, limit: usize) -> Result<Loaded, String> {
    let limit = limit.clamp(1, MAX_LIMIT);
    let weave_file = match load_weave(root) {
        Ok(Some(mut report)) => {
            report.entries.truncate(limit);
            return Ok(Loaded {
                root: root.to_path_buf(),
                source: Source::Weave,
                weave_file: WeaveFile::Used,
                window: None,
                report,
            });
        }
        Ok(None) => WeaveFile::Absent,
        Err(reason) => WeaveFile::Invalid(reason),
    };
    if !root.join(".git").exists() {
        return Err("the project is not a git work tree".to_owned());
    }
    Ok(Loaded {
        root: root.to_path_buf(),
        source: Source::Git,
        weave_file,
        window: Some(window),
        report: compute(root, window, limit)?,
    })
}

// ---------------------------------------------------------------------------
// Read hints
// ---------------------------------------------------------------------------

/// The hint line of `entry`: its path, its score band and the ids of its
/// planned actions. Exact counts and the repo's `refactor_hint` stay out:
/// the line changes only when the band or the plan does, not with every
/// commit (#498), and no text from the repository reaches a read.
pub fn hint_line(entry: &Entry) -> String {
    let band = if entry.score >= HIGH_BAND {
        "75โ€“100"
    } else {
        "50โ€“74"
    };
    let actions: Vec<&str> = plan_for(entry).iter().map(|a| a.action).collect();
    format!(
        "{}: hotspot, score {band}; plan: {}",
        entry.path,
        actions.join(", ")
    )
}

/// The suffix naming the hotspots among `rel_paths` (deduplicated, in the
/// report's order): empty when none scores [`HINT_MIN_SCORE`] or more.
pub fn suffix_for_paths(report: &Report, rel_paths: &[&str]) -> String {
    let hits: Vec<&Entry> = report
        .entries
        .iter()
        .filter(|e| e.score >= HINT_MIN_SCORE && rel_paths.contains(&e.path.as_str()))
        .take(MAX_SUFFIX_FILES)
        .collect();
    if hits.is_empty() {
        return String::new();
    }
    let lines: Vec<String> = hits.into_iter().map(hint_line).collect();
    format!(
        "\n\n{HINT_HEADER}\n{}\nRefactor plan: lean-ctx hotspots",
        lines.join("\n")
    )
}

#[derive(Default)]
struct Slot {
    /// The `HEAD` the last attempt ran for, successful or not.
    head: Option<String>,
    report: Option<Arc<Report>>,
    /// When the last attempt finished; a failed one throttles too.
    attempted_at: Option<Instant>,
    computing: bool,
    /// The last `HEAD` looked up for reads, and when.
    seen_head: Option<(Option<String>, Instant)>,
}

struct WeaveSlot {
    stamp: (u64, Option<SystemTime>),
    report: Option<Arc<Report>>,
}

type Slots<T> = LazyLock<Arc<RwLock<HashMap<PathBuf, T>>>>;
static GIT_SLOTS: Slots<Slot> = LazyLock::new(|| Arc::new(RwLock::new(HashMap::new())));
static WEAVE_SLOTS: Slots<WeaveSlot> = LazyLock::new(|| Arc::new(RwLock::new(HashMap::new())));

/// Weave's report of `root`, read again only when the file changed. The
/// file is read and parsed outside the lock.
fn cached_weave(root: &Path) -> Option<Arc<Report>> {
    let meta = std::fs::symlink_metadata(root.join(WEAVE_FILE)).ok()?;
    let stamp = (meta.len(), meta.modified().ok());
    {
        let slots = bounded_lock::read_for(&WEAVE_SLOTS, "hotspot weave cache", LOCK_BUDGET)?;
        if let Some(slot) = slots.get(root)
            && slot.stamp == stamp
        {
            return slot.report.clone();
        }
    }
    let report = load_weave(root).ok().flatten().map(Arc::new);
    if let Some(mut slots) =
        bounded_lock::write_for(&WEAVE_SLOTS, "hotspot weave cache", LOCK_BUDGET)
    {
        slots.insert(
            root.to_path_buf(),
            WeaveSlot {
                stamp,
                report: report.clone(),
            },
        );
    }
    report
}

/// Whether `slot` needs no new attempt for `head`: one already ran for this
/// `HEAD` (even a failed one), or the last finished within
/// [`RECOMPUTE_INTERVAL`].
fn settled(slot: &Slot, head: Option<&String>) -> bool {
    slot.computing
        || slot
            .attempted_at
            .is_some_and(|at| slot.head.as_ref() == head || at.elapsed() < RECOMPUTE_INTERVAL)
}

/// The local report of `root` for hints: the last one computed, refreshed on
/// a background thread when `HEAD` moved (at most every
/// [`RECOMPUTE_INTERVAL`], failures included). `None` until the first one
/// is ready. git runs outside the lock.
fn cached_git(root: &Path) -> Option<Arc<Report>> {
    let recent = {
        let slots = bounded_lock::read_for(&GIT_SLOTS, "hotspot git cache", LOCK_BUDGET)?;
        slots
            .get(root)
            .and_then(|s| s.seen_head.clone())
            .filter(|(_, at)| at.elapsed() < HEAD_TTL)
    };
    let looked_up = recent.is_none();
    // The hardened git() with a short limit, outside the lock.
    let head = match recent {
        Some((head, _)) => head,
        None => git_within(
            root,
            &["rev-parse", "--verify", "--end-of-options", "HEAD"],
            HEAD_TIMEOUT,
        )
        .ok()
        .map(|h| h.trim().to_owned()),
    };
    let mut slots = bounded_lock::write_for(&GIT_SLOTS, "hotspot git cache", LOCK_BUDGET)?;
    let slot = slots.entry(root.to_path_buf()).or_default();
    if looked_up {
        slot.seen_head = Some((head.clone(), Instant::now()));
    }
    if !settled(slot, head.as_ref()) {
        slot.computing = true;
        let owned = root.to_path_buf();
        let attempt_head = head.clone();
        crate::core::policy::runtime::spawn_for_project(owned.clone(), move || {
            let report = compute(&owned, Window::default(), MAX_LIMIT).ok();
            // A missed lock budget must not leave the slot marked as computing.
            let mut lock = None;
            for _ in 0..25 {
                lock = bounded_lock::write_for(&GIT_SLOTS, "hotspot git cache", LOCK_BUDGET);
                if lock.is_some() {
                    break;
                }
            }
            if let Some(mut slots) = lock {
                let slot = slots.entry(owned).or_default();
                slot.computing = false;
                slot.attempted_at = Some(Instant::now());
                slot.head = attempt_head;
                if let Some(report) = report {
                    slot.report = Some(Arc::new(report));
                }
            }
        });
    }
    slot.report.clone()
}

/// The report hints use for the work tree at `root`.
fn report_for_hints(root: &Path) -> Option<Arc<Report>> {
    cached_weave(root).or_else(|| cached_git(root))
}

/// The hint suffix for a read of `file` (absolute, or relative to the
/// process directory): empty while a gateway policy is active, outside a git
/// work tree, or when the file is no hotspot.
pub fn suffix_for_read(file: &str) -> String {
    if crate::core::policy::runtime::is_active() {
        return String::new();
    }
    let path = Path::new(file);
    let Some(root) = repo_root(path) else {
        return String::new();
    };
    let Some(rel) = crate::core::decisions::relative_path(&root, path) else {
        return String::new();
    };
    report_for_hints(&root).map_or_else(String::new, |report| {
        suffix_for_paths(&report, &[rel.as_str()])
    })
}

/// The hint suffix for a `ctx_compose` answer rooted at `root`: hotspots
/// among the files its text names.
pub fn suffix_for_compose(root: &Path, text: &str) -> String {
    if crate::core::policy::runtime::is_active() {
        return String::new();
    }
    let Some(repo) = repo_root(root) else {
        return String::new();
    };
    let named = crate::core::decisions::paths_named_in(root, text);
    if named.is_empty() {
        return String::new();
    }
    let rel: Vec<String> = named
        .iter()
        .filter_map(|p| crate::core::decisions::relative_path(&repo, &root.join(p)))
        .collect();
    let rel: Vec<&str> = rel.iter().map(String::as_str).collect();
    report_for_hints(&repo).map_or_else(String::new, |report| suffix_for_paths(&report, &rel))
}