Skip to main content

lean_ctx_ext/core/
context_radar.rs

1// SPDX-License-Identifier: Apache-2.0
2use std::path::{Path, PathBuf};
3
4use serde::{Deserialize, Serialize};
5
6/// ContextRadar aggregates all context sources into a single budget model.
7/// Data flows in from: hooks (JSONL), proxy introspector, rules scanner, session cache.
8pub struct ContextRadar {
9    pub events: Vec<RadarEvent>,
10    pub rules_tokens: RulesTokens,
11    pub window_size: usize,
12}
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct RadarEvent {
16    pub ts: u64,
17    pub event_type: String,
18    pub tokens: usize,
19    #[serde(default)]
20    pub tool_name: Option<String>,
21    #[serde(default)]
22    pub detail: Option<String>,
23    #[serde(default)]
24    pub content: Option<String>,
25    #[serde(default)]
26    pub model: Option<String>,
27    #[serde(default)]
28    pub conversation_id: Option<String>,
29}
30
31#[derive(Debug, Default, Clone)]
32pub struct RulesTokens {
33    pub files: Vec<(String, usize)>,
34    pub total: usize,
35}
36
37#[derive(Debug, Serialize)]
38pub struct BudgetBreakdown {
39    pub window_size: usize,
40    pub system_prompt_tokens: usize,
41    pub user_message_tokens: usize,
42    pub agent_response_tokens: usize,
43    pub lean_ctx_tool_tokens: usize,
44    pub other_mcp_tokens: usize,
45    pub native_read_tokens: usize,
46    pub shell_tokens: usize,
47    pub thinking_tokens: usize,
48    pub tracked_total: usize,
49    pub available: usize,
50    pub compaction_count: usize,
51    pub session_total_tokens: usize,
52    pub session_user_tokens: usize,
53    pub session_agent_tokens: usize,
54    pub session_lctx_tokens: usize,
55    pub session_mcp_tokens: usize,
56    pub session_native_tokens: usize,
57    pub session_shell_tokens: usize,
58    pub session_thinking_tokens: usize,
59    pub source: String,
60}
61
62impl ContextRadar {
63    pub fn new(window_size: usize) -> Self {
64        Self {
65            events: Vec::new(),
66            rules_tokens: RulesTokens::default(),
67            window_size,
68        }
69    }
70
71    pub fn load(data_dir: &Path, window_size: usize) -> Self {
72        let mut radar = Self::new(window_size);
73        radar.load_events(data_dir);
74        radar.scan_rules();
75        radar
76    }
77
78    fn load_events(&mut self, data_dir: &Path) {
79        let mut all: Vec<RadarEvent> = Vec::new();
80
81        let prev_path = data_dir.join("context_radar.prev.jsonl");
82        if let Ok(content) = std::fs::read_to_string(&prev_path) {
83            for line in content.lines() {
84                if let Ok(ev) = serde_json::from_str::<RadarEvent>(line) {
85                    all.push(ev);
86                }
87            }
88        }
89
90        let radar_path = data_dir.join("context_radar.jsonl");
91        if let Ok(content) = std::fs::read_to_string(&radar_path) {
92            for line in content.lines() {
93                if let Ok(ev) = serde_json::from_str::<RadarEvent>(line) {
94                    all.push(ev);
95                }
96            }
97        }
98
99        const MAX_EVENTS: usize = 50_000;
100        if all.len() > MAX_EVENTS {
101            self.events = all[all.len() - MAX_EVENTS..].to_vec();
102        } else {
103            self.events = all;
104        }
105    }
106
107    pub fn scan_rules(&mut self) {
108        let Some(home) = crate::core::home::resolve_home_dir() else {
109            return;
110        };
111
112        let cwd = std::env::current_dir().unwrap_or_default();
113        let mut files: Vec<(String, usize)> = Vec::new();
114
115        let paths_to_scan: Vec<PathBuf> = vec![
116            cwd.join(".cursorrules"),
117            cwd.join("AGENTS.md"),
118            cwd.join("CLAUDE.md"),
119            cwd.join("CODEBUDDY.md"),
120            cwd.join("LEAN-CTX.md"),
121            home.join(".cursor").join("rules"),
122            home.join(".cursorrules"),
123            cwd.join(".cursor").join("rules"),
124        ];
125
126        for path in &paths_to_scan {
127            if path.is_file() {
128                if Self::is_rules_file(path)
129                    && let Ok(content) = std::fs::read_to_string(path)
130                {
131                    let tokens = content.len() / 4;
132                    if tokens > 0 {
133                        files.push((path.display().to_string(), tokens));
134                    }
135                }
136            } else if path.is_dir()
137                && let Ok(entries) = std::fs::read_dir(path)
138            {
139                for entry in entries.flatten() {
140                    let p = entry.path();
141                    if p.is_file()
142                        && Self::is_rules_file(&p)
143                        && let Ok(content) = std::fs::read_to_string(&p)
144                    {
145                        let tokens = content.len() / 4;
146                        if tokens > 0 {
147                            files.push((p.display().to_string(), tokens));
148                        }
149                    }
150                }
151            }
152        }
153
154        let total = files.iter().map(|(_, t)| *t).sum();
155        self.rules_tokens = RulesTokens { files, total };
156    }
157
158    fn is_rules_file(path: &Path) -> bool {
159        let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
160            return false;
161        };
162        if name.starts_with('.') && name != ".cursorrules" {
163            return false;
164        }
165        if name.contains(".bak") || name.contains(".tmp") || name.contains(".swp") {
166            return false;
167        }
168        if name == ".cursorrules"
169            || name == "AGENTS.md"
170            || name == "CLAUDE.md"
171            || name == "CODEBUDDY.md"
172            || name == "LEAN-CTX.md"
173        {
174            return true;
175        }
176        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
177        matches!(ext, "md" | "mdc" | "markdown" | "txt")
178    }
179
180    pub fn budget_breakdown(&self) -> BudgetBreakdown {
181        let mut compaction_count = 0;
182        let mut last_compaction_idx: Option<usize> = None;
183
184        for (i, event) in self.events.iter().enumerate() {
185            if event.event_type == "compaction" {
186                compaction_count += 1;
187                last_compaction_idx = Some(i);
188            }
189        }
190
191        let current_window_start = last_compaction_idx.map_or(0, |i| i + 1);
192        let current_events = &self.events[current_window_start..];
193
194        let (mut user_cur, mut agent_cur, mut lctx_cur, mut mcp_cur) = (0, 0, 0, 0);
195        let (mut native_cur, mut shell_cur, mut thinking_cur) = (0, 0, 0);
196        let (mut user_all, mut agent_all, mut lctx_all, mut mcp_all) = (0, 0, 0, 0);
197        let (mut native_all, mut shell_all, mut thinking_all) = (0, 0, 0);
198
199        for event in &self.events {
200            Self::classify_event(
201                event,
202                &mut user_all,
203                &mut agent_all,
204                &mut lctx_all,
205                &mut mcp_all,
206                &mut native_all,
207                &mut shell_all,
208                &mut thinking_all,
209            );
210        }
211        for event in current_events {
212            Self::classify_event(
213                event,
214                &mut user_cur,
215                &mut agent_cur,
216                &mut lctx_cur,
217                &mut mcp_cur,
218                &mut native_cur,
219                &mut shell_cur,
220                &mut thinking_cur,
221            );
222        }
223
224        let system_prompt_tokens = self.rules_tokens.total;
225        let tracked_total = system_prompt_tokens
226            + user_cur
227            + agent_cur
228            + lctx_cur
229            + mcp_cur
230            + native_cur
231            + shell_cur;
232        let available = self.window_size.saturating_sub(tracked_total);
233
234        let session_total = system_prompt_tokens
235            + user_all
236            + agent_all
237            + lctx_all
238            + mcp_all
239            + native_all
240            + shell_all;
241
242        BudgetBreakdown {
243            window_size: self.window_size,
244            system_prompt_tokens,
245            user_message_tokens: user_cur,
246            agent_response_tokens: agent_cur,
247            lean_ctx_tool_tokens: lctx_cur,
248            other_mcp_tokens: mcp_cur,
249            native_read_tokens: native_cur,
250            shell_tokens: shell_cur,
251            thinking_tokens: thinking_cur,
252            tracked_total,
253            available,
254            compaction_count,
255            session_total_tokens: session_total,
256            session_user_tokens: user_all,
257            session_agent_tokens: agent_all,
258            session_lctx_tokens: lctx_all,
259            session_mcp_tokens: mcp_all,
260            session_native_tokens: native_all,
261            session_shell_tokens: shell_all,
262            session_thinking_tokens: thinking_all,
263            source: "hooks + rules-scan".to_string(),
264        }
265    }
266
267    fn classify_event(
268        event: &RadarEvent,
269        user: &mut usize,
270        agent: &mut usize,
271        lctx: &mut usize,
272        mcp: &mut usize,
273        native: &mut usize,
274        shell: &mut usize,
275        thinking: &mut usize,
276    ) {
277        match event.event_type.as_str() {
278            "user_message" => *user += event.tokens,
279            "agent_response" => *agent += event.tokens,
280            "mcp_call" => {
281                let is_leanctx = event
282                    .detail
283                    .as_deref()
284                    .is_some_and(|d| d.contains("lean-ctx"))
285                    || event
286                        .tool_name
287                        .as_deref()
288                        .is_some_and(|t| t.starts_with("ctx_"));
289                if is_leanctx {
290                    *lctx += event.tokens;
291                } else {
292                    *mcp += event.tokens;
293                }
294            }
295            "native_tool" | "file_read" => *native += event.tokens,
296            "shell" => *shell += event.tokens,
297            "thinking" => *thinking += event.tokens,
298            _ => {}
299        }
300    }
301
302    pub fn format_display(&self) -> String {
303        let b = self.budget_breakdown();
304        let pct = |tokens: usize| -> f64 {
305            if b.window_size == 0 {
306                0.0
307            } else {
308                (tokens as f64 / b.window_size as f64 * 100.0).min(100.0)
309            }
310        };
311        let bar = |tokens: usize| -> String {
312            let width = (pct(tokens) / 2.0).min(40.0) as usize;
313            "█".repeat(width)
314        };
315
316        let mut out = String::new();
317        out.push_str(&format!(
318            "CONTEXT RADAR — Current Window ({:.0}k)\n",
319            b.window_size as f64 / 1000.0
320        ));
321        if b.compaction_count > 0 {
322            out.push_str(&format!(
323                "  (after {} compaction(s) — showing current window only)\n",
324                b.compaction_count
325            ));
326        }
327        out.push_str(&format!(
328            "  System Prompt (est.): {:>8} tok {:>5.1}%  {}\n",
329            fmt_num(b.system_prompt_tokens),
330            pct(b.system_prompt_tokens),
331            bar(b.system_prompt_tokens)
332        ));
333        out.push_str(&format!(
334            "  User Messages:        {:>8} tok {:>5.1}%  {}\n",
335            fmt_num(b.user_message_tokens),
336            pct(b.user_message_tokens),
337            bar(b.user_message_tokens)
338        ));
339        out.push_str(&format!(
340            "  Agent Responses:      {:>8} tok {:>5.1}%  {}\n",
341            fmt_num(b.agent_response_tokens),
342            pct(b.agent_response_tokens),
343            bar(b.agent_response_tokens)
344        ));
345        out.push_str(&format!(
346            "  lean-ctx Tools:       {:>8} tok {:>5.1}%  {}\n",
347            fmt_num(b.lean_ctx_tool_tokens),
348            pct(b.lean_ctx_tool_tokens),
349            bar(b.lean_ctx_tool_tokens)
350        ));
351        out.push_str(&format!(
352            "  Other MCP:            {:>8} tok {:>5.1}%  {}\n",
353            fmt_num(b.other_mcp_tokens),
354            pct(b.other_mcp_tokens),
355            bar(b.other_mcp_tokens)
356        ));
357        out.push_str(&format!(
358            "  Native Reads:         {:>8} tok {:>5.1}%  {}\n",
359            fmt_num(b.native_read_tokens),
360            pct(b.native_read_tokens),
361            bar(b.native_read_tokens)
362        ));
363        out.push_str(&format!(
364            "  Shell Output:         {:>8} tok {:>5.1}%  {}\n",
365            fmt_num(b.shell_tokens),
366            pct(b.shell_tokens),
367            bar(b.shell_tokens)
368        ));
369        out.push_str("  ──────────────────────────────────────────\n");
370        out.push_str(&format!(
371            "  TRACKED:              {:>8} tok {:>5.1}%\n",
372            fmt_num(b.tracked_total),
373            pct(b.tracked_total)
374        ));
375        out.push_str(&format!(
376            "  Available:            {:>8} tok {:>5.1}%\n",
377            fmt_num(b.available),
378            pct(b.available)
379        ));
380        if b.thinking_tokens > 0 {
381            out.push_str(&format!(
382                "  Thinking (not in window): {:>5} tok\n",
383                fmt_num(b.thinking_tokens)
384            ));
385        }
386        if b.session_total_tokens > b.tracked_total {
387            out.push_str(&format!(
388                "\n  SESSION TOTAL:        {:>8} tok (across {} compaction(s))\n",
389                fmt_num(b.session_total_tokens),
390                b.compaction_count
391            ));
392        }
393        out.push_str(&format!("  Source: {}\n", b.source));
394        out
395    }
396}
397
398fn fmt_num(n: usize) -> String {
399    if n >= 1000 {
400        format!("{},{:03}", n / 1000, n % 1000)
401    } else {
402        n.to_string()
403    }
404}
405
406/// Default context window size based on client name.
407pub fn default_window_for_client(client: &str) -> usize {
408    if let Some((_model, window)) = crate::core::host_state::load_detected_model() {
409        return window;
410    }
411    client_default_window(client)
412}
413
414fn client_default_window(client: &str) -> usize {
415    let client = client.to_lowercase();
416    if client.contains("gemini") {
417        1_000_000
418    } else if ["windsurf", "zed", "copilot"]
419        .iter()
420        .any(|name| client.contains(name))
421    {
422        128_000
423    } else {
424        200_000
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    #[test]
433    fn budget_breakdown_empty() {
434        let radar = ContextRadar::new(200_000);
435        let b = radar.budget_breakdown();
436        assert_eq!(b.window_size, 200_000);
437        assert_eq!(b.tracked_total, 0);
438        assert_eq!(b.available, 200_000);
439    }
440
441    fn ev(
442        ts: u64,
443        event_type: &str,
444        tokens: usize,
445        tool_name: Option<&str>,
446        detail: Option<&str>,
447    ) -> RadarEvent {
448        RadarEvent {
449            ts,
450            event_type: event_type.to_string(),
451            tokens,
452            tool_name: tool_name.map(String::from),
453            detail: detail.map(String::from),
454            content: None,
455            model: None,
456            conversation_id: None,
457        }
458    }
459
460    #[test]
461    fn budget_breakdown_with_events() {
462        let mut radar = ContextRadar::new(200_000);
463        radar.events.push(ev(1000, "user_message", 500, None, None));
464        radar
465            .events
466            .push(ev(1001, "agent_response", 2000, None, None));
467        radar
468            .events
469            .push(ev(1002, "shell", 300, None, Some("git status")));
470        let b = radar.budget_breakdown();
471        assert_eq!(b.user_message_tokens, 500);
472        assert_eq!(b.agent_response_tokens, 2000);
473        assert_eq!(b.shell_tokens, 300);
474        assert_eq!(b.tracked_total, 2800);
475        assert_eq!(b.available, 200_000 - 2800);
476    }
477
478    #[test]
479    fn budget_breakdown_resets_after_compaction() {
480        let mut radar = ContextRadar::new(100_000);
481        radar.events.push(ev(1, "user_message", 50_000, None, None));
482        radar.events.push(ev(2, "compaction", 0, None, None));
483        radar.events.push(ev(3, "user_message", 10_000, None, None));
484        let b = radar.budget_breakdown();
485        assert_eq!(
486            b.user_message_tokens, 10_000,
487            "only counts since compaction"
488        );
489        assert_eq!(b.available, 90_000);
490        assert_eq!(b.compaction_count, 1);
491        assert_eq!(b.session_user_tokens, 60_000, "session total includes all");
492    }
493
494    #[test]
495    fn format_display_not_empty() {
496        let radar = ContextRadar::new(200_000);
497        let display = radar.format_display();
498        assert!(display.contains("CONTEXT RADAR"));
499        assert!(display.contains("200k"));
500    }
501
502    #[test]
503    fn client_default_window_recognizes_composite_ids() {
504        assert_eq!(client_default_window("vscode-copilot"), 128_000);
505        assert_eq!(client_default_window("github-copilot/1.2"), 128_000);
506    }
507
508    #[test]
509    fn default_window_sizes() {
510        // If a detected model file exists on the system, default_window_for_client
511        // returns that model's window for all clients. Skip client-specific asserts
512        // in that case and only verify the function returns a reasonable value.
513        if crate::core::host_state::load_detected_model().is_some() {
514            let w = default_window_for_client("cursor");
515            assert!(
516                (128_000..=2_000_000).contains(&w),
517                "window {w} out of range"
518            );
519        } else {
520            assert_eq!(default_window_for_client("cursor"), 200_000);
521            assert_eq!(default_window_for_client("gemini"), 1_000_000);
522            assert_eq!(default_window_for_client("windsurf"), 128_000);
523        }
524    }
525}