Skip to main content

lean_ctx/core/
litm.rs

1use crate::core::session::SessionState;
2use crate::core::tokens::count_tokens;
3
4/// Default hard ceiling (tokens) on the re-injected ACTIVE SESSION block (#962).
5/// Generous: a true safety cap that normal sessions never hit, so default output
6/// is unchanged while a pathological session can no longer crowd out the task.
7pub const DEFAULT_ACTIVE_SESSION_BUDGET: usize = 800;
8
9/// Effective ACTIVE SESSION token budget (`LEAN_CTX_ACTIVE_SESSION_BUDGET` overrides).
10#[must_use]
11pub fn active_session_budget() -> usize {
12    std::env::var("LEAN_CTX_ACTIVE_SESSION_BUDGET")
13        .ok()
14        .and_then(|v| v.parse().ok())
15        .filter(|&n| n > 0)
16        .unwrap_or(DEFAULT_ACTIVE_SESSION_BUDGET)
17}
18
19#[derive(Debug, Clone, Copy)]
20pub struct LitmProfile {
21    pub alpha: f64,
22    pub beta: f64,
23    pub gamma: f64,
24    pub name: &'static str,
25}
26
27impl LitmProfile {
28    pub const CLAUDE: Self = Self {
29        alpha: 0.92,
30        beta: 0.50,
31        gamma: 0.88,
32        name: "claude",
33    };
34    pub const GPT: Self = Self {
35        alpha: 0.90,
36        beta: 0.55,
37        gamma: 0.85,
38        name: "gpt",
39    };
40    pub const GEMINI: Self = Self {
41        alpha: 0.88,
42        beta: 0.60,
43        gamma: 0.82,
44        name: "gemini",
45    };
46    pub const DEFAULT: Self = Self::GPT;
47
48    pub fn from_client_name(client: &str) -> Self {
49        if let Ok(override_val) = std::env::var("LEAN_CTX_LITM_PROFILE") {
50            return Self::from_name(&override_val);
51        }
52        let lower = client.to_lowercase();
53        if lower.contains("claude") || lower.contains("cursor") {
54            Self::CLAUDE
55        } else if lower.contains("gemini") {
56            Self::GEMINI
57        } else {
58            Self::GPT
59        }
60    }
61
62    pub fn from_name(name: &str) -> Self {
63        match name.to_lowercase().as_str() {
64            "claude" | "codebuddy" | "cursor" => Self::CLAUDE,
65            "gemini" => Self::GEMINI,
66            "gpt" | "openai" | "codex" => Self::GPT,
67            _ => Self::DEFAULT,
68        }
69    }
70}
71
72#[cfg(test)]
73const _ALPHA: f64 = 0.9;
74#[cfg(test)]
75const _BETA: f64 = 0.55;
76#[cfg(test)]
77const _GAMMA: f64 = 0.85;
78
79pub struct PositionedOutput {
80    pub begin_block: String,
81    pub end_block: String,
82}
83
84impl PositionedOutput {
85    /// Deterministic hard cap on the re-injected ACTIVE SESSION block (#962).
86    /// Session memory rides every turn, so an unbounded block crowds out the
87    /// user's actual task. The begin block keeps priority over the end block;
88    /// within each, the least-critical lines (rendered last) drop first.
89    pub fn enforce_token_budget(&mut self, budget: usize) {
90        self.begin_block = trim_lines_to_budget(&self.begin_block, budget);
91        let remaining = budget.saturating_sub(count_tokens(&self.begin_block));
92        self.end_block = trim_lines_to_budget(&self.end_block, remaining);
93    }
94}
95
96/// Keeps whole leading lines until the next would exceed `budget`. Deterministic.
97fn trim_lines_to_budget(block: &str, budget: usize) -> String {
98    if block.is_empty() || count_tokens(block) <= budget {
99        return block.to_string();
100    }
101    let mut kept: Vec<&str> = Vec::new();
102    let mut used = 0usize;
103    for line in block.lines() {
104        let cost = count_tokens(line);
105        if used + cost > budget {
106            break;
107        }
108        used += cost;
109        kept.push(line);
110    }
111    kept.join("\n")
112}
113
114/// Sorts session state fields by attention priority:
115///   P1 (begin): task, decisions, project topology, file refs
116///   P2 (end): recent findings, test results, next steps
117///   P3 (dropped): old completed tasks, historical reads beyond limit
118pub fn position_optimize(session: &SessionState) -> PositionedOutput {
119    position_optimize_with_share(session, crate::core::litm_calibration::DEFAULT_BEGIN_SHARE)
120}
121
122/// Calibrated variant (#539): `begin_share` < 0.6 means the begin position
123/// empirically under-performs for this client — progress moves to the end
124/// block and the task line is duplicated there (recency rescue for the most
125/// critical item). At the default share the layout is byte-identical to the
126/// uncalibrated version.
127pub fn position_optimize_with_share(session: &SessionState, begin_share: f64) -> PositionedOutput {
128    let begin_weak = begin_share < 0.6;
129    let mut begin_lines = Vec::new();
130    let mut end_lines = Vec::new();
131
132    // Stable prefix for LLM prefix-cache compatibility:
133    // project root and file refs rarely change, keeping the prefix stable.
134    if let Some(ref root) = session.project_root {
135        begin_lines.push(format!("Root: {root}"));
136    }
137
138    if let Some(ref task) = session.task {
139        let pct = task
140            .progress_pct
141            .map_or(String::new(), |p| format!(" [{p}%]"));
142        begin_lines.push(format!("Task: {}{pct}", task.description));
143    }
144
145    if !session.decisions.is_empty() {
146        let items: Vec<&str> = session
147            .decisions
148            .iter()
149            .rev()
150            .take(5)
151            .map(|d| d.summary.as_str())
152            .collect();
153        begin_lines.push(format!("Decisions: {}", items.join(" | ")));
154    }
155
156    if !session.files_touched.is_empty() {
157        let items: Vec<String> = session
158            .files_touched
159            .iter()
160            .rev()
161            .take(15)
162            .map(|f| {
163                let r = f.file_ref.as_deref().unwrap_or("?");
164                let status = if f.modified { "mod" } else { &f.last_mode };
165                let summary_hint = f
166                    .summary
167                    .as_deref()
168                    .map_or(String::new(), |s| format!(", \"{s}\""));
169                format!("{r}={} [{status}{summary_hint}]", short_path(&f.path))
170            })
171            .collect();
172        begin_lines.push(format!("Files: {}", items.join(" ")));
173    }
174
175    // Progress entries (recent work done). When the begin position is
176    // calibrated as weak (#539) this least-critical begin item moves to the
177    // end block instead.
178    if !session.progress.is_empty() {
179        let items: Vec<String> = session
180            .progress
181            .iter()
182            .rev()
183            .take(5)
184            .map(|p| {
185                p.detail
186                    .as_deref()
187                    .map_or_else(|| p.action.clone(), |d| format!("{}: {d}", p.action))
188            })
189            .collect();
190        let line = format!("Progress: {}", items.join(" | "));
191        if begin_weak {
192            end_lines.push(line);
193        } else {
194            begin_lines.push(line);
195        }
196    }
197
198    // Only findings that may be delivered now (`SessionState::finding_served`):
199    // a finding bound to a source that no longer admits is left out, and the
200    // line with it when none is left.
201    let findings: Vec<String> = session
202        .findings
203        .iter()
204        .rev()
205        .filter(|f| session.finding_served(f))
206        .take(8)
207        .map(|f| f.summary.clone())
208        .collect();
209    if !findings.is_empty() {
210        end_lines.push(format!("Findings: {}", findings.join(" | ")));
211    }
212
213    if let Some(ref tests) = session.test_results {
214        let status = if tests.failed > 0 { "FAIL" } else { "PASS" };
215        end_lines.push(format!(
216            "Tests [{status}]: {}/{} ({})",
217            tests.passed, tests.total, tests.command
218        ));
219    }
220
221    if !session.next_steps.is_empty() {
222        end_lines.push(format!("Next: {}", session.next_steps.join(" → ")));
223    }
224
225    // Recency rescue (#539): when begin is weak, repeat the task line at the
226    // end — ~10 tokens to keep the single most critical item in the strong
227    // position for this client.
228    if begin_weak && let Some(ref task) = session.task {
229        end_lines.push(format!("Task (active): {}", task.description));
230    }
231
232    // Session stats at end — changes every call, placing here preserves prefix-cache stability
233    end_lines.push(format!(
234        "ACTIVE SESSION v{} | {} calls | {} tok saved",
235        session.version, session.stats.total_tool_calls, session.stats.total_tokens_saved
236    ));
237
238    PositionedOutput {
239        begin_block: begin_lines.join("\n"),
240        end_block: end_lines.join("\n"),
241    }
242}
243
244#[cfg(test)]
245pub fn compute_litm_efficiency(
246    begin_tokens: usize,
247    middle_tokens: usize,
248    end_tokens: usize,
249    ccp_begin_tokens: usize,
250    ccp_end_tokens: usize,
251) -> (f64, f64) {
252    let total_without = (begin_tokens + middle_tokens + end_tokens) as f64;
253    let effective_without =
254        _ALPHA * begin_tokens as f64 + _BETA * middle_tokens as f64 + _GAMMA * end_tokens as f64;
255
256    let total_with = (ccp_begin_tokens + ccp_end_tokens) as f64;
257    let effective_with = _ALPHA * ccp_begin_tokens as f64 + _GAMMA * ccp_end_tokens as f64;
258
259    let eff_without = if total_without > 0.0 {
260        effective_without / total_without * 100.0
261    } else {
262        0.0
263    };
264    let eff_with = if total_with > 0.0 {
265        effective_with / total_with * 100.0
266    } else {
267        0.0
268    };
269
270    (eff_without, eff_with)
271}
272
273#[cfg(test)]
274pub fn compute_litm_efficiency_for_profile(
275    begin_tokens: usize,
276    middle_tokens: usize,
277    end_tokens: usize,
278    ccp_begin_tokens: usize,
279    ccp_end_tokens: usize,
280    profile: &LitmProfile,
281) -> (f64, f64) {
282    let total_without = (begin_tokens + middle_tokens + end_tokens) as f64;
283    let effective_without = profile.alpha * begin_tokens as f64
284        + profile.beta * middle_tokens as f64
285        + profile.gamma * end_tokens as f64;
286
287    let total_with = (ccp_begin_tokens + ccp_end_tokens) as f64;
288    let effective_with =
289        profile.alpha * ccp_begin_tokens as f64 + profile.gamma * ccp_end_tokens as f64;
290
291    let eff_without = if total_without > 0.0 {
292        effective_without / total_without * 100.0
293    } else {
294        0.0
295    };
296    let eff_with = if total_with > 0.0 {
297        effective_with / total_with * 100.0
298    } else {
299        0.0
300    };
301
302    (eff_without, eff_with)
303}
304
305fn short_path(path: &str) -> String {
306    let parts: Vec<&str> = path.split('/').collect();
307    if parts.len() <= 2 {
308        return path.to_string();
309    }
310    parts.last().copied().unwrap_or(path).to_string()
311}
312
313#[cfg(test)]
314pub mod tests {
315    use super::*;
316
317    #[test]
318    fn litm_efficiency_without_ccp_lower() {
319        let (eff_without, eff_with) = compute_litm_efficiency(100, 500, 100, 300, 200);
320        assert!(
321            eff_with > eff_without,
322            "CCP should improve LITM efficiency: without={eff_without:.1}%, with={eff_with:.1}%"
323        );
324    }
325
326    #[test]
327    fn litm_efficiency_zero_tokens() {
328        let (eff_without, eff_with) = compute_litm_efficiency(0, 0, 0, 0, 0);
329        assert_eq!(eff_without, 0.0);
330        assert_eq!(eff_with, 0.0);
331    }
332
333    #[test]
334    fn litm_all_at_begin_is_alpha() {
335        let (_, eff_with) = compute_litm_efficiency(0, 0, 0, 100, 0);
336        assert!((eff_with - 90.0).abs() < 0.1, "all begin should be ~90%");
337    }
338
339    #[test]
340    fn litm_all_at_end_is_gamma() {
341        let (_, eff_with) = compute_litm_efficiency(0, 0, 0, 0, 100);
342        assert!((eff_with - 85.0).abs() < 0.1, "all end should be ~85%");
343    }
344
345    #[test]
346    fn litm_middle_heavy_is_worst() {
347        let (eff_middle, _) = compute_litm_efficiency(10, 1000, 10, 0, 0);
348        let (eff_balanced, _) = compute_litm_efficiency(500, 20, 500, 0, 0);
349        assert!(
350            eff_balanced > eff_middle,
351            "middle-heavy should be less efficient"
352        );
353    }
354
355    #[test]
356    fn calibrated_share_moves_progress_to_end() {
357        let mut session = SessionState::new();
358        session.task = Some(crate::core::session::TaskInfo {
359            description: "fix webhook".to_string(),
360            intent: None,
361            progress_pct: None,
362        });
363        session.progress.push(crate::core::session::ProgressEntry {
364            action: "deployed billing".to_string(),
365            detail: None,
366            timestamp: chrono::Utc::now(),
367        });
368
369        let default_layout = position_optimize_with_share(&session, 0.7);
370        assert!(default_layout.begin_block.contains("Progress:"));
371        assert!(!default_layout.end_block.contains("Task (active)"));
372
373        let weak_begin = position_optimize_with_share(&session, 0.45);
374        assert!(!weak_begin.begin_block.contains("Progress:"));
375        assert!(weak_begin.end_block.contains("Progress:"));
376        assert!(weak_begin.end_block.contains("Task (active): fix webhook"));
377    }
378
379    #[test]
380    fn default_share_is_byte_identical_to_uncalibrated() {
381        let mut session = SessionState::new();
382        session.task = Some(crate::core::session::TaskInfo {
383            description: "t".to_string(),
384            intent: None,
385            progress_pct: Some(50),
386        });
387        let a = position_optimize(&session);
388        let b = position_optimize_with_share(
389            &session,
390            crate::core::litm_calibration::DEFAULT_BEGIN_SHARE,
391        );
392        assert_eq!(a.begin_block, b.begin_block);
393        assert_eq!(a.end_block, b.end_block);
394    }
395
396    #[test]
397    fn short_path_simple() {
398        assert_eq!(short_path("file.rs"), "file.rs");
399        assert_eq!(short_path("src/file.rs"), "src/file.rs");
400        assert_eq!(short_path("a/b/c/file.rs"), "file.rs");
401    }
402
403    #[test]
404    fn enforce_token_budget_caps_block_deterministically() {
405        let mut session = SessionState::new();
406        session.project_root = Some("/tmp/x".to_string());
407        session.task = Some(crate::core::session::TaskInfo {
408            description: "deploy ".repeat(200),
409            intent: None,
410            progress_pct: None,
411        });
412
413        let mut a = position_optimize(&session);
414        let before = count_tokens(&a.begin_block);
415        a.enforce_token_budget(8);
416        let after = count_tokens(&a.begin_block);
417        assert!(
418            after <= 8,
419            "begin block must respect the budget, got {after}"
420        );
421        assert!(after < before, "an oversized block must actually shrink");
422
423        let mut b = position_optimize(&session);
424        b.enforce_token_budget(8);
425        assert_eq!(
426            a.begin_block, b.begin_block,
427            "trimming must be deterministic"
428        );
429    }
430
431    #[test]
432    fn enforce_token_budget_is_noop_under_budget() {
433        let mut session = SessionState::new();
434        session.task = Some(crate::core::session::TaskInfo {
435            description: "small task".to_string(),
436            intent: None,
437            progress_pct: Some(50),
438        });
439        let mut out = position_optimize(&session);
440        let original = out.begin_block.clone();
441        out.enforce_token_budget(DEFAULT_ACTIVE_SESSION_BUDGET);
442        assert_eq!(out.begin_block, original, "a small block is left untouched");
443    }
444
445    #[test]
446    fn litm_profile_from_client_claude() {
447        let p = LitmProfile::from_client_name("Claude Desktop");
448        assert_eq!(p.name, "claude");
449        assert!((p.alpha - 0.92).abs() < f64::EPSILON);
450    }
451
452    #[test]
453    fn litm_profile_from_client_cursor() {
454        let p = LitmProfile::from_client_name("Cursor");
455        assert_eq!(p.name, "claude");
456    }
457
458    #[test]
459    fn litm_profile_from_client_gemini() {
460        let p = LitmProfile::from_client_name("Gemini CLI");
461        assert_eq!(p.name, "gemini");
462        assert!((p.beta - 0.60).abs() < f64::EPSILON);
463    }
464
465    #[test]
466    fn litm_profile_unknown_defaults_to_gpt() {
467        let p = LitmProfile::from_client_name("unknown-tool");
468        assert_eq!(p.name, "gpt");
469    }
470
471    #[test]
472    fn litm_profile_efficiency_differs_by_model() {
473        let (_, claude_eff) =
474            compute_litm_efficiency_for_profile(200, 0, 100, 200, 100, &LitmProfile::CLAUDE);
475        let (_, gemini_eff) =
476            compute_litm_efficiency_for_profile(200, 0, 100, 200, 100, &LitmProfile::GEMINI);
477        assert!(
478            (claude_eff - gemini_eff).abs() > 0.1,
479            "different profiles should yield different efficiencies"
480        );
481    }
482
483    fn with_two_findings(root: &str) -> SessionState {
484        std::fs::write(format!("{root}/pool.rs"), "pub fn lease() {}\n").expect("source");
485        let mut session = SessionState::new();
486        session.project_root = Some(root.to_owned());
487        session.add_finding_for_file(Some("pool.rs"), Some(1), "the pool leaks one lease");
488        session.add_finding_for_file(None, None, "noted without a file");
489        session
490    }
491
492    /// The injected session block shows a finding bound to a source while
493    /// the source admits and drops it — and the line, when it was the only
494    /// one — once the source is deleted. A finding without a file stays.
495    #[test]
496    fn a_finding_whose_source_is_gone_leaves_the_injected_block() {
497        use crate::core::context_admission::stored::lineage_support::{governed, project, scoped};
498        let _data = governed();
499        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
500        let (_directory, root) = project();
501        let session = with_two_findings(&root);
502        let mut bound_only = session.clone();
503        bound_only.findings.pop();
504        let end_block = |session: &SessionState| {
505            scoped(&root, || {
506                position_optimize_with_share(session, 1.0).end_block
507            })
508        };
509
510        let shown = end_block(&session);
511        assert!(
512            shown.contains("Findings: noted without a file | the pool leaks one lease\n"),
513            "{shown}"
514        );
515        assert!(end_block(&bound_only).contains("Findings: the pool leaks one lease\n"));
516
517        std::fs::remove_file(format!("{root}/pool.rs")).expect("delete");
518        let withheld = end_block(&session);
519        assert!(
520            withheld.contains("Findings: noted without a file\n"),
521            "{withheld}"
522        );
523        assert!(!withheld.contains("leaks"), "{withheld}");
524        let none = end_block(&bound_only);
525        assert!(!none.contains("Findings:"), "{none}");
526        assert!(none.starts_with("ACTIVE SESSION v"), "{none}");
527    }
528
529    /// Developer mode: the findings line is as before.
530    #[test]
531    fn findings_are_injected_as_before_in_developer_mode() {
532        use crate::core::context_admission::stored::lineage_support::project;
533        let _data = crate::core::data_dir::isolated_data_dir();
534        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
535        let (_directory, root) = project();
536        let session = with_two_findings(&root);
537        std::fs::remove_file(format!("{root}/pool.rs")).expect("delete");
538        let end_block = position_optimize_with_share(&session, 1.0).end_block;
539        assert!(
540            end_block.contains("Findings: noted without a file | the pool leaks one lease\n"),
541            "{end_block}"
542        );
543    }
544}