1use 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
33pub const SCHEMA: &str = "hotspots-v1";
35pub const WEAVE_FILE: &str = ".leanctx/hotspots.json";
37pub const HINT_HEADER: &str = "--- Hotspot ---";
39pub const HINT_MIN_SCORE: u32 = 50;
41pub const DEFAULT_COMMITS: usize = 1000;
43pub const DEFAULT_MERGES: usize = 200;
45pub const MIN_CHURN: u32 = 3;
47pub const DEFAULT_LIMIT: usize = 20;
49pub const MAX_LIMIT: usize = 200;
50const MAX_WEAVE_BYTES: u64 = 1024 * 1024;
52const MAX_WEAVE_ENTRIES: usize = 2000;
53const MAX_HINT_CHARS: usize = 200;
55const MAX_REPO_CHARS: usize = 200;
56const MAX_PATH_CHARS: usize = 512;
57const MAX_SUFFIX_FILES: usize = 8;
59const MAX_SIZED_BYTES: u64 = 16 * 1024 * 1024;
61const SPLIT_LINES: u32 = 800;
64const CONFLICT_ACTION_MIN: u32 = 2;
65const RECOMPUTE_INTERVAL: Duration = Duration::from_secs(600);
67const GIT_TIMEOUT: Duration = Duration::from_secs(30);
69const HEAD_TIMEOUT: Duration = Duration::from_secs(2);
71const HEAD_TTL: Duration = Duration::from_secs(10);
73const LOCK_BUDGET: Duration = Duration::from_millis(200);
76const HIGH_BAND: u32 = 75;
78
79const 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#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
95pub struct Entry {
96 pub path: String,
98 pub churn: u32,
100 pub conflicts: u32,
103 pub reverts: u32,
106 pub size: u32,
108 pub score: u32,
110 pub refactor_hint: Option<String>,
112}
113
114#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
116pub struct Report {
117 pub schema: &'static str,
118 pub repo: Option<String>,
121 pub generated_from: Option<String>,
123 pub entries: Vec<Entry>,
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
129#[serde(rename_all = "lowercase")]
130pub enum Source {
131 Git,
132 Weave,
133}
134
135#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum WeaveFile {
138 Absent,
139 Used,
140 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#[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#[derive(Debug, Clone)]
172pub struct Loaded {
173 pub root: PathBuf,
174 pub source: Source,
175 pub weave_file: WeaveFile,
176 pub window: Option<Window>,
178 pub report: Report,
179}
180
181#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
183pub struct Action {
184 pub action: &'static str,
187 pub reason: String,
188}
189
190pub 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
240pub 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
249fn git(root: &Path, args: &[&str]) -> Result<String, String> {
259 git_within(root, args, GIT_TIMEOUT)
260}
261
262fn 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#[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
329fn 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
335pub(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
356pub(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
379pub(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
401fn 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 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
434pub(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
441pub(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
483pub 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
536fn 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
548pub(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
564fn 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
570fn 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
588fn 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
614pub 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
651pub 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
667pub 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
697pub 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
719pub 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 head: Option<String>,
742 report: Option<Arc<Report>>,
743 attempted_at: Option<Instant>,
745 computing: bool,
746 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
759fn 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
787fn 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
797fn 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 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 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
854fn report_for_hints(root: &Path) -> Option<Arc<Report>> {
856 cached_weave(root).or_else(|| cached_git(root))
857}
858
859pub 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
878pub 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}