Skip to main content

lean_ctx/core/
rule_scorer.rs

1//! Rule-relevance scoring (#1141): scores agent config rules against the
2//! current working context to determine which rules to inject.
3//!
4//! Uses BM25 keyword matching between rule content and active context signals
5//! (open files, recent tool calls, working directory). Rules below the relevance
6//! threshold are moved to a dormant pool and only activated on context change.
7//!
8//! Determinism (#498): same rules + same context → same scores + same selection.
9use std::collections::BTreeMap;
10
11const CHARS_PER_TOKEN: usize = 4;
12const DEFAULT_THRESHOLD: f64 = 0.15;
13
14/// A parsed agent rule with metadata.
15#[derive(Debug, Clone)]
16pub struct AgentRule {
17    pub id: String,
18    pub source_path: String,
19    pub content: String,
20    pub path_globs: Vec<String>,
21    pub tokens: usize,
22    pub keywords: Vec<String>,
23}
24
25/// Scoring result for a rule.
26#[derive(Debug, Clone)]
27pub struct ScoredRule {
28    pub rule: AgentRule,
29    pub score: f64,
30    pub injected: bool,
31}
32
33/// Context signals from the current agent session.
34#[derive(Debug, Clone, Default)]
35pub struct SessionContext {
36    pub open_files: Vec<String>,
37    pub recent_tool_calls: Vec<String>,
38    pub working_directory: String,
39    pub recent_content_keywords: Vec<String>,
40}
41
42/// Result of rule scoring and budget allocation.
43#[derive(Debug)]
44pub struct BudgetAllocation {
45    pub injected: Vec<ScoredRule>,
46    pub dormant: Vec<ScoredRule>,
47    pub total_tokens_injected: usize,
48    pub total_tokens_dormant: usize,
49    pub budget_tokens: usize,
50}
51
52/// Score and allocate rules against a token budget.
53pub fn allocate_rules(
54    rules: &[AgentRule],
55    context: &SessionContext,
56    budget_tokens: usize,
57) -> BudgetAllocation {
58    let mut scored: Vec<ScoredRule> = rules
59        .iter()
60        .map(|rule| {
61            let score = score_rule(rule, context);
62            ScoredRule {
63                rule: rule.clone(),
64                score,
65                injected: false,
66            }
67        })
68        .collect();
69
70    // Sort by score descending
71    scored.sort_by(|a, b| {
72        b.score
73            .partial_cmp(&a.score)
74            .unwrap_or(std::cmp::Ordering::Equal)
75    });
76
77    let mut remaining_budget = budget_tokens;
78    let mut injected = Vec::new();
79    let mut dormant = Vec::new();
80
81    for mut sr in scored {
82        if sr.score >= DEFAULT_THRESHOLD && sr.rule.tokens <= remaining_budget {
83            remaining_budget -= sr.rule.tokens;
84            sr.injected = true;
85            injected.push(sr);
86        } else {
87            sr.injected = false;
88            dormant.push(sr);
89        }
90    }
91
92    let total_injected: usize = injected.iter().map(|r| r.rule.tokens).sum();
93    let total_dormant: usize = dormant.iter().map(|r| r.rule.tokens).sum();
94
95    BudgetAllocation {
96        injected,
97        dormant,
98        total_tokens_injected: total_injected,
99        total_tokens_dormant: total_dormant,
100        budget_tokens,
101    }
102}
103
104/// Score a single rule against the current session context.
105fn score_rule(rule: &AgentRule, context: &SessionContext) -> f64 {
106    let path_score = score_path_match(rule, context);
107    let keyword_score = score_keyword_match(rule, context);
108    let glob_score = score_glob_match(rule, context);
109
110    // Weighted combination — path match is strongest signal
111    path_score * 0.45 + keyword_score * 0.35 + glob_score * 0.20
112}
113
114/// Score based on whether rule's path globs match currently open files.
115fn score_path_match(rule: &AgentRule, context: &SessionContext) -> f64 {
116    if rule.path_globs.is_empty() {
117        return 0.3; // no path restriction → mildly relevant everywhere
118    }
119    if context.open_files.is_empty() {
120        return 0.1;
121    }
122
123    let matches = context
124        .open_files
125        .iter()
126        .filter(|file| {
127            rule.path_globs
128                .iter()
129                .any(|glob| path_matches_glob(file, glob))
130        })
131        .count();
132
133    if matches > 0 {
134        (matches as f64 / context.open_files.len().max(1) as f64).min(1.0)
135    } else {
136        0.0
137    }
138}
139
140/// Score based on keyword overlap between rule and current context.
141fn score_keyword_match(rule: &AgentRule, context: &SessionContext) -> f64 {
142    if rule.keywords.is_empty() || context.recent_content_keywords.is_empty() {
143        return 0.0;
144    }
145
146    let rule_terms: BTreeMap<&str, usize> = {
147        let mut tf = BTreeMap::new();
148        for kw in &rule.keywords {
149            *tf.entry(kw.as_str()).or_insert(0) += 1;
150        }
151        tf
152    };
153
154    let matching = context
155        .recent_content_keywords
156        .iter()
157        .filter(|kw| rule_terms.contains_key(kw.as_str()))
158        .count();
159
160    let denominator = context
161        .recent_content_keywords
162        .len()
163        .min(rule.keywords.len())
164        .max(1);
165    (matching as f64 / denominator as f64).min(1.0)
166}
167
168/// Score based on glob patterns matching working directory.
169fn score_glob_match(rule: &AgentRule, context: &SessionContext) -> f64 {
170    if rule.path_globs.is_empty() || context.working_directory.is_empty() {
171        return 0.2; // neutral
172    }
173    if rule
174        .path_globs
175        .iter()
176        .any(|g| context.working_directory.contains(g.trim_matches('*')))
177    {
178        return 1.0;
179    }
180    0.0
181}
182
183/// Simple glob matching: supports `*` and `**` patterns.
184fn path_matches_glob(path: &str, glob: &str) -> bool {
185    if glob == "**" || glob == "*" {
186        return true;
187    }
188    // Handle **/*.ext patterns
189    if let Some(ext) = glob.strip_prefix("**/") {
190        if ext.starts_with("*.") {
191            let suffix = &ext[1..]; // .ext
192            return path.ends_with(suffix);
193        }
194        return path.contains(ext);
195    }
196    // Handle *.ext patterns
197    if let Some(ext) = glob.strip_prefix("*.") {
198        return path.ends_with(&format!(".{ext}"));
199    }
200    // Handle dir/* patterns
201    if let Some(dir) = glob.strip_suffix("/*") {
202        return path.starts_with(dir) || path.contains(&format!("/{dir}/"));
203    }
204    // Direct substring match
205    path.contains(glob)
206}
207
208/// Parse an agent rule from raw content and source path.
209pub fn parse_rule(id: &str, source_path: &str, content: &str) -> AgentRule {
210    let path_globs = extract_path_globs(content);
211    let keywords = extract_rule_keywords(content);
212    let tokens = content.len() / CHARS_PER_TOKEN;
213
214    AgentRule {
215        id: id.to_string(),
216        source_path: source_path.to_string(),
217        content: content.to_string(),
218        path_globs,
219        tokens,
220        keywords,
221    }
222}
223
224/// Extract path globs from frontmatter or content patterns.
225fn extract_path_globs(content: &str) -> Vec<String> {
226    let mut globs = Vec::new();
227
228    for line in content.lines() {
229        let trimmed = line.trim();
230        // YAML frontmatter: paths: ["*.rs", "src/**"]
231        if trimmed.starts_with("paths:") || trimmed.starts_with("globs:") {
232            let after_colon = trimmed.split_once(':').map_or("", |(_, v)| v.trim());
233            for part in after_colon
234                .trim_matches(|c| c == '[' || c == ']')
235                .split(',')
236            {
237                let cleaned = part.trim().trim_matches('"').trim_matches('\'');
238                if !cleaned.is_empty() {
239                    globs.push(cleaned.to_string());
240                }
241            }
242        }
243        // Cursor rule frontmatter: path pattern after `---`
244        if trimmed.starts_with("- ") && (trimmed.contains("*.") || trimmed.contains("**/")) {
245            let glob = trimmed.strip_prefix("- ").unwrap_or(trimmed).trim();
246            globs.push(glob.to_string());
247        }
248    }
249
250    globs
251}
252
253/// Extract meaningful keywords from rule content.
254pub fn extract_rule_keywords(content: &str) -> Vec<String> {
255    let mut tf: BTreeMap<String, usize> = BTreeMap::new();
256
257    for word in content.split(|c: char| !c.is_alphanumeric() && c != '_' && c != '-') {
258        let lower = word.to_lowercase();
259        if lower.len() >= 3 && lower.len() <= 40 && !is_common_word(&lower) {
260            *tf.entry(lower).or_insert(0) += 1;
261        }
262    }
263
264    let mut terms: Vec<(String, usize)> = tf.into_iter().collect();
265    terms.sort_by_key(|t| std::cmp::Reverse(t.1));
266    terms.truncate(30);
267    terms.into_iter().map(|(k, _)| k).collect()
268}
269
270fn is_common_word(word: &str) -> bool {
271    const COMMON: &[&str] = &[
272        "the", "and", "for", "are", "but", "not", "you", "all", "can", "had", "her", "was", "one",
273        "our", "out", "has", "his", "how", "its", "let", "may", "new", "now", "old", "see", "way",
274        "who", "this", "that", "with", "will", "been", "each", "make", "like", "from", "have",
275        "must", "should", "would", "could", "when", "then", "than", "also", "into", "only", "your",
276        "what", "more", "use", "using", "used", "file", "files", "code", "rule", "rules",
277    ];
278    COMMON.contains(&word)
279}
280
281#[cfg(test)]
282pub mod tests {
283    use super::*;
284
285    fn make_rule(id: &str, content: &str, globs: &[&str]) -> AgentRule {
286        AgentRule {
287            id: id.to_string(),
288            source_path: format!(".cursor/rules/{id}.mdc"),
289            content: content.to_string(),
290            path_globs: globs.iter().map(ToString::to_string).collect(),
291            tokens: content.len() / 4,
292            keywords: extract_rule_keywords(content),
293        }
294    }
295
296    fn make_context(files: &[&str], keywords: &[&str]) -> SessionContext {
297        SessionContext {
298            open_files: files.iter().map(ToString::to_string).collect(),
299            recent_tool_calls: vec![],
300            working_directory: "src/proxy".to_string(),
301            recent_content_keywords: keywords.iter().map(ToString::to_string).collect(),
302        }
303    }
304
305    #[test]
306    fn path_glob_matching_works() {
307        assert!(path_matches_glob("src/proxy/forward.rs", "**/*.rs"));
308        assert!(path_matches_glob("src/proxy/forward.rs", "src/proxy/*"));
309        assert!(!path_matches_glob("src/proxy/forward.rs", "**/*.ts"));
310        assert!(path_matches_glob("tests/unit.rs", "*.rs"));
311    }
312
313    #[test]
314    fn relevant_rules_score_higher() {
315        let rust_rule = make_rule(
316            "rust-conv",
317            "Use snake_case for Rust functions. Prefer Result over panic.",
318            &["**/*.rs"],
319        );
320        let ts_rule = make_rule(
321            "ts-conv",
322            "Use camelCase for TypeScript. Prefer interfaces over types.",
323            &["**/*.ts"],
324        );
325
326        let ctx = make_context(
327            &["src/proxy/forward.rs", "src/core/mod.rs"],
328            &["rust", "proxy", "forward"],
329        );
330
331        let rust_score = score_rule(&rust_rule, &ctx);
332        let ts_score = score_rule(&ts_rule, &ctx);
333
334        assert!(
335            rust_score > ts_score,
336            "Rust rule ({rust_score:.3}) should score higher than TS rule ({ts_score:.3})"
337        );
338    }
339
340    #[test]
341    fn budget_allocation_respects_limit() {
342        let rules: Vec<AgentRule> = (0..20)
343            .map(|i| {
344                make_rule(
345                    &format!("rule-{i}"),
346                    &format!("Rule content for module {i} with proxy and forward patterns"),
347                    &["**/*.rs"],
348                )
349            })
350            .collect();
351
352        let ctx = make_context(&["src/proxy/forward.rs"], &["proxy", "forward"]);
353        let result = allocate_rules(&rules, &ctx, 100);
354
355        let injected_tokens: usize = result.injected.iter().map(|r| r.rule.tokens).sum();
356        assert!(
357            injected_tokens <= 100,
358            "Injected tokens ({injected_tokens}) should be within budget (100)"
359        );
360    }
361
362    #[test]
363    fn unscoped_rules_get_mild_score() {
364        let unscoped = make_rule(
365            "general",
366            "Always respond in German. Keep responses concise.",
367            &[],
368        );
369        let ctx = make_context(&["src/proxy/forward.rs"], &["proxy"]);
370
371        let score = score_rule(&unscoped, &ctx);
372        assert!(
373            score > 0.0,
374            "Unscoped rules should get a mild baseline score"
375        );
376        assert!(score < 0.5, "But not a high score");
377    }
378
379    #[test]
380    fn scoring_is_deterministic() {
381        let rule = make_rule("test", "Proxy forward authentication tokens", &["**/*.rs"]);
382        let ctx = make_context(&["src/proxy/forward.rs"], &["proxy", "authentication"]);
383
384        let s1 = score_rule(&rule, &ctx);
385        let s2 = score_rule(&rule, &ctx);
386        assert_eq!(s1, s2);
387    }
388
389    #[test]
390    fn allocation_is_deterministic() {
391        let rules = vec![
392            make_rule("a", "Proxy rules for forward module", &["**/*.rs"]),
393            make_rule("b", "TypeScript component patterns", &["**/*.ts"]),
394            make_rule("c", "Database migration conventions", &["migrations/*"]),
395        ];
396        let ctx = make_context(&["src/proxy/forward.rs"], &["proxy", "forward"]);
397
398        let r1 = allocate_rules(&rules, &ctx, 500);
399        let r2 = allocate_rules(&rules, &ctx, 500);
400
401        assert_eq!(r1.injected.len(), r2.injected.len());
402        assert_eq!(r1.total_tokens_injected, r2.total_tokens_injected);
403    }
404
405    #[test]
406    fn parse_rule_extracts_globs_from_frontmatter() {
407        let content = "---\npaths: [\"**/*.rs\", \"src/proxy/*\"]\n---\nAlways use Result types.";
408        let rule = parse_rule("test", ".cursor/rules/test.mdc", content);
409        assert_eq!(rule.path_globs, vec!["**/*.rs", "src/proxy/*"]);
410    }
411
412    #[test]
413    fn empty_context_still_works() {
414        let rule = make_rule("test", "Some rule content here", &["**/*.rs"]);
415        let ctx = SessionContext::default();
416        let score = score_rule(&rule, &ctx);
417        assert!(score >= 0.0);
418    }
419}