1use std::collections::HashMap;
10use std::fmt::Write as FmtWrite;
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13
14use tokio::sync::Mutex;
15use tree_sitter_tags::{TagsConfiguration, TagsContext};
16
17use crate::errors::{Result, WinxError};
18use crate::state::bash_state::BashState;
19use crate::types::{Outline, OutlineFile, OutlineOutput, OutlineSymbol};
20use crate::utils::mmap::read_file_to_string;
21use crate::utils::path::resolve_in_workspace;
22use crate::utils::path_prob::score_paths;
23use crate::utils::repo::walk_workspace_files;
24use crate::utils::symbols::{self, Symbol};
25
26const DEFAULT_MAX_FILES: usize = 50;
28const DEFAULT_MAX_SYMBOLS: usize = 500;
30const MAX_OUTLINE_FILE_SIZE: u64 = 2_000_000;
32const OUTLINE_MAX_BYTES: usize = 24_000 * 4;
34const MAX_FILES_SCANNED: usize = 20_000;
37
38type Configs = HashMap<String, Option<TagsConfiguration>>;
39
40pub async fn handle_tool_call(
41 bash_state_arc: &Arc<Mutex<Option<BashState>>>,
42 args: Outline,
43) -> Result<(String, serde_json::Value)> {
44 let (cwd, workspace_root) = {
45 let guard = bash_state_arc.lock().await;
46 let bash_state = guard.as_ref().ok_or(WinxError::BashStateNotInitialized)?;
47 (bash_state.cwd.clone(), bash_state.workspace_root.clone())
48 };
49
50 tokio::task::spawn_blocking(move || outline_with_paths(&args, &cwd, workspace_root))
51 .await
52 .map_err(|error| {
53 WinxError::CommandExecutionError(format!("CodeMap outline worker failed: {error}"))
54 })?
55}
56
57fn outline_with_paths(
58 args: &Outline,
59 cwd: &Path,
60 workspace_root: PathBuf,
61) -> Result<(String, serde_json::Value)> {
62 let workspace_root = workspace_root.canonicalize().unwrap_or(workspace_root);
63 let root = resolve_in_workspace(&args.path, cwd, &workspace_root).map_err(|e| {
64 WinxError::PathSecurityError { path: PathBuf::from(&args.path), message: e.to_string() }
65 })?;
66
67 let mut context = TagsContext::new();
68 let mut configs: Configs = HashMap::new();
69
70 if root.is_file() {
71 outline_one(&root, &workspace_root, args, &mut context, &mut configs)
72 } else if root.is_dir() {
73 outline_repo(&root, &workspace_root, args, &mut context, &mut configs)
74 } else {
75 Err(WinxError::FileAccessError {
77 path: root.clone(),
78 message: "path not found (or not a regular file/directory)".to_string(),
79 })
80 }
81}
82
83fn empty_file_outline(message: String) -> Result<(String, serde_json::Value)> {
85 let structured = OutlineOutput {
86 mode: "file".to_string(),
87 files_shown: 0,
88 files: Vec::new(),
89 truncated: false,
90 };
91 Ok((message, crate::tools::structured_json(&structured)?))
92}
93
94fn ext_of(path: &Path) -> String {
96 path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_lowercase()
97}
98
99fn rel_of(path: &Path, workspace_root: &Path) -> String {
101 path.strip_prefix(workspace_root).unwrap_or(path).to_string_lossy().to_string()
102}
103
104fn config_for<'a>(configs: &'a mut Configs, ext: &str) -> Option<&'a TagsConfiguration> {
106 configs.entry(ext.to_string()).or_insert_with(|| symbols::config_for(ext)).as_ref()
107}
108
109fn render_symbols(out: &mut String, syms: &[Symbol]) {
110 for s in syms {
111 let _ = writeln!(out, " {:>5} {:<9} {}", s.line, s.kind, s.name);
112 }
113}
114
115fn to_output(syms: Vec<Symbol>) -> Vec<OutlineSymbol> {
116 syms.into_iter().map(|s| OutlineSymbol { name: s.name, kind: s.kind, line: s.line }).collect()
117}
118
119fn outline_one(
120 file: &Path,
121 workspace_root: &Path,
122 args: &Outline,
123 context: &mut TagsContext,
124 configs: &mut Configs,
125) -> Result<(String, serde_json::Value)> {
126 let rel = rel_of(file, workspace_root);
127 let max = if args.max_results == 0 { DEFAULT_MAX_SYMBOLS } else { args.max_results };
128 let ext = ext_of(file);
129
130 if !symbols::supports(&ext) {
133 return empty_file_outline(format!(
134 "No symbols in {rel}: unsupported language (extension `.{ext}`)."
135 ));
136 }
137 let text = match read_file_to_string(file, MAX_OUTLINE_FILE_SIZE) {
138 Ok(text) => text,
139 Err(e) => return empty_file_outline(format!("Could not outline {rel}: {e}")),
140 };
141 let Some(config) = config_for(configs, &ext) else {
142 return empty_file_outline(format!("No symbols in {rel}: no tags query for `.{ext}`."));
143 };
144
145 let mut syms = symbols::extract(context, config, &text);
146 let total = syms.len();
147 let truncated = total > max;
148 if truncated {
149 syms.truncate(max);
150 }
151
152 let mut out = String::new();
153 if syms.is_empty() {
154 return empty_file_outline(format!("No definitions found in {rel}."));
155 }
156 if truncated {
157 let _ = writeln!(out, "{rel} ({} of {total} symbols):", syms.len());
158 } else {
159 let noun = if total == 1 { "symbol" } else { "symbols" };
160 let _ = writeln!(out, "{rel} ({total} {noun}):");
161 }
162 render_symbols(&mut out, &syms);
163 if truncated {
164 let _ = write!(out, "(...{} more; raise max_results)", total - syms.len());
165 }
166
167 let structured = OutlineOutput {
168 mode: "file".to_string(),
169 files_shown: 1,
170 files: vec![OutlineFile { file: rel, symbols: to_output(syms) }],
171 truncated,
172 };
173 Ok((out, crate::tools::structured_json(&structured)?))
174}
175
176fn ranked_supported_files(root: &Path, workspace_root: &Path) -> Vec<(PathBuf, String)> {
179 let mut files: Vec<(PathBuf, String)> = walk_workspace_files(root)
180 .into_iter()
181 .filter(|abs| symbols::supports(&ext_of(abs)))
182 .map(|abs| {
183 let rel = rel_of(&abs, workspace_root);
184 (abs, rel)
185 })
186 .collect();
187
188 files.sort_by(|a, b| a.1.cmp(&b.1));
191 let ranking = {
195 let rels: Vec<&str> = files.iter().map(|(_, r)| r.as_str()).collect();
196 score_paths(&rels)
197 };
198 if let Some(weights) = ranking {
199 let mut pairs: Vec<(f64, (PathBuf, String))> = weights.into_iter().zip(files).collect();
203 pairs.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
204 files = pairs.into_iter().map(|(_, f)| f).collect();
205 }
206 files
207}
208
209fn outline_repo(
210 root: &Path,
211 workspace_root: &Path,
212 args: &Outline,
213 context: &mut TagsContext,
214 configs: &mut Configs,
215) -> Result<(String, serde_json::Value)> {
216 let max_files = if args.max_results == 0 { DEFAULT_MAX_FILES } else { args.max_results };
217
218 let mut out = String::new();
219 let mut out_files: Vec<OutlineFile> = Vec::new();
220 let mut truncated = false;
221 let mut scanned = 0usize;
222
223 for (abs, rel) in ranked_supported_files(root, workspace_root) {
224 if out_files.len() >= max_files
225 || out.len() >= OUTLINE_MAX_BYTES
226 || scanned >= MAX_FILES_SCANNED
227 {
228 truncated = true;
229 break;
230 }
231 let Ok(text) = read_file_to_string(&abs, MAX_OUTLINE_FILE_SIZE) else { continue };
234 scanned += 1;
235 let ext = ext_of(&abs);
236 let mut syms = match config_for(configs, &ext) {
237 Some(config) => symbols::extract(context, config, &text),
238 None => continue,
239 };
240 if syms.is_empty() {
241 continue;
242 }
243 if syms.len() > DEFAULT_MAX_SYMBOLS {
246 syms.truncate(DEFAULT_MAX_SYMBOLS);
247 truncated = true;
248 }
249 let _ = writeln!(out, "{rel}");
250 render_symbols(&mut out, &syms);
251 out_files.push(OutlineFile { file: rel, symbols: to_output(syms) });
252 }
253
254 if out_files.is_empty() {
255 out = format!("No code symbols found under {}.", root.display());
256 } else if truncated {
257 let _ = write!(out, "(...capped; narrow `path` or raise max_results)");
258 }
259
260 let files_shown = out_files.len();
261 let structured =
262 OutlineOutput { mode: "repo".to_string(), files_shown, files: out_files, truncated };
263 Ok((out, crate::tools::structured_json(&structured)?))
264}
265
266#[cfg(test)]
267mod tests {
268 #![allow(clippy::unwrap_used)]
269 use super::*;
270 use tempfile::TempDir;
271
272 fn state_in(dir: &TempDir) -> Arc<Mutex<Option<BashState>>> {
273 let mut bs = BashState::new();
274 let root = dir.path().canonicalize().unwrap();
275 bs.cwd = root.clone();
276 bs.workspace_root = root;
277 Arc::new(Mutex::new(Some(bs)))
278 }
279
280 fn args(path: &str) -> Outline {
281 Outline { path: path.to_string(), max_results: 0, thread_id: String::new() }
282 }
283
284 #[tokio::test]
285 async fn single_file_lists_symbols() {
286 let dir = TempDir::new().unwrap();
287 std::fs::write(dir.path().join("a.rs"), "pub fn alpha() {}\nstruct Beta;\n").unwrap();
288 let st = state_in(&dir);
289 let (out, structured) = handle_tool_call(&st, args("a.rs")).await.unwrap();
290 assert!(out.contains("alpha"));
291 assert!(out.contains("Beta"));
292 assert_eq!(structured["mode"], "file");
293 let syms = structured["files"][0]["symbols"].as_array().unwrap();
294 assert!(syms.iter().any(|s| s["name"] == "alpha"));
295 }
296
297 #[tokio::test]
298 async fn repo_map_ranks_files() {
299 let dir = TempDir::new().unwrap();
300 std::fs::create_dir_all(dir.path().join("src")).unwrap();
301 std::fs::write(dir.path().join("src/lib.rs"), "pub fn one() {}\n").unwrap();
302 std::fs::write(dir.path().join("src/util.rs"), "fn two() {}\n").unwrap();
303 std::fs::write(dir.path().join("notes.txt"), "not code\n").unwrap();
304 let st = state_in(&dir);
305 let (out, structured) = handle_tool_call(&st, args("")).await.unwrap();
306 assert_eq!(structured["mode"], "repo");
307 assert_eq!(structured["files_shown"], 2); assert!(out.contains("one"));
309 assert!(out.contains("two"));
310 assert!(!out.contains("notes.txt"));
311 }
312
313 #[tokio::test]
314 async fn no_symbols_message() {
315 let dir = TempDir::new().unwrap();
316 std::fs::write(dir.path().join("data.json"), "{\"a\":1}\n").unwrap();
317 let st = state_in(&dir);
318 let (out, structured) = handle_tool_call(&st, args("data.json")).await.unwrap();
319 assert!(out.to_lowercase().contains("no symbols"));
320 assert_eq!(structured["files_shown"], 0);
321 }
322
323 #[tokio::test]
324 async fn nonexistent_path_errors_instead_of_repo_scan() {
325 let dir = TempDir::new().unwrap();
328 std::fs::write(dir.path().join("real.rs"), "fn x() {}\n").unwrap();
329 let st = state_in(&dir);
330 assert!(handle_tool_call(&st, args("nope_typo.rs")).await.is_err());
331 }
332
333 #[tokio::test]
334 async fn repo_per_file_cap_marks_truncated() {
335 let dir = TempDir::new().unwrap();
338 let mut src = String::new();
339 for i in 0..(DEFAULT_MAX_SYMBOLS + 100) {
340 let _ = writeln!(src, "fn f{i}() {{}}");
341 }
342 std::fs::write(dir.path().join("big.rs"), src).unwrap();
343 let st = state_in(&dir);
344 let (_, structured) = handle_tool_call(&st, args("")).await.unwrap();
345 let syms = structured["files"][0]["symbols"].as_array().unwrap();
346 assert!(syms.len() <= DEFAULT_MAX_SYMBOLS, "got {}", syms.len());
347 assert_eq!(structured["truncated"], true);
348 }
349}