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;
pub const SCHEMA: &str = "hotspots-v1";
pub const WEAVE_FILE: &str = ".leanctx/hotspots.json";
pub const HINT_HEADER: &str = "--- Hotspot ---";
pub const HINT_MIN_SCORE: u32 = 50;
pub const DEFAULT_COMMITS: usize = 1000;
pub const DEFAULT_MERGES: usize = 200;
pub const MIN_CHURN: u32 = 3;
pub const DEFAULT_LIMIT: usize = 20;
pub const MAX_LIMIT: usize = 200;
const MAX_WEAVE_BYTES: u64 = 1024 * 1024;
const MAX_WEAVE_ENTRIES: usize = 2000;
const MAX_HINT_CHARS: usize = 200;
const MAX_REPO_CHARS: usize = 200;
const MAX_PATH_CHARS: usize = 512;
const MAX_SUFFIX_FILES: usize = 8;
const MAX_SIZED_BYTES: u64 = 16 * 1024 * 1024;
const SPLIT_LINES: u32 = 800;
const CONFLICT_ACTION_MIN: u32 = 2;
const RECOMPUTE_INTERVAL: Duration = Duration::from_secs(600);
const GIT_TIMEOUT: Duration = Duration::from_secs(30);
const HEAD_TIMEOUT: Duration = Duration::from_secs(2);
const HEAD_TTL: Duration = Duration::from_secs(10);
const LOCK_BUDGET: Duration = Duration::from_millis(200);
const HIGH_BAND: u32 = 75;
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",
];
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Entry {
pub path: String,
pub churn: u32,
pub conflicts: u32,
pub reverts: u32,
pub size: u32,
pub score: u32,
pub refactor_hint: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Report {
pub schema: &'static str,
pub repo: Option<String>,
pub generated_from: Option<String>,
pub entries: Vec<Entry>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Source {
Git,
Weave,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WeaveFile {
Absent,
Used,
Invalid(String),
}
impl WeaveFile {
pub fn as_str(&self) -> &'static str {
match self {
Self::Absent => "absent",
Self::Used => "used",
Self::Invalid(_) => "invalid",
}
}
}
#[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,
}
}
}
#[derive(Debug, Clone)]
pub struct Loaded {
pub root: PathBuf,
pub source: Source,
pub weave_file: WeaveFile,
pub window: Option<Window>,
pub report: Report,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Action {
pub action: &'static str,
pub reason: String,
}
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 }
}
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)
}
fn git(root: &Path, args: &[&str]) -> Result<String, String> {
git_within(root, args, GIT_TIMEOUT)
}
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())
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Counts {
pub churn: u32,
pub conflicts: u32,
pub reverts: u32,
}
fn path_line(line: &str) -> Option<&str> {
let line = line.trim_end_matches('\r');
(!line.is_empty() && !line.starts_with('"')).then_some(line)
}
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())
})
})
}
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);
}
}
}
}
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"))
}
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;
}
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))
}
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
}
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()
}
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)),
})
}
fn is_invisible(c: char) -> bool {
matches!(
c,
'\u{061c}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2060}'..='\u{2069}' | '\u{feff}'
)
}
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}โฆ")
}
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())
}
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())
}
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,
})
}
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,
})
}
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)
}
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)?,
})
}
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(", ")
)
}
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 {
head: Option<String>,
report: Option<Arc<Report>>,
attempted_at: Option<Instant>,
computing: bool,
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())));
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
}
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)
}
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();
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();
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()
}
fn report_for_hints(root: &Path) -> Option<Arc<Report>> {
cached_weave(root).or_else(|| cached_git(root))
}
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()])
})
}
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))
}