Skip to main content

lean_ctx/tools/
ctx_overview.rs

1use crate::core::cache::SessionCache;
2use crate::core::task_relevance::{compute_relevance, parse_task_hints};
3use crate::core::tokens::count_tokens;
4use crate::tools::CrpMode;
5
6/// Multi-resolution context overview.
7///
8/// Provides a compact map of the entire project, organized by task relevance.
9/// Files are shown at different detail levels based on their relevance score:
10/// - Level 0 (full): directly task-relevant files → full content (use ctx_read)
11/// - Level 1 (signatures): graph neighbors → key signatures
12/// - Level 2 (reference): distant files → name + line count only
13///
14/// This implements lazy evaluation for context: start with the overview,
15/// then zoom into specific files as needed.
16pub fn handle(
17    cache: &SessionCache,
18    task: Option<&str>,
19    path: Option<&str>,
20    _crp_mode: CrpMode,
21) -> String {
22    let project_root = path
23        .map(|p| p.to_string())
24        .unwrap_or_else(|| ".".to_string());
25
26    let index =
27        if let Some(idx) = crate::core::index_orchestrator::try_load_graph_index(&project_root) {
28            idx
29        } else {
30            crate::core::index_orchestrator::ensure_all_background(&project_root);
31            return format!(
32                "INDEXING IN PROGRESS\n\n\
33            The knowledge graph for this project is being built in the background.\n\
34            Project: {}\n\n\
35            Because this is a large project, the initial scan may take a moment.\n\
36            Please try this command again in 1-2 minutes.",
37                project_root
38            );
39        };
40
41    let (task_files, task_keywords) = if let Some(task_desc) = task {
42        parse_task_hints(task_desc)
43    } else {
44        (vec![], vec![])
45    };
46
47    let has_task = !task_files.is_empty() || !task_keywords.is_empty();
48
49    let mut output = Vec::new();
50
51    if has_task {
52        let relevance = compute_relevance(&index, &task_files, &task_keywords);
53
54        if let Some(task_desc) = task {
55            let file_context: Vec<(String, usize)> = relevance
56                .iter()
57                .filter(|r| r.score >= 0.3)
58                .take(8)
59                .filter_map(|r| {
60                    std::fs::read_to_string(&r.path)
61                        .ok()
62                        .map(|c| (r.path.clone(), c.lines().count()))
63                })
64                .collect();
65            let briefing = crate::core::task_briefing::build_briefing(task_desc, &file_context);
66            output.push(crate::core::task_briefing::format_briefing(&briefing));
67        }
68
69        let high: Vec<&_> = relevance.iter().filter(|r| r.score >= 0.8).collect();
70        let medium: Vec<&_> = relevance
71            .iter()
72            .filter(|r| r.score >= 0.3 && r.score < 0.8)
73            .collect();
74        let low: Vec<&_> = relevance.iter().filter(|r| r.score < 0.3).collect();
75
76        output.push(format!(
77            "PROJECT OVERVIEW  {} files  task-filtered",
78            index.files.len()
79        ));
80        output.push(String::new());
81
82        if !high.is_empty() {
83            output.push("▸ DIRECTLY RELEVANT (use ctx_read full):".to_string());
84            for r in &high {
85                let line_count = file_line_count(&r.path);
86                let ref_id = cache.get_file_ref_readonly(&r.path);
87                let ref_str = ref_id.map_or(String::new(), |r| format!("{r}="));
88                output.push(format!(
89                    "  {ref_str}{} {line_count}L  score={:.1}",
90                    short_path(&r.path),
91                    r.score
92                ));
93            }
94            output.push(String::new());
95        }
96
97        if !medium.is_empty() {
98            output.push("▸ CONTEXT (use ctx_read signatures/map):".to_string());
99            for r in medium.iter().take(20) {
100                let line_count = file_line_count(&r.path);
101                output.push(format!(
102                    "  {} {line_count}L  mode={}",
103                    short_path(&r.path),
104                    r.recommended_mode
105                ));
106            }
107            if medium.len() > 20 {
108                output.push(format!("  ... +{} more", medium.len() - 20));
109            }
110            output.push(String::new());
111        }
112
113        if !low.is_empty() {
114            output.push(format!(
115                "▸ DISTANT ({} files, not loaded unless needed)",
116                low.len()
117            ));
118            for r in low.iter().take(10) {
119                output.push(format!("  {}", short_path(&r.path)));
120            }
121            if low.len() > 10 {
122                output.push(format!("  ... +{} more", low.len() - 10));
123            }
124        }
125    } else {
126        // No task context: show project structure overview
127        output.push(format!(
128            "PROJECT OVERVIEW  {} files  {} edges",
129            index.files.len(),
130            index.edges.len()
131        ));
132        output.push(String::new());
133
134        // Group by directory
135        let mut by_dir: std::collections::BTreeMap<String, Vec<String>> =
136            std::collections::BTreeMap::new();
137
138        for file_entry in index.files.values() {
139            let dir = std::path::Path::new(&file_entry.path)
140                .parent()
141                .map(|p| p.to_string_lossy().to_string())
142                .unwrap_or_else(|| ".".to_string());
143            by_dir
144                .entry(dir)
145                .or_default()
146                .push(short_path(&file_entry.path));
147        }
148
149        for (dir, files) in &by_dir {
150            let dir_display = if dir.len() > 50 {
151                format!("...{}", &dir[dir.len() - 47..])
152            } else {
153                dir.clone()
154            };
155
156            if files.len() <= 5 {
157                output.push(format!("{dir_display}/  {}", files.join(" ")));
158            } else {
159                output.push(format!(
160                    "{dir_display}/  {} +{} more",
161                    files[..3].join(" "),
162                    files.len() - 3
163                ));
164            }
165        }
166
167        // Show top connected files (hub files)
168        output.push(String::new());
169        let mut connection_counts: std::collections::HashMap<&str, usize> =
170            std::collections::HashMap::new();
171        for edge in &index.edges {
172            *connection_counts.entry(&edge.from).or_insert(0) += 1;
173            *connection_counts.entry(&edge.to).or_insert(0) += 1;
174        }
175        let mut hubs: Vec<(&&str, &usize)> = connection_counts.iter().collect();
176        hubs.sort_by(|a, b| b.1.cmp(a.1));
177
178        if !hubs.is_empty() {
179            output.push("HUB FILES (most connected):".to_string());
180            for (path, count) in hubs.iter().take(8) {
181                output.push(format!("  {} ({count} edges)", short_path(path)));
182            }
183        }
184    }
185
186    let wakeup = build_wakeup_briefing(&project_root, task);
187    if !wakeup.is_empty() {
188        output.push(String::new());
189        output.push(wakeup);
190    }
191
192    let original = count_tokens(&format!("{} files", index.files.len())) * index.files.len();
193    let compressed = count_tokens(&output.join("\n"));
194    output.push(String::new());
195    output.push(crate::core::protocol::format_savings(original, compressed));
196
197    output.join("\n")
198}
199
200fn build_wakeup_briefing(project_root: &str, task: Option<&str>) -> String {
201    let mut parts = Vec::new();
202
203    if let Some(knowledge) = crate::core::knowledge::ProjectKnowledge::load(project_root) {
204        let facts_line = knowledge.format_wakeup();
205        if !facts_line.is_empty() {
206            parts.push(facts_line);
207        }
208    }
209
210    if let Some(session) = crate::core::session::SessionState::load_latest() {
211        if let Some(ref task) = session.task {
212            parts.push(format!("LAST_TASK:{}", task.description));
213        }
214        if !session.decisions.is_empty() {
215            let recent: Vec<String> = session
216                .decisions
217                .iter()
218                .rev()
219                .take(3)
220                .map(|d| d.summary.clone())
221                .collect();
222            parts.push(format!("RECENT_DECISIONS:{}", recent.join("|")));
223        }
224    }
225
226    if let Some(t) = task {
227        for r in crate::core::prospective_memory::reminders_for_task(project_root, t) {
228            parts.push(r);
229        }
230    }
231
232    let registry = crate::core::agents::AgentRegistry::load_or_create();
233    let active_agents: Vec<&crate::core::agents::AgentEntry> = registry
234        .agents
235        .iter()
236        .filter(|a| a.status != crate::core::agents::AgentStatus::Finished)
237        .collect();
238    if !active_agents.is_empty() {
239        let agents: Vec<String> = active_agents
240            .iter()
241            .map(|a| format!("{}({})", a.agent_id, a.role.as_deref().unwrap_or("-")))
242            .collect();
243        parts.push(format!("AGENTS:{}", agents.join(",")));
244    }
245
246    if parts.is_empty() {
247        return String::new();
248    }
249
250    format!("WAKE-UP BRIEFING:\n{}", parts.join("\n"))
251}
252
253fn short_path(path: &str) -> String {
254    let parts: Vec<&str> = path.split('/').collect();
255    if parts.len() <= 2 {
256        return path.to_string();
257    }
258    parts[parts.len() - 2..].join("/")
259}
260
261fn file_line_count(path: &str) -> usize {
262    std::fs::read_to_string(path)
263        .map(|c| c.lines().count())
264        .unwrap_or(0)
265}