Skip to main content

lean_ctx_ext/core/
pop_pruning.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::collections::{BTreeMap, BTreeSet};
3
4use crate::core::task_relevance::RelevanceScore;
5
6#[derive(Debug, Clone)]
7pub struct PopDecision {
8    pub included_modules: Vec<String>,
9    pub excluded_modules: Vec<ExcludedModule>,
10}
11
12#[derive(Debug, Clone)]
13pub struct ExcludedModule {
14    pub module: String,
15    pub candidate_files: usize,
16    pub max_relevance: f64,
17    pub reason: String,
18}
19
20pub fn decide_for_candidates(
21    task: &str,
22    project_root: &str,
23    candidates: &[&RelevanceScore],
24) -> PopDecision {
25    let task_l = task.to_lowercase();
26
27    let mut module_scores: BTreeMap<String, (usize, f64)> = BTreeMap::new(); // (count, max_score)
28    for c in candidates {
29        let m = module_for_path(&c.path, project_root);
30        let e = module_scores.entry(m).or_insert((0, 0.0));
31        e.0 += 1;
32        e.1 = e.1.max(c.score);
33    }
34
35    let mut include: BTreeSet<String> = BTreeSet::new();
36    for m in module_scores.keys() {
37        if module_explicitly_mentioned(&task_l, m) {
38            include.insert(m.clone());
39        }
40    }
41
42    if include.is_empty() {
43        for (m, (_n, max)) in &module_scores {
44            if *max >= 0.7 {
45                include.insert(m.clone());
46            }
47        }
48    }
49
50    let mut excluded = Vec::new();
51    if !include.is_empty() {
52        for (m, (count, max)) in &module_scores {
53            if include.contains(m) {
54                continue;
55            }
56            if *max >= 0.25 {
57                continue;
58            }
59            if *count <= 1 {
60                continue;
61            }
62            excluded.push(ExcludedModule {
63                module: m.clone(),
64                candidate_files: *count,
65                max_relevance: *max,
66                reason: format!("not mentioned by task, max_relevance={max:.2} (<0.25)"),
67            });
68        }
69    }
70
71    PopDecision {
72        included_modules: include.into_iter().collect(),
73        excluded_modules: excluded,
74    }
75}
76
77pub fn filter_candidates_by_pop<'a>(
78    project_root: &str,
79    candidates: &'a [&RelevanceScore],
80    pop: &PopDecision,
81) -> Vec<&'a RelevanceScore> {
82    if pop.excluded_modules.is_empty() {
83        return candidates.to_vec();
84    }
85    let excluded: BTreeSet<&str> = pop
86        .excluded_modules
87        .iter()
88        .map(|e| e.module.as_str())
89        .collect();
90    candidates
91        .iter()
92        .copied()
93        .filter(|c| {
94            let m = module_for_path(&c.path, project_root);
95            !excluded.contains(m.as_str())
96        })
97        .collect()
98}
99
100pub fn module_for_path(path: &str, project_root: &str) -> String {
101    let rel = path
102        .strip_prefix(project_root)
103        .unwrap_or(path)
104        .trim_start_matches('/')
105        .trim_start_matches('\\');
106    rel.split('/')
107        .next()
108        .filter(|s| !s.is_empty())
109        .unwrap_or(".")
110        .to_string()
111}
112
113fn module_explicitly_mentioned(task_l: &str, module: &str) -> bool {
114    if task_l.contains(module) {
115        return true;
116    }
117    match module {
118        "rust" => {
119            task_l.contains("cargo")
120                || task_l.contains("clippy")
121                || task_l.contains("rust")
122                || task_l.contains("ctx_")
123                || task_l.contains("mcp")
124        }
125        "website" => {
126            task_l.contains("website")
127                || task_l.contains("docs")
128                || task_l.contains("astro")
129                || task_l.contains("tailwind")
130                || task_l.contains("gitlab pages")
131        }
132        "packages" => {
133            task_l.contains("vscode")
134                || task_l.contains("chrome")
135                || task_l.contains("extension")
136                || task_l.contains("npm")
137                || task_l.contains("node")
138        }
139        "cloud-infra" => task_l.contains("docker") || task_l.contains("infra"),
140        _ => false,
141    }
142}
143
144#[cfg(test)]
145pub mod tests {
146    use super::*;
147
148    #[test]
149    fn pop_excludes_unmentioned_module() {
150        let root = "/repo";
151        let task = "fix rust bug in ctx_read";
152        let candidates = [
153            RelevanceScore {
154                path: "/repo/rust/src/tools/ctx_read.rs".to_string(),
155                score: 0.9,
156                recommended_mode: "full",
157            },
158            RelevanceScore {
159                path: "/repo/website/src/index.astro".to_string(),
160                score: 0.1,
161                recommended_mode: "map",
162            },
163            RelevanceScore {
164                path: "/repo/website/src/a.astro".to_string(),
165                score: 0.05,
166                recommended_mode: "map",
167            },
168        ];
169        let refs: Vec<&RelevanceScore> = candidates.iter().collect();
170        let pop = decide_for_candidates(task, root, &refs);
171        assert!(pop.included_modules.contains(&"rust".to_string()));
172        assert!(pop.excluded_modules.iter().any(|e| e.module == "website"));
173        let kept = filter_candidates_by_pop(root, &refs, &pop);
174        assert!(kept.iter().all(|c| !c.path.contains("/website/")));
175    }
176
177    #[test]
178    fn pop_keeps_website_when_task_mentions_docs() {
179        let root = "/repo";
180        let task = "update website docs";
181        let candidates = [
182            RelevanceScore {
183                path: "/repo/website/src/index.astro".to_string(),
184                score: 0.2,
185                recommended_mode: "map",
186            },
187            RelevanceScore {
188                path: "/repo/rust/src/lib.rs".to_string(),
189                score: 0.2,
190                recommended_mode: "map",
191            },
192        ];
193        let refs: Vec<&RelevanceScore> = candidates.iter().collect();
194        let pop = decide_for_candidates(task, root, &refs);
195        assert!(pop.included_modules.contains(&"website".to_string()));
196        assert!(pop.excluded_modules.is_empty());
197    }
198}