| 1 | //! File search tool with fuzzy matching and scoring. |
| 2 | |
| 3 | use std::cmp::Ordering; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering}; |
| 6 | use std::sync::{Arc, Mutex, PoisonError}; |
| 7 | use std::time::{Duration, Instant}; |
| 8 | |
| 9 | use async_trait::async_trait; |
| 10 | use globset::{GlobBuilder, GlobMatcher, GlobSetBuilder}; |
| 11 | use ignore::{WalkBuilder, WalkState}; |
| 12 | use serde_json::{Value, json}; |
| 13 | use tokio_util::sync::CancellationToken; |
| 14 | |
| 15 | use super::file::{SEARCH_NAME_ALIASES, SEARCH_NAME_PARAMS}; |
| 16 | use super::spec::{ |
| 17 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 18 | optional_bool, optional_str, optional_u64, required_str, |
| 19 | }; |
| 20 | use codewhale_tools::param_alias::{PATH_ALIASES, apply_param_aliases}; |
| 21 | |
| 22 | const FILE_SEARCH_TIMEOUT: Duration = Duration::from_secs(30); |
| 23 | const FILE_SEARCH_BUDGET: Duration = Duration::from_secs(20); |
| 24 | const SHALLOW_PASS_DEPTH: usize = 4; |
| 25 | |
| 26 | #[derive(Debug, Default)] |
| 27 | struct FileSearchOutcome { |
| 28 | matches: Vec<FileSearchMatch>, |
| 29 | total_matches: usize, |
| 30 | stopped_after: Option<Duration>, |
| 31 | } |
| 32 | |
| 33 | #[derive(Debug, Clone)] |
| 34 | struct FileSearchMatch { |
| 35 | path: String, |
| 36 | score: f64, |
| 37 | } |
| 38 | |
| 39 | pub struct FileSearchTool; |
| 40 | |
| 41 | #[async_trait] |
| 42 | impl ToolSpec for FileSearchTool { |
| 43 | fn name(&self) -> &'static str { |
| 44 | "file_search" |
| 45 | } |
| 46 | |
| 47 | fn model_visible(&self) -> bool { |
| 48 | true |
| 49 | } |
| 50 | |
| 51 | fn description(&self) -> &'static str { |
| 52 | "Find workspace files by name, path, or glob (e.g. src/**/*.rs). Space-separated terms must all match. Literal matches rank above fuzzy matches; results return {files, total_matches, truncated}. Respects ignore files and skips build/dependency directories and hidden dot-directories by default (search inside one by setting path to it or naming it in the query). Use extensions to filter suffixes." |
| 53 | } |
| 54 | |
| 55 | fn input_schema(&self) -> Value { |
| 56 | json!({ |
| 57 | "type": "object", |
| 58 | "properties": { |
| 59 | "query": { |
| 60 | "type": "string", |
| 61 | "description": "File name, path fragment, space-separated terms, or glob (e.g. **/engine*.rs)." |
| 62 | }, |
| 63 | "path": { |
| 64 | "type": "string", |
| 65 | "description": "Optional base path to search (relative to workspace)." |
| 66 | }, |
| 67 | "limit": { |
| 68 | "type": "integer", |
| 69 | "description": "Maximum number of ranked results to return (default: 20, maximum: 200)." |
| 70 | }, |
| 71 | "extensions": { |
| 72 | "type": "array", |
| 73 | "items": { "type": "string" }, |
| 74 | "description": "Optional list of file extensions to include (e.g. [\"rs\", \"md\"])." |
| 75 | }, |
| 76 | "exclude": { |
| 77 | "type": "array", |
| 78 | "items": { "type": "string" }, |
| 79 | "description": "Extra exclusion globs appended to the defaults (e.g. [\"fixtures/**\"]) unless replace_default_excludes=true." |
| 80 | }, |
| 81 | "replace_default_excludes": { |
| 82 | "type": "boolean", |
| 83 | "description": "If true, exclude replaces the default build/dependency exclusions instead of appending (default: false)." |
| 84 | } |
| 85 | }, |
| 86 | "required": ["query"] |
| 87 | }) |
| 88 | } |
| 89 | |
| 90 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 91 | vec![ToolCapability::ReadOnly, ToolCapability::Sandboxable] |
| 92 | } |
| 93 | |
| 94 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 95 | ApprovalRequirement::Auto |
| 96 | } |
| 97 | |
| 98 | fn supports_parallel(&self) -> bool { |
| 99 | true |
| 100 | } |
| 101 | |
| 102 | async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> { |
| 103 | let mut input = input; |
| 104 | apply_param_aliases(&mut input, PATH_ALIASES, "File search_name")?; |
| 105 | apply_param_aliases(&mut input, SEARCH_NAME_ALIASES, "File search_name")?; |
| 106 | SEARCH_NAME_PARAMS.reject_unknown(&input)?; |
| 107 | |
| 108 | let query = required_str(&input, "query")?.trim(); |
| 109 | if query.is_empty() { |
| 110 | return Err(ToolError::invalid_input("query cannot be empty")); |
| 111 | } |
| 112 | |
| 113 | let limit = optional_u64(&input, "limit", 20)?.clamp(1, 200) as usize; |
| 114 | // S1: enumerating names inside a denied tree is a read of that tree — |
| 115 | // Seatbelt's `deny file-read*` blocks readdir of denied dirs, so a |
| 116 | // denied search root is refused rather than walked. The raw spelling is |
| 117 | // checked before `resolve_path` (F2) so the refusal names the caller's |
| 118 | // path, never a symlink target it might resolve to. |
| 119 | let base_path = match optional_str(&input, "path")? { |
| 120 | Some(path) if !path.trim().is_empty() => { |
| 121 | super::file::resolve_guarded_search_root(context, path, "file_search", false) |
| 122 | .await? |
| 123 | .0 |
| 124 | } |
| 125 | _ => { |
| 126 | let path = context.workspace.clone(); |
| 127 | super::file::enforce_read_denylist(&path, "file_search")?; |
| 128 | if super::file::is_codewhale_credential_path(&path) { |
| 129 | return Err(ToolError::permission_denied( |
| 130 | "file_search cannot expose Codewhale configuration or credential-store files; use `codewhale config list` or `codewhale auth status` for safe inspection", |
| 131 | )); |
| 132 | } |
| 133 | path |
| 134 | } |
| 135 | }; |
| 136 | |
| 137 | let extensions = parse_extensions(&input); |
| 138 | optional_bool(&input, "replace_default_excludes", false)?; |
| 139 | let exclude_patterns = parse_exclude_patterns(&input); |
| 140 | let follow_symlinks = context.follow_symlinks && !context.strict_workspace_confinement; |
| 141 | let outcome = search_files_async( |
| 142 | query.to_string(), |
| 143 | base_path, |
| 144 | context.workspace.clone(), |
| 145 | extensions, |
| 146 | exclude_patterns, |
| 147 | limit, |
| 148 | context.cancel_token.clone(), |
| 149 | FILE_SEARCH_TIMEOUT, |
| 150 | FILE_SEARCH_BUDGET, |
| 151 | follow_symlinks, |
| 152 | ) |
| 153 | .await?; |
| 154 | file_search_result(outcome).map_err(|e| ToolError::execution_failed(e.to_string())) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | fn file_search_result(outcome: FileSearchOutcome) -> Result<ToolResult, serde_json::Error> { |
| 159 | let files: Vec<String> = outcome.matches.into_iter().map(|m| m.path).collect(); |
| 160 | let truncated = outcome.stopped_after.is_some() || outcome.total_matches > files.len(); |
| 161 | let Some(stopped_after) = outcome.stopped_after else { |
| 162 | return ToolResult::json(&json!({ |
| 163 | "files": files, |
| 164 | "total_matches": outcome.total_matches, |
| 165 | "truncated": truncated, |
| 166 | })); |
| 167 | }; |
| 168 | let seconds = stopped_after.as_secs().max(1); |
| 169 | let note = format!( |
| 170 | "partial: stopped after {seconds}s before the whole tree was searched; these are the best matches found so far. Narrow `path` or the query for complete results." |
| 171 | ); |
| 172 | Ok(ToolResult::json(&json!({ |
| 173 | "files": files, |
| 174 | "total_matches": outcome.total_matches, |
| 175 | "truncated": true, |
| 176 | "partial": true, |
| 177 | "note": note, |
| 178 | }))? |
| 179 | .with_metadata(json!({ "partial": true, "stopped_after_secs": seconds }))) |
| 180 | } |
| 181 | |
| 182 | #[allow(clippy::too_many_arguments)] |
| 183 | async fn search_files_async( |
| 184 | query: String, |
| 185 | base_path: PathBuf, |
| 186 | workspace: PathBuf, |
| 187 | extensions: Vec<String>, |
| 188 | exclude_patterns: Vec<String>, |
| 189 | limit: usize, |
| 190 | cancel_token: Option<CancellationToken>, |
| 191 | timeout: Duration, |
| 192 | budget: Duration, |
| 193 | follow_symlinks: bool, |
| 194 | ) -> Result<FileSearchOutcome, ToolError> { |
| 195 | let workspace_canonical = tokio::fs::canonicalize(&workspace).await.ok(); |
| 196 | run_blocking_file_search(timeout, cancel_token, move |worker_cancel_token| { |
| 197 | search_files( |
| 198 | &query, |
| 199 | &base_path, |
| 200 | &workspace, |
| 201 | workspace_canonical, |
| 202 | extensions, |
| 203 | exclude_patterns, |
| 204 | limit, |
| 205 | Some(&worker_cancel_token), |
| 206 | budget, |
| 207 | follow_symlinks, |
| 208 | ) |
| 209 | }) |
| 210 | .await |
| 211 | } |
| 212 | |
| 213 | async fn run_blocking_file_search<F>( |
| 214 | timeout: Duration, |
| 215 | cancel_token: Option<CancellationToken>, |
| 216 | search: F, |
| 217 | ) -> Result<FileSearchOutcome, ToolError> |
| 218 | where |
| 219 | F: FnOnce(CancellationToken) -> Result<FileSearchOutcome, ToolError> + Send + 'static, |
| 220 | { |
| 221 | if cancel_token |
| 222 | .as_ref() |
| 223 | .is_some_and(CancellationToken::is_cancelled) |
| 224 | { |
| 225 | return Err(file_search_cancelled()); |
| 226 | } |
| 227 | |
| 228 | let worker_cancel_token = cancel_token |
| 229 | .as_ref() |
| 230 | .map(CancellationToken::child_token) |
| 231 | .unwrap_or_default(); |
| 232 | let _worker_cancel_guard = worker_cancel_token.clone().drop_guard(); |
| 233 | let task = tokio::task::spawn_blocking(move || search(worker_cancel_token)); |
| 234 | let result = match cancel_token { |
| 235 | Some(token) => { |
| 236 | tokio::select! { |
| 237 | biased; |
| 238 | () = token.cancelled() => return Err(file_search_cancelled()), |
| 239 | result = tokio::time::timeout(timeout, task) => result, |
| 240 | } |
| 241 | } |
| 242 | None => tokio::time::timeout(timeout, task).await, |
| 243 | }; |
| 244 | |
| 245 | let joined = result.map_err(|_| file_search_timeout(timeout))?; |
| 246 | joined.map_err(|err| { |
| 247 | ToolError::execution_failed(format!( |
| 248 | "file_search worker failed before completion: {err}" |
| 249 | )) |
| 250 | })? |
| 251 | } |
| 252 | |
| 253 | fn file_search_cancelled() -> ToolError { |
| 254 | ToolError::cancelled("file_search cancelled before completion") |
| 255 | } |
| 256 | |
| 257 | fn file_search_timeout(timeout: Duration) -> ToolError { |
| 258 | ToolError::Timeout { |
| 259 | seconds: timeout.as_secs().max(1), |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | fn parse_extensions(input: &Value) -> Vec<String> { |
| 264 | let mut out = Vec::new(); |
| 265 | if let Some(values) = input.get("extensions").and_then(|v| v.as_array()) { |
| 266 | for value in values { |
| 267 | if let Some(ext) = value.as_str() { |
| 268 | let ext = ext.trim().trim_start_matches('.').to_ascii_lowercase(); |
| 269 | if !ext.is_empty() { |
| 270 | out.push(ext); |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | if out.is_empty() |
| 276 | && let Some(value) = input.get("extension").and_then(|v| v.as_str()) |
| 277 | { |
| 278 | let ext = value.trim().trim_start_matches('.').to_ascii_lowercase(); |
| 279 | if !ext.is_empty() { |
| 280 | out.push(ext); |
| 281 | } |
| 282 | } |
| 283 | out |
| 284 | } |
| 285 | |
| 286 | fn parse_exclude_patterns(input: &Value) -> Vec<String> { |
| 287 | let caller: Vec<String> = input |
| 288 | .get("exclude") |
| 289 | .and_then(Value::as_array) |
| 290 | .into_iter() |
| 291 | .flatten() |
| 292 | .filter_map(Value::as_str) |
| 293 | .map(str::trim) |
| 294 | .filter(|pattern| !pattern.is_empty()) |
| 295 | .map(ToOwned::to_owned) |
| 296 | .collect(); |
| 297 | if input |
| 298 | .get("replace_default_excludes") |
| 299 | .and_then(Value::as_bool) |
| 300 | .unwrap_or(false) |
| 301 | { |
| 302 | return caller; |
| 303 | } |
| 304 | let mut patterns = default_exclude_patterns(); |
| 305 | patterns.extend(caller); |
| 306 | patterns |
| 307 | } |
| 308 | |
| 309 | fn default_exclude_patterns() -> Vec<String> { |
| 310 | [ |
| 311 | "**/target/**", |
| 312 | "**/node_modules/**", |
| 313 | "**/.git/**", |
| 314 | "**/DerivedData/**", |
| 315 | "**/dist/**", |
| 316 | "**/build/**", |
| 317 | "**/.venv/**", |
| 318 | "**/__pycache__/**", |
| 319 | "**/.next/**", |
| 320 | "**/.turbo/**", |
| 321 | "**/.gradle/**", |
| 322 | "*.lock", |
| 323 | "*.plist", |
| 324 | ] |
| 325 | .into_iter() |
| 326 | .map(ToOwned::to_owned) |
| 327 | .collect() |
| 328 | } |
| 329 | |
| 330 | #[allow(clippy::too_many_arguments)] |
| 331 | fn search_files( |
| 332 | query: &str, |
| 333 | base_path: &Path, |
| 334 | workspace: &Path, |
| 335 | workspace_canonical: Option<PathBuf>, |
| 336 | extensions: Vec<String>, |
| 337 | exclude_patterns: Vec<String>, |
| 338 | limit: usize, |
| 339 | cancel_token: Option<&CancellationToken>, |
| 340 | budget: Duration, |
| 341 | follow_symlinks: bool, |
| 342 | ) -> Result<FileSearchOutcome, ToolError> { |
| 343 | let started = Instant::now(); |
| 344 | let deadline = started + budget; |
| 345 | check_cancelled(cancel_token)?; |
| 346 | |
| 347 | if !base_path.exists() { |
| 348 | return Err(ToolError::invalid_input(format!( |
| 349 | "Base path does not exist: {}", |
| 350 | base_path.display() |
| 351 | ))); |
| 352 | } |
| 353 | |
| 354 | let query_norm = query.to_lowercase().replace('\\', "/"); |
| 355 | let query_norm = query_norm.strip_prefix("./").unwrap_or(&query_norm); |
| 356 | if query_norm.is_empty() { |
| 357 | return Err(ToolError::invalid_input("query cannot be empty")); |
| 358 | } |
| 359 | let query_glob = if query_norm.contains(['*', '?', '[', '{']) { |
| 360 | let pattern = if query_norm.contains('/') { |
| 361 | query_norm.to_string() |
| 362 | } else { |
| 363 | format!("**/{query_norm}") |
| 364 | }; |
| 365 | match GlobBuilder::new(&pattern) |
| 366 | .literal_separator(true) |
| 367 | .case_insensitive(true) |
| 368 | .build() |
| 369 | { |
| 370 | Ok(glob) => Some(glob.compile_matcher()), |
| 371 | Err(err) if query_norm.contains(['*', '?']) => { |
| 372 | return Err(ToolError::invalid_input(format!( |
| 373 | "Invalid query glob: {err}" |
| 374 | ))); |
| 375 | } |
| 376 | Err(_) => None, |
| 377 | } |
| 378 | } else { |
| 379 | None |
| 380 | }; |
| 381 | let query_terms: Vec<_> = query_norm.split_whitespace().collect(); |
| 382 | let mut exclusions = GlobSetBuilder::new(); |
| 383 | for pattern in exclude_patterns { |
| 384 | let pattern = pattern.replace('\\', "/"); |
| 385 | let pattern = if pattern.contains('/') { |
| 386 | pattern |
| 387 | } else { |
| 388 | format!("**/{pattern}") |
| 389 | }; |
| 390 | for glob in std::iter::once(pattern.as_str()).chain(pattern.strip_suffix("/**")) { |
| 391 | exclusions.add( |
| 392 | GlobBuilder::new(glob) |
| 393 | .literal_separator(true) |
| 394 | .build() |
| 395 | .map_err(|err| { |
| 396 | ToolError::invalid_input(format!("Invalid exclude glob: {err}")) |
| 397 | })?, |
| 398 | ); |
| 399 | } |
| 400 | } |
| 401 | let exclusions = exclusions |
| 402 | .build() |
| 403 | .map_err(|err| ToolError::invalid_input(format!("Invalid exclude globs: {err}")))?; |
| 404 | let include_hidden_dirs = query_norm.starts_with('.') || query_norm.contains("/."); |
| 405 | let walk_root = base_path.to_path_buf(); |
| 406 | let walk_cancel_token = cancel_token.cloned(); |
| 407 | let deadline_hit = Arc::new(AtomicBool::new(false)); |
| 408 | let walk_deadline_hit = Arc::clone(&deadline_hit); |
| 409 | |
| 410 | let mut builder = WalkBuilder::new(base_path); |
| 411 | builder |
| 412 | .hidden(false) |
| 413 | .follow_links(follow_symlinks) |
| 414 | .require_git(false) |
| 415 | .filter_entry(move |entry| { |
| 416 | if Instant::now() >= deadline { |
| 417 | walk_deadline_hit.store(true, AtomicOrdering::Relaxed); |
| 418 | return false; |
| 419 | } |
| 420 | let rel_path = entry |
| 421 | .path() |
| 422 | .strip_prefix(&walk_root) |
| 423 | .unwrap_or(entry.path()); |
| 424 | if entry.depth() > 0 |
| 425 | && !include_hidden_dirs |
| 426 | && entry.file_type().is_some_and(|kind| kind.is_dir()) |
| 427 | && entry.file_name().to_string_lossy().starts_with('.') |
| 428 | { |
| 429 | return false; |
| 430 | } |
| 431 | if entry.depth() > 0 |
| 432 | && !walk_cancel_token |
| 433 | .as_ref() |
| 434 | .is_some_and(CancellationToken::is_cancelled) |
| 435 | && exclusions.is_match(rel_path) |
| 436 | { |
| 437 | return false; |
| 438 | } |
| 439 | // Sandbox read deny-list (S1). A walk rooted above a denied tree |
| 440 | // must not enumerate its names. Reject directories before descent; |
| 441 | // the explicit root refusal remains at the guard above. |
| 442 | if let Err(denial) = codewhale_sandbox::read_guard::active().check(entry.path()) { |
| 443 | tracing::debug!( |
| 444 | target: "codewhale::sandbox::read_guard", |
| 445 | requested = %denial.requested.display(), |
| 446 | "sandbox read deny-list skipped an entry during file_search" |
| 447 | ); |
| 448 | return false; |
| 449 | } |
| 450 | !super::file::is_codewhale_credential_path(entry.path()) |
| 451 | }); |
| 452 | let match_path = |path: &Path| -> Option<FileSearchMatch> { |
| 453 | let rel_path = path |
| 454 | .strip_prefix(base_path) |
| 455 | .unwrap_or(path) |
| 456 | .to_string_lossy() |
| 457 | .replace('\\', "/"); |
| 458 | if !extensions.is_empty() && !extension_matches(path, &extensions) { |
| 459 | return None; |
| 460 | } |
| 461 | let name = file_name(path); |
| 462 | let score = score_match( |
| 463 | query_norm, |
| 464 | &query_terms, |
| 465 | query_glob.as_ref(), |
| 466 | &rel_path, |
| 467 | &name, |
| 468 | )?; |
| 469 | let shown_path = path |
| 470 | .strip_prefix(workspace) |
| 471 | .ok() |
| 472 | .or_else(|| { |
| 473 | workspace_canonical |
| 474 | .as_deref() |
| 475 | .and_then(|canonical| path.strip_prefix(canonical).ok()) |
| 476 | }) |
| 477 | .unwrap_or(path) |
| 478 | .to_string_lossy() |
| 479 | .replace('\\', "/"); |
| 480 | Some(FileSearchMatch { |
| 481 | path: shown_path, |
| 482 | score, |
| 483 | }) |
| 484 | }; |
| 485 | let run_pass = |builder: &WalkBuilder, max_depth: Option<usize>| { |
| 486 | let ranked = Mutex::new(Vec::with_capacity(limit)); |
| 487 | let total_matches = AtomicUsize::new(0); |
| 488 | let deeper = AtomicBool::new(false); |
| 489 | builder.build_parallel().run(|| { |
| 490 | let match_path = &match_path; |
| 491 | let ranked = &ranked; |
| 492 | let total_matches = &total_matches; |
| 493 | let deadline_hit = &deadline_hit; |
| 494 | let deeper = &deeper; |
| 495 | Box::new(move |entry| { |
| 496 | if cancel_token.is_some_and(CancellationToken::is_cancelled) { |
| 497 | return WalkState::Quit; |
| 498 | } |
| 499 | if Instant::now() >= deadline { |
| 500 | deadline_hit.store(true, AtomicOrdering::Relaxed); |
| 501 | return WalkState::Quit; |
| 502 | } |
| 503 | let Ok(entry) = entry else { |
| 504 | return WalkState::Continue; |
| 505 | }; |
| 506 | let Some(file_type) = entry.file_type() else { |
| 507 | return WalkState::Continue; |
| 508 | }; |
| 509 | if file_type.is_dir() && max_depth.is_some_and(|depth| entry.depth() >= depth) { |
| 510 | deeper.store(true, AtomicOrdering::Relaxed); |
| 511 | } |
| 512 | if !file_type.is_file() { |
| 513 | return WalkState::Continue; |
| 514 | } |
| 515 | if let Some(found) = match_path(entry.path()) { |
| 516 | total_matches.fetch_add(1, AtomicOrdering::Relaxed); |
| 517 | let mut results = ranked.lock().unwrap_or_else(PoisonError::into_inner); |
| 518 | insert_ranked(&mut results, found, limit); |
| 519 | } |
| 520 | WalkState::Continue |
| 521 | }) |
| 522 | }); |
| 523 | ( |
| 524 | ranked.into_inner().unwrap_or_else(PoisonError::into_inner), |
| 525 | total_matches.into_inner(), |
| 526 | deadline_hit.load(AtomicOrdering::Relaxed), |
| 527 | deeper.into_inner(), |
| 528 | ) |
| 529 | }; |
| 530 | let outcome = |matches, total_matches, stopped: bool| FileSearchOutcome { |
| 531 | matches, |
| 532 | total_matches, |
| 533 | stopped_after: stopped.then(|| started.elapsed()), |
| 534 | }; |
| 535 | |
| 536 | builder.max_depth(Some(SHALLOW_PASS_DEPTH)); |
| 537 | let (shallow, shallow_total, stopped, deeper) = run_pass(&builder, Some(SHALLOW_PASS_DEPTH)); |
| 538 | check_cancelled(cancel_token)?; |
| 539 | if stopped || !deeper { |
| 540 | return Ok(outcome(shallow, shallow_total, stopped)); |
| 541 | } |
| 542 | |
| 543 | builder.max_depth(None); |
| 544 | let (mut full, full_total, stopped, _) = run_pass(&builder, None); |
| 545 | check_cancelled(cancel_token)?; |
| 546 | let total_matches = if stopped { |
| 547 | for found in shallow { |
| 548 | if !full.iter().any(|existing| existing.path == found.path) { |
| 549 | insert_ranked(&mut full, found, limit); |
| 550 | } |
| 551 | } |
| 552 | full_total.max(shallow_total).max(full.len()) |
| 553 | } else { |
| 554 | full_total |
| 555 | }; |
| 556 | Ok(outcome(full, total_matches, stopped)) |
| 557 | } |
| 558 | |
| 559 | fn insert_ranked(results: &mut Vec<FileSearchMatch>, found: FileSearchMatch, limit: usize) { |
| 560 | if results.len() == limit |
| 561 | && results |
| 562 | .last() |
| 563 | .is_some_and(|worst| compare_match(&found, worst) != Ordering::Less) |
| 564 | { |
| 565 | return; |
| 566 | } |
| 567 | let index = results |
| 568 | .binary_search_by(|existing| compare_match(existing, &found)) |
| 569 | .unwrap_or_else(|index| index); |
| 570 | if index < limit { |
| 571 | results.insert(index, found); |
| 572 | results.truncate(limit); |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | fn check_cancelled(cancel_token: Option<&CancellationToken>) -> Result<(), ToolError> { |
| 577 | if cancel_token.is_some_and(CancellationToken::is_cancelled) { |
| 578 | return Err(file_search_cancelled()); |
| 579 | } |
| 580 | Ok(()) |
| 581 | } |
| 582 | |
| 583 | fn extension_matches(path: &Path, extensions: &[String]) -> bool { |
| 584 | let Some(ext) = path.extension().and_then(|e| e.to_str()) else { |
| 585 | return false; |
| 586 | }; |
| 587 | let ext = ext.to_ascii_lowercase(); |
| 588 | extensions.iter().any(|wanted| wanted == &ext) |
| 589 | } |
| 590 | |
| 591 | fn file_name(path: &Path) -> String { |
| 592 | path.file_name() |
| 593 | .map(|name| name.to_string_lossy().into_owned()) |
| 594 | .unwrap_or_else(|| path.to_string_lossy().to_string()) |
| 595 | } |
| 596 | |
| 597 | fn score_match( |
| 598 | query: &str, |
| 599 | terms: &[&str], |
| 600 | glob: Option<&GlobMatcher>, |
| 601 | rel_path: &str, |
| 602 | name: &str, |
| 603 | ) -> Option<f64> { |
| 604 | let path_norm = rel_path.to_lowercase(); |
| 605 | let name_norm = name.to_lowercase(); |
| 606 | if path_norm == query { |
| 607 | return Some(1.0); |
| 608 | } |
| 609 | if name_norm == query { |
| 610 | return Some(0.99); |
| 611 | } |
| 612 | if let Some(glob) = glob { |
| 613 | if name_norm.contains(query) || path_norm.contains(query) { |
| 614 | return score_fragment(query, &path_norm, &name_norm); |
| 615 | } |
| 616 | return glob |
| 617 | .is_match(&path_norm) |
| 618 | .then(|| 0.9 + 0.08 / name.chars().count().max(1) as f64); |
| 619 | } |
| 620 | |
| 621 | if terms.len() > 1 { |
| 622 | let mut total = 0.0; |
| 623 | let mut minimum = 1.0_f64; |
| 624 | for term in terms { |
| 625 | let score = score_fragment(term, &path_norm, &name_norm)?; |
| 626 | minimum = minimum.min(score); |
| 627 | total += score; |
| 628 | } |
| 629 | return Some(minimum * 0.995 + 0.005 * total / terms.len() as f64); |
| 630 | } |
| 631 | score_fragment(query, &path_norm, &name_norm) |
| 632 | } |
| 633 | |
| 634 | fn score_fragment(query: &str, path_norm: &str, name_norm: &str) -> Option<f64> { |
| 635 | if path_norm == query { |
| 636 | return Some(1.0); |
| 637 | } |
| 638 | if name_norm == query { |
| 639 | return Some(0.99); |
| 640 | } |
| 641 | |
| 642 | if name_norm.starts_with(query) { |
| 643 | return Some(0.9 + length_bonus(query, name_norm)); |
| 644 | } |
| 645 | if path_norm.starts_with(query) { |
| 646 | return Some(0.8 + length_bonus(query, path_norm)); |
| 647 | } |
| 648 | |
| 649 | if name_norm.contains(query) { |
| 650 | return Some(0.7 + length_bonus(query, name_norm)); |
| 651 | } |
| 652 | if path_norm.contains(query) { |
| 653 | return Some(0.6 + length_bonus(query, path_norm)); |
| 654 | } |
| 655 | |
| 656 | if let Some(score) = fuzzy_score(query, name_norm) { |
| 657 | return Some(0.4 + 0.15 * score); |
| 658 | } |
| 659 | if let Some(score) = fuzzy_score(query, path_norm) { |
| 660 | return Some(0.2 + 0.15 * score); |
| 661 | } |
| 662 | |
| 663 | None |
| 664 | } |
| 665 | |
| 666 | fn length_bonus(query: &str, target: &str) -> f64 { |
| 667 | let q_len = query.chars().count().max(1) as f64; |
| 668 | let t_len = target.chars().count().max(1) as f64; |
| 669 | (q_len / t_len).min(1.0) * 0.08 |
| 670 | } |
| 671 | |
| 672 | fn fuzzy_score(query: &str, target: &str) -> Option<f64> { |
| 673 | let mut query_chars = query.chars(); |
| 674 | let mut current = query_chars.next()?; |
| 675 | let mut first = None; |
| 676 | let mut last = 0; |
| 677 | let mut matched = 0; |
| 678 | |
| 679 | for (idx, ch) in target.chars().enumerate() { |
| 680 | if ch == current { |
| 681 | first.get_or_insert(idx); |
| 682 | last = idx; |
| 683 | matched += 1; |
| 684 | if let Some(next) = query_chars.next() { |
| 685 | current = next; |
| 686 | } else { |
| 687 | break; |
| 688 | } |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | if matched != query.chars().count() { |
| 693 | return None; |
| 694 | } |
| 695 | |
| 696 | let first = first? as f64; |
| 697 | let last = last as f64; |
| 698 | let span = (last - first + 1.0).max(1.0); |
| 699 | let query_len = query.chars().count().max(1) as f64; |
| 700 | let target_len = target.chars().count().max(1) as f64; |
| 701 | |
| 702 | let density = (query_len / span).min(1.0); |
| 703 | let coverage = (query_len / target_len).min(1.0); |
| 704 | Some((density * 0.7 + coverage * 0.3).min(1.0)) |
| 705 | } |
| 706 | |
| 707 | fn compare_match(a: &FileSearchMatch, b: &FileSearchMatch) -> Ordering { |
| 708 | b.score |
| 709 | .partial_cmp(&a.score) |
| 710 | .unwrap_or(Ordering::Equal) |
| 711 | .then_with(|| a.path.cmp(&b.path)) |
| 712 | } |
| 713 | |
| 714 | #[cfg(test)] |
| 715 | mod tests { |
| 716 | use super::*; |
| 717 | use tempfile::tempdir; |
| 718 | |
| 719 | #[tokio::test] |
| 720 | async fn test_file_search_basic() { |
| 721 | let tmp = tempdir().expect("tempdir"); |
| 722 | let root = tmp.path(); |
| 723 | std::fs::create_dir_all(root.join("src")).expect("mkdir"); |
| 724 | std::fs::write(root.join("src").join("main.rs"), "fn main() {}\n").expect("write"); |
| 725 | std::fs::write(root.join("README.md"), "docs\n").expect("write"); |
| 726 | |
| 727 | let ctx = ToolContext::new(root.to_path_buf()); |
| 728 | let tool = FileSearchTool; |
| 729 | let result = tool |
| 730 | .execute(json!({"query": "main", "limit": 5}), &ctx) |
| 731 | .await |
| 732 | .expect("execute"); |
| 733 | |
| 734 | assert!(result.success); |
| 735 | assert!(result.content.contains("main.rs")); |
| 736 | } |
| 737 | |
| 738 | #[tokio::test] |
| 739 | async fn test_file_search_respects_gitignore() { |
| 740 | let tmp = tempdir().expect("tempdir"); |
| 741 | let root = tmp.path(); |
| 742 | std::fs::write(root.join(".gitignore"), "ignored.txt\n").expect("write"); |
| 743 | std::fs::write(root.join("ignored.txt"), "nope\n").expect("write"); |
| 744 | std::fs::write(root.join("keep.txt"), "ok\n").expect("write"); |
| 745 | |
| 746 | let ctx = ToolContext::new(root.to_path_buf()); |
| 747 | let tool = FileSearchTool; |
| 748 | let result = tool |
| 749 | .execute(json!({"query": "txt"}), &ctx) |
| 750 | .await |
| 751 | .expect("execute"); |
| 752 | |
| 753 | assert!(result.success); |
| 754 | assert!(!result.content.contains("ignored.txt")); |
| 755 | assert!(result.content.contains("keep.txt")); |
| 756 | } |
| 757 | |
| 758 | #[tokio::test] |
| 759 | async fn test_file_search_extension_filter() { |
| 760 | let tmp = tempdir().expect("tempdir"); |
| 761 | let root = tmp.path(); |
| 762 | std::fs::write(root.join("main.rs"), "fn main() {}\n").expect("write"); |
| 763 | std::fs::write(root.join("notes.md"), "docs\n").expect("write"); |
| 764 | |
| 765 | let ctx = ToolContext::new(root.to_path_buf()); |
| 766 | let tool = FileSearchTool; |
| 767 | let result = tool |
| 768 | .execute(json!({"query": "m", "extensions": ["rs"]}), &ctx) |
| 769 | .await |
| 770 | .expect("execute"); |
| 771 | |
| 772 | assert!(result.success); |
| 773 | assert!(result.content.contains("main.rs")); |
| 774 | assert!(!result.content.contains("notes.md")); |
| 775 | } |
| 776 | |
| 777 | #[tokio::test] |
| 778 | async fn test_file_search_exclude_filter() { |
| 779 | let tmp = tempdir().expect("tempdir"); |
| 780 | let root = tmp.path(); |
| 781 | std::fs::create_dir_all(root.join("fixtures")).expect("mkdir"); |
| 782 | std::fs::write(root.join("fixtures").join("needle.txt"), "no\n").expect("write"); |
| 783 | std::fs::write(root.join("needle.txt"), "yes\n").expect("write"); |
| 784 | |
| 785 | let ctx = ToolContext::new(root.to_path_buf()); |
| 786 | let tool = FileSearchTool; |
| 787 | let result = tool |
| 788 | .execute(json!({"query": "needle", "exclude": ["fixtures/**"]}), &ctx) |
| 789 | .await |
| 790 | .expect("execute"); |
| 791 | |
| 792 | assert!(result.success); |
| 793 | let body: Value = serde_json::from_str(&result.content).expect("search json"); |
| 794 | let files: Vec<&str> = body["files"] |
| 795 | .as_array() |
| 796 | .expect("files") |
| 797 | .iter() |
| 798 | .filter_map(Value::as_str) |
| 799 | .collect(); |
| 800 | assert!(files.contains(&"needle.txt")); |
| 801 | assert_eq!(body["total_matches"], json!(1)); |
| 802 | assert_eq!(body["truncated"], json!(false)); |
| 803 | assert!(!result.content.contains("fixtures/needle.txt")); |
| 804 | } |
| 805 | |
| 806 | #[tokio::test] |
| 807 | async fn test_file_search_exclude_appends_to_defaults_and_skips_hidden_dirs() { |
| 808 | let tmp = tempdir().expect("tempdir"); |
| 809 | let root = tmp.path(); |
| 810 | for dir in ["target", "fixtures", ".scratch", ".github"] { |
| 811 | std::fs::create_dir_all(root.join(dir)).expect("mkdir"); |
| 812 | std::fs::write(root.join(dir).join("needle.txt"), "no\n").expect("write"); |
| 813 | } |
| 814 | std::fs::write(root.join("needle.txt"), "yes\n").expect("write"); |
| 815 | let ctx = ToolContext::new(root.to_path_buf()); |
| 816 | let files = |content: &str| -> Vec<String> { |
| 817 | let body: Value = serde_json::from_str(content).expect("search json"); |
| 818 | body["files"] |
| 819 | .as_array() |
| 820 | .expect("files") |
| 821 | .iter() |
| 822 | .filter_map(Value::as_str) |
| 823 | .map(ToOwned::to_owned) |
| 824 | .collect() |
| 825 | }; |
| 826 | |
| 827 | let appended = FileSearchTool |
| 828 | .execute(json!({"query": "needle", "exclude": ["fixtures/**"]}), &ctx) |
| 829 | .await |
| 830 | .expect("execute"); |
| 831 | assert_eq!(files(&appended.content), vec!["needle.txt"]); |
| 832 | |
| 833 | let replaced = FileSearchTool |
| 834 | .execute( |
| 835 | json!({"query": "needle", "exclude": ["fixtures/**"], "replace_default_excludes": true}), |
| 836 | &ctx, |
| 837 | ) |
| 838 | .await |
| 839 | .expect("execute"); |
| 840 | let replaced = files(&replaced.content); |
| 841 | assert!( |
| 842 | replaced.contains(&"target/needle.txt".to_string()), |
| 843 | "{replaced:?}" |
| 844 | ); |
| 845 | assert!( |
| 846 | !replaced.iter().any(|path| path.starts_with('.')), |
| 847 | "{replaced:?}" |
| 848 | ); |
| 849 | |
| 850 | let targeted = FileSearchTool |
| 851 | .execute(json!({"query": ".github/needle"}), &ctx) |
| 852 | .await |
| 853 | .expect("execute"); |
| 854 | assert!( |
| 855 | files(&targeted.content).contains(&".github/needle.txt".to_string()), |
| 856 | "{}", |
| 857 | targeted.content |
| 858 | ); |
| 859 | } |
| 860 | |
| 861 | #[tokio::test] |
| 862 | async fn test_file_search_default_excludes_build_artifacts() { |
| 863 | let tmp = tempdir().expect("tempdir"); |
| 864 | let root = tmp.path(); |
| 865 | std::fs::create_dir_all(root.join("target")).expect("mkdir"); |
| 866 | std::fs::write(root.join("target").join("needle.txt"), "no\n").expect("write"); |
| 867 | std::fs::create_dir_all(root.join("member").join("target")).expect("mkdir nested"); |
| 868 | std::fs::write( |
| 869 | root.join("member").join("target").join("nested_needle.txt"), |
| 870 | "no\n", |
| 871 | ) |
| 872 | .expect("write nested"); |
| 873 | std::fs::write(root.join("needle.txt"), "yes\n").expect("write"); |
| 874 | |
| 875 | let ctx = ToolContext::new(root.to_path_buf()); |
| 876 | let tool = FileSearchTool; |
| 877 | let result = tool |
| 878 | .execute(json!({"query": "needle"}), &ctx) |
| 879 | .await |
| 880 | .expect("execute"); |
| 881 | |
| 882 | assert!(result.success); |
| 883 | let body: Value = serde_json::from_str(&result.content).expect("search json"); |
| 884 | let files: Vec<&str> = body["files"] |
| 885 | .as_array() |
| 886 | .expect("files") |
| 887 | .iter() |
| 888 | .filter_map(Value::as_str) |
| 889 | .collect(); |
| 890 | assert!(files.contains(&"needle.txt")); |
| 891 | assert_eq!(body["total_matches"], json!(1)); |
| 892 | assert_eq!(body["truncated"], json!(false)); |
| 893 | assert!(!result.content.contains("target/needle.txt")); |
| 894 | assert!(!result.content.contains("nested_needle.txt")); |
| 895 | } |
| 896 | |
| 897 | #[tokio::test] |
| 898 | async fn test_file_search_default_excludes_stop_at_the_directory() { |
| 899 | let tmp = tempdir().expect("tempdir"); |
| 900 | let root = tmp.path(); |
| 901 | std::fs::create_dir_all(root.join("build")).expect("mkdir"); |
| 902 | std::fs::create_dir_all(root.join("builders")).expect("mkdir"); |
| 903 | std::fs::write(root.join("build").join("build_out.rs"), "no\n").expect("write"); |
| 904 | std::fs::write(root.join("build.rs"), "yes\n").expect("write"); |
| 905 | std::fs::write(root.join("builders").join("build_x.rs"), "yes\n").expect("write"); |
| 906 | |
| 907 | let ctx = ToolContext::new(root.to_path_buf()); |
| 908 | let result = FileSearchTool |
| 909 | .execute(json!({"query": "build", "limit": 20}), &ctx) |
| 910 | .await |
| 911 | .expect("execute"); |
| 912 | |
| 913 | let body: Value = serde_json::from_str(&result.content).expect("search json"); |
| 914 | let paths: Vec<&str> = body["files"] |
| 915 | .as_array() |
| 916 | .expect("files") |
| 917 | .iter() |
| 918 | .filter_map(Value::as_str) |
| 919 | .collect(); |
| 920 | // `build/**` hides the build directory, not same-prefix siblings. |
| 921 | assert!(paths.contains(&"build.rs"), "{paths:?}"); |
| 922 | assert!(paths.contains(&"builders/build_x.rs"), "{paths:?}"); |
| 923 | assert!(!paths.contains(&"build/build_out.rs"), "{paths:?}"); |
| 924 | assert_eq!(body["total_matches"], json!(2)); |
| 925 | assert_eq!(body["truncated"], json!(false)); |
| 926 | } |
| 927 | |
| 928 | #[tokio::test] |
| 929 | async fn test_file_search_respects_cancel_token() { |
| 930 | let tmp = tempdir().expect("tempdir"); |
| 931 | let root = tmp.path(); |
| 932 | std::fs::write(root.join("needle.txt"), "yes\n").expect("write"); |
| 933 | let cancel_token = CancellationToken::new(); |
| 934 | cancel_token.cancel(); |
| 935 | let ctx = ToolContext::new(root.to_path_buf()).with_cancel_token(cancel_token); |
| 936 | |
| 937 | let tool = FileSearchTool; |
| 938 | let err = tool |
| 939 | .execute(json!({"query": "needle"}), &ctx) |
| 940 | .await |
| 941 | .expect_err("cancelled file_search should return an error"); |
| 942 | |
| 943 | assert!( |
| 944 | format!("{err:?}").contains("cancelled"), |
| 945 | "unexpected error: {err:?}" |
| 946 | ); |
| 947 | } |
| 948 | |
| 949 | #[tokio::test] |
| 950 | async fn test_file_search_blocking_wrapper_reports_timeout() { |
| 951 | let (finished, worker_finished) = tokio::sync::oneshot::channel(); |
| 952 | let err = run_blocking_file_search(Duration::from_millis(1), None, move |cancel_token| { |
| 953 | while !cancel_token.is_cancelled() { |
| 954 | std::thread::sleep(Duration::from_millis(1)); |
| 955 | } |
| 956 | let _ = finished.send(cancel_token.is_cancelled()); |
| 957 | Err(file_search_cancelled()) |
| 958 | }) |
| 959 | .await |
| 960 | .expect_err("slow file_search worker should time out"); |
| 961 | |
| 962 | assert!( |
| 963 | matches!(err, ToolError::Timeout { seconds: 1 }), |
| 964 | "unexpected error: {err:?}" |
| 965 | ); |
| 966 | assert!( |
| 967 | tokio::time::timeout(Duration::from_secs(1), worker_finished) |
| 968 | .await |
| 969 | .expect("timed-out worker must stop") |
| 970 | .expect("worker completion"), |
| 971 | "timeout must cancel the worker without a parent cancellation token" |
| 972 | ); |
| 973 | } |
| 974 | |
| 975 | #[tokio::test] |
| 976 | #[cfg(unix)] |
| 977 | async fn test_file_search_does_not_follow_symlinked_files() { |
| 978 | let tmp = tempdir().expect("tempdir"); |
| 979 | let root = tmp.path().join("workspace"); |
| 980 | let outside = tmp.path().join("outside"); |
| 981 | std::fs::create_dir_all(&root).expect("mkdir workspace"); |
| 982 | std::fs::create_dir_all(&outside).expect("mkdir outside"); |
| 983 | let outside_file = outside.join("secret.txt"); |
| 984 | std::fs::write(&outside_file, "outside\n").expect("write outside"); |
| 985 | std::os::unix::fs::symlink(&outside_file, root.join("secret.txt")).expect("symlink"); |
| 986 | |
| 987 | let ctx = ToolContext::new(root); |
| 988 | let tool = FileSearchTool; |
| 989 | let result = tool |
| 990 | .execute(json!({"query": "secret"}), &ctx) |
| 991 | .await |
| 992 | .expect("execute"); |
| 993 | |
| 994 | assert!(result.success); |
| 995 | assert!(!result.content.contains("secret.txt")); |
| 996 | } |
| 997 | |
| 998 | /// F1: searching a denied directory is enumeration of it — `file_search` |
| 999 | /// with its root inside a denied tree must refuse, matching the OS layer |
| 1000 | /// (Seatbelt `deny file-read*` blocks readdir of denied dirs). |
| 1001 | #[tokio::test] |
| 1002 | async fn test_file_search_refuses_a_denied_root() { |
| 1003 | let holder = tempdir().expect("tempdir"); |
| 1004 | let project = holder.path().join("project"); |
| 1005 | // Deterministic anchor: the `.env` filename rule denies any path whose |
| 1006 | // file name is `.env`, directory or not. |
| 1007 | std::fs::create_dir_all(project.join(".env")).expect("mkdir"); |
| 1008 | std::fs::write(project.join(".env").join("token"), "x\n").expect("write"); |
| 1009 | |
| 1010 | let ctx = ToolContext::new(project.clone()); |
| 1011 | let tool = FileSearchTool; |
| 1012 | let error = tool |
| 1013 | .execute( |
| 1014 | json!({"query": "token", "path": project.join(".env")}), |
| 1015 | &ctx, |
| 1016 | ) |
| 1017 | .await |
| 1018 | .expect_err("a denied search root must be refused, not walked"); |
| 1019 | |
| 1020 | assert!( |
| 1021 | matches!(error, ToolError::PermissionDenied { .. }), |
| 1022 | "expected a permission refusal, got: {error:?}" |
| 1023 | ); |
| 1024 | } |
| 1025 | |
| 1026 | /// F1: a walk rooted *above* a denied path must not enumerate names inside |
| 1027 | /// it — `path = "~"` must not surface `~/.ssh/id_rsa`, and a project root |
| 1028 | /// must not surface its `.env` (denied by name under the default list). |
| 1029 | #[tokio::test] |
| 1030 | async fn test_file_search_skips_denied_entries_during_the_walk() { |
| 1031 | let tmp = tempdir().expect("tempdir"); |
| 1032 | let root = tmp.path(); |
| 1033 | std::fs::write(root.join("needle.txt"), "yes\n").expect("write"); |
| 1034 | std::fs::write(root.join(".env"), "SECRET=1\n").expect("write env"); |
| 1035 | std::fs::write(root.join(".env.local"), "SECRET=2\n").expect("write env local"); |
| 1036 | std::fs::create_dir_all(root.join("denied").join(".env")).expect("mkdir denied"); |
| 1037 | std::fs::write( |
| 1038 | root.join("denied").join(".env").join("needle-secret.txt"), |
| 1039 | "SECRET=3\n", |
| 1040 | ) |
| 1041 | .expect("write denied child"); |
| 1042 | |
| 1043 | let ctx = ToolContext::new(root.to_path_buf()); |
| 1044 | let tool = FileSearchTool; |
| 1045 | let result = tool |
| 1046 | .execute(json!({"query": "env"}), &ctx) |
| 1047 | .await |
| 1048 | .expect("execute"); |
| 1049 | |
| 1050 | assert!(result.success); |
| 1051 | assert!( |
| 1052 | !result.content.contains(".env"), |
| 1053 | "denied entries must not be enumerated by a name search: {}", |
| 1054 | result.content |
| 1055 | ); |
| 1056 | |
| 1057 | // The innocent sibling is still found — the deny-list filters, it does |
| 1058 | // not blank the search. |
| 1059 | let result = tool |
| 1060 | .execute(json!({"query": "needle"}), &ctx) |
| 1061 | .await |
| 1062 | .expect("execute"); |
| 1063 | assert!(result.success); |
| 1064 | assert!(result.content.contains("needle.txt")); |
| 1065 | assert!(!result.content.contains("needle-secret.txt")); |
| 1066 | } |
| 1067 | |
| 1068 | #[tokio::test] |
| 1069 | async fn test_file_search_large_non_git_tree_skips_heavy_dirs_and_returns_partial_on_budget() { |
| 1070 | let tmp = tempdir().expect("tempdir"); |
| 1071 | let root = tmp.path(); |
| 1072 | for dir in 0..40 { |
| 1073 | let shard = root.join("artifacts").join(format!("run-{dir}")); |
| 1074 | std::fs::create_dir_all(&shard).expect("mkdir shard"); |
| 1075 | for file in 0..50 { |
| 1076 | std::fs::write(shard.join(format!("log-{file}.txt")), "x\n").expect("write"); |
| 1077 | } |
| 1078 | let heavy = root.join("worktrees").join(format!("wt-{dir}")); |
| 1079 | for skipped in ["target/debug", "node_modules/pkg", ".git/objects"] { |
| 1080 | std::fs::create_dir_all(heavy.join(skipped)).expect("mkdir heavy"); |
| 1081 | std::fs::write(heavy.join(skipped).join("READINESS.md"), "no\n").expect("write"); |
| 1082 | } |
| 1083 | std::fs::write(heavy.join(".gitignore"), "scratch/\n").expect("write ignore"); |
| 1084 | std::fs::create_dir_all(heavy.join("scratch")).expect("mkdir scratch"); |
| 1085 | std::fs::write(heavy.join("scratch").join("READINESS.md"), "no\n").expect("write"); |
| 1086 | } |
| 1087 | let wanted = root.join("ops").join("releases").join("launch"); |
| 1088 | std::fs::create_dir_all(&wanted).expect("mkdir wanted"); |
| 1089 | std::fs::write(wanted.join("READINESS.md"), "yes\n").expect("write wanted"); |
| 1090 | let deep = root.join("deep").join("a").join("b").join("c").join("d"); |
| 1091 | std::fs::create_dir_all(&deep).expect("mkdir deep"); |
| 1092 | std::fs::write(deep.join("READINESS.md"), "yes\n").expect("write deep"); |
| 1093 | |
| 1094 | let search = |budget| { |
| 1095 | search_files_async( |
| 1096 | "READINESS.md".to_string(), |
| 1097 | root.to_path_buf(), |
| 1098 | root.to_path_buf(), |
| 1099 | Vec::new(), |
| 1100 | parse_exclude_patterns(&json!({})), |
| 1101 | 20, |
| 1102 | None, |
| 1103 | FILE_SEARCH_TIMEOUT, |
| 1104 | budget, |
| 1105 | false, |
| 1106 | ) |
| 1107 | }; |
| 1108 | |
| 1109 | let complete = search(FILE_SEARCH_BUDGET).await.expect("complete search"); |
| 1110 | assert!(complete.stopped_after.is_none()); |
| 1111 | let mut paths: Vec<&str> = complete.matches.iter().map(|m| m.path.as_str()).collect(); |
| 1112 | paths.sort_unstable(); |
| 1113 | assert_eq!( |
| 1114 | paths, |
| 1115 | [ |
| 1116 | "deep/a/b/c/d/READINESS.md", |
| 1117 | "ops/releases/launch/READINESS.md" |
| 1118 | ] |
| 1119 | ); |
| 1120 | |
| 1121 | let partial = search(Duration::ZERO) |
| 1122 | .await |
| 1123 | .expect("budget stop is not a failure"); |
| 1124 | assert!(partial.stopped_after.is_some()); |
| 1125 | let result = file_search_result(partial).expect("partial result"); |
| 1126 | assert!(result.success); |
| 1127 | let body: Value = serde_json::from_str(&result.content).expect("partial json"); |
| 1128 | assert_eq!(body["partial"], json!(true)); |
| 1129 | assert_eq!(body["truncated"], json!(true)); |
| 1130 | assert!(body["files"].is_array()); |
| 1131 | assert!(body["total_matches"].is_u64()); |
| 1132 | assert!( |
| 1133 | body["note"] |
| 1134 | .as_str() |
| 1135 | .is_some_and(|note| note.contains("Narrow `path`")) |
| 1136 | ); |
| 1137 | } |
| 1138 | |
| 1139 | #[tokio::test] |
| 1140 | async fn test_file_search_reports_total_matches_and_truncation_at_limit() { |
| 1141 | let tmp = tempdir().expect("tempdir"); |
| 1142 | let root = tmp.path(); |
| 1143 | let deep = root.join("a").join("b").join("c").join("d").join("e"); |
| 1144 | std::fs::create_dir_all(&deep).expect("mkdir deep"); |
| 1145 | for idx in 1..=4 { |
| 1146 | std::fs::write(root.join(format!("item_{idx}.rs")), "fn x() {}\n").expect("write"); |
| 1147 | } |
| 1148 | std::fs::write(deep.join("item_5.rs"), "fn x() {}\n").expect("write deep"); |
| 1149 | |
| 1150 | let ctx = ToolContext::new(root.to_path_buf()); |
| 1151 | let capped = FileSearchTool |
| 1152 | .execute(json!({"query": "item", "limit": 2}), &ctx) |
| 1153 | .await |
| 1154 | .expect("capped execute"); |
| 1155 | let capped_body: Value = serde_json::from_str(&capped.content).expect("capped json"); |
| 1156 | assert_eq!(capped_body["files"].as_array().expect("files").len(), 2); |
| 1157 | assert_eq!(capped_body["total_matches"], json!(5)); |
| 1158 | assert_eq!(capped_body["truncated"], json!(true)); |
| 1159 | |
| 1160 | let exact = FileSearchTool |
| 1161 | .execute(json!({"query": "item", "limit": 5}), &ctx) |
| 1162 | .await |
| 1163 | .expect("exact execute"); |
| 1164 | let exact_body: Value = serde_json::from_str(&exact.content).expect("exact json"); |
| 1165 | assert_eq!(exact_body["files"].as_array().expect("files").len(), 5); |
| 1166 | assert_eq!(exact_body["total_matches"], json!(5)); |
| 1167 | assert_eq!(exact_body["truncated"], json!(false)); |
| 1168 | } |
| 1169 | |
| 1170 | #[allow(clippy::await_holding_lock)] |
| 1171 | #[tokio::test] |
| 1172 | async fn test_file_search_skips_and_refuses_codewhale_credential_paths() { |
| 1173 | use crate::test_support::{EnvVarGuard, lock_test_env}; |
| 1174 | |
| 1175 | let _lock = lock_test_env(); |
| 1176 | let tmp = tempdir().expect("tempdir"); |
| 1177 | let root = tmp.path().canonicalize().expect("canon root"); |
| 1178 | let cw_home = root.join("cw-home"); |
| 1179 | std::fs::create_dir_all(cw_home.join("secrets")).expect("mkdir secrets"); |
| 1180 | let _cw_home_guard = EnvVarGuard::set("CODEWHALE_HOME", &cw_home); |
| 1181 | let _cfg_guard = EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"); |
| 1182 | let _legacy_cfg_guard = EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"); |
| 1183 | |
| 1184 | std::fs::write(cw_home.join("config.toml"), "api_key = \"secret\"\n").expect("write cfg"); |
| 1185 | std::fs::write(cw_home.join("secrets").join("vault.json"), "{}\n").expect("write vault"); |
| 1186 | std::fs::write(root.join("config_example.toml"), "ok = true\n").expect("write public"); |
| 1187 | |
| 1188 | let ctx = ToolContext::new(&root); |
| 1189 | let result = FileSearchTool |
| 1190 | .execute(json!({"query": "config"}), &ctx) |
| 1191 | .await |
| 1192 | .expect("search succeeds"); |
| 1193 | assert!(!result.content.contains("cw-home"), "{}", result.content); |
| 1194 | assert!( |
| 1195 | result.content.contains("config_example.toml"), |
| 1196 | "{}", |
| 1197 | result.content |
| 1198 | ); |
| 1199 | |
| 1200 | let vault_result = FileSearchTool |
| 1201 | .execute(json!({"query": "vault"}), &ctx) |
| 1202 | .await |
| 1203 | .expect("vault search succeeds"); |
| 1204 | assert!( |
| 1205 | !vault_result.content.contains("vault.json"), |
| 1206 | "{}", |
| 1207 | vault_result.content |
| 1208 | ); |
| 1209 | |
| 1210 | let root_err = FileSearchTool |
| 1211 | .execute( |
| 1212 | json!({"query": "vault", "path": cw_home.join("secrets").to_string_lossy()}), |
| 1213 | &ctx, |
| 1214 | ) |
| 1215 | .await |
| 1216 | .expect_err("direct search rooted at credential dir must be refused"); |
| 1217 | assert!( |
| 1218 | matches!(root_err, ToolError::PermissionDenied { .. }), |
| 1219 | "{root_err:?}" |
| 1220 | ); |
| 1221 | } |
| 1222 | } |
| 1223 |