返回 CodeWhale
tests.rs
根目录 / crates / engine / src / tools / search / tests.rs
1 use std::fs;
2
3 use serde_json::{Value, json};
4 use tempfile::tempdir;
5 use tokio_util::sync::CancellationToken;
6
7 use crate::tools::spec::{ApprovalRequirement, ToolContext, ToolSpec};
8
9 use super::{GrepFilesTool, matches_glob};
10
11 #[test]
12 fn grep_description_matches_default_exclusion_behavior() {
13 let description = GrepFilesTool.description();
14
15 assert!(description.contains("skips common non-code directories"));
16 assert!(!description.contains("respects `.gitignore`"));
17 }
18
19 /// Representative of the ~150 shared `optional_*` call sites outside the
20 /// three that motivated the change: a wrong type is refused by name, an
21 /// absent or null field still takes its default.
22 #[tokio::test]
23 async fn grep_refuses_mistyped_optional_parameters_by_name() {
24 let tmp = tempdir().expect("tempdir");
25 fs::write(tmp.path().join("a.txt"), "needle\n").expect("write");
26 let ctx = ToolContext::new(tmp.path());
27
28 for (field, input) in [
29 (
30 "max_results",
31 json!({"pattern": "needle", "max_results": "10"}),
32 ),
33 (
34 "case_insensitive",
35 json!({"pattern": "needle", "case_insensitive": "true"}),
36 ),
37 (
38 "context_lines",
39 json!({"pattern": "needle", "context_lines": 2.5}),
40 ),
41 ("path", json!({"pattern": "needle", "path": ["."]})),
42 ] {
43 let err = GrepFilesTool
44 .execute(input, &ctx)
45 .await
46 .expect_err("a mistyped optional parameter must be refused");
47 let err = err.to_string();
48 assert!(err.contains(field), "error must name '{field}': {err}");
49 }
50
51 GrepFilesTool
52 .execute(
53 json!({"pattern": "needle", "max_results": Value::Null, "path": Value::Null}),
54 &ctx,
55 )
56 .await
57 .expect("explicit nulls read as absent");
58 }
59
60 /// The model supplies the pattern, so it compiles through the bounded
61 /// regex cache: an over-long pattern is refused, not compiled.
62 #[tokio::test]
63 async fn grep_refuses_a_pattern_past_the_user_regex_length_cap() {
64 let tmp = tempdir().expect("tempdir");
65 fs::write(tmp.path().join("a.txt"), "needle\n").expect("write");
66 let ctx = ToolContext::new(tmp.path());
67 let long = "a".repeat(codewhale_runtime::regex_cache::MAX_USER_REGEX_PATTERN_BYTES + 1);
68 let err = GrepFilesTool
69 .execute(json!({ "pattern": long }), &ctx)
70 .await
71 .expect_err("an over-long pattern must be refused");
72 assert!(err.to_string().contains("limit"), "{err}");
73 }
74
75 #[test]
76 fn test_matches_glob_star() {
77 assert!(matches_glob("test.rs", "*.rs"));
78 assert!(matches_glob("foo.rs", "*.rs"));
79 assert!(!matches_glob("test.ts", "*.rs"));
80 assert!(!matches_glob("test.rs.bak", "*.rs"));
81 }
82
83 #[test]
84 fn test_matches_glob_question() {
85 assert!(matches_glob("test.rs", "test.??"));
86 assert!(!matches_glob("test.rs", "test.?"));
87 }
88
89 #[test]
90 fn test_matches_glob_double_star() {
91 assert!(matches_glob("src/main.rs", "src/**"));
92 assert!(matches_glob("src/lib/mod.rs", "src/**"));
93 assert!(matches_glob("node_modules/pkg/index.js", "node_modules/*"));
94 }
95
96 #[test]
97 fn test_matches_glob_path() {
98 assert!(matches_glob("src/main.rs", "src/*.rs"));
99 assert!(!matches_glob("lib/main.rs", "src/*.rs"));
100 }
101
102 /// Regression for #249: byte-index slicing panics on multi-byte
103 /// characters inside filenames like `dialogue_line__冰糖.mp3`.
104 #[test]
105 fn test_matches_glob_unicode_filename() {
106 let filename = "dialogue_line__冰糖.mp3";
107 // The filename should match *.mp3 without panicking.
108 assert!(matches_glob(filename, "*.mp3"));
109 // Asterisk matching against multi-byte characters must succeed.
110 assert!(matches_glob(filename, "dialogue_line__*"));
111 // Literal multi-byte characters inside the pattern must match.
112 assert!(matches_glob(filename, "*冰糖*"));
113 // Non-matching pattern must not panic either.
114 assert!(!matches_glob(filename, "nonexistent*"));
115 }
116
117 #[tokio::test]
118 async fn test_grep_files_basic() {
119 let tmp = tempdir().expect("tempdir");
120 let ctx = ToolContext::new(tmp.path().to_path_buf());
121
122 // Create test files
123 fs::write(
124 tmp.path().join("test.rs"),
125 "fn main() {\n println!(\"hello\");\n}\n",
126 )
127 .expect("write");
128 fs::write(
129 tmp.path().join("lib.rs"),
130 "pub fn hello() {}\npub fn world() {}\n",
131 )
132 .expect("write");
133
134 let tool = GrepFilesTool;
135 let result = tool
136 .execute(json!({"pattern": "fn"}), &ctx)
137 .await
138 .expect("execute");
139
140 assert!(result.success);
141 assert!(result.content.contains("main"));
142 assert!(result.content.contains("hello"));
143 }
144
145 #[tokio::test]
146 async fn test_grep_files_with_context() {
147 let tmp = tempdir().expect("tempdir");
148 let ctx = ToolContext::new(tmp.path().to_path_buf());
149
150 fs::write(
151 tmp.path().join("test.txt"),
152 "line1\nline2\nMATCH\nline4\nline5\n",
153 )
154 .expect("write");
155
156 let tool = GrepFilesTool;
157 let result = tool
158 .execute(json!({"pattern": "MATCH", "context_lines": 1}), &ctx)
159 .await
160 .expect("execute");
161
162 assert!(result.success);
163 assert!(result.content.contains("line2")); // context before
164 assert!(result.content.contains("line4")); // context after
165
166 let parsed: Value = serde_json::from_str(&result.content).unwrap();
167 let matches = parsed["matches"].as_array().unwrap();
168 assert_eq!(matches.len(), 1);
169 assert_eq!(matches[0]["context_before"], "line2");
170 assert_eq!(matches[0]["context_after"], "line4");
171 assert!(matches[0]["context_before"].is_string());
172 assert!(matches[0]["context_after"].is_string());
173 }
174
175 #[tokio::test]
176 async fn test_grep_files_multi_line_context_remains_arrays() {
177 let tmp = tempdir().expect("tempdir");
178 let ctx = ToolContext::new(tmp.path().to_path_buf());
179
180 fs::write(tmp.path().join("test.txt"), "a\nb\nMATCH\nd\ne\n").expect("write");
181
182 let tool = GrepFilesTool;
183 let result = tool
184 .execute(json!({"pattern": "MATCH", "context_lines": 2}), &ctx)
185 .await
186 .expect("execute");
187
188 let parsed: Value = serde_json::from_str(&result.content).unwrap();
189 let matches = parsed["matches"].as_array().unwrap();
190 assert_eq!(matches.len(), 1);
191 assert_eq!(matches[0]["context_before"], json!(["a", "b"]));
192 assert_eq!(matches[0]["context_after"], json!(["d", "e"]));
193 }
194
195 #[tokio::test]
196 async fn test_grep_files_case_insensitive() {
197 let tmp = tempdir().expect("tempdir");
198 let ctx = ToolContext::new(tmp.path().to_path_buf());
199
200 fs::write(
201 tmp.path().join("test.txt"),
202 "Hello World\nHELLO WORLD\nhello world\n",
203 )
204 .expect("write");
205
206 let tool = GrepFilesTool;
207 let result = tool
208 .execute(json!({"pattern": "hello", "case_insensitive": true}), &ctx)
209 .await
210 .expect("execute");
211
212 assert!(result.success);
213 // Should find all 3 lines
214 let parsed: Value = serde_json::from_str(&result.content).unwrap();
215 assert_eq!(parsed["total_matches"].as_u64().unwrap(), 3);
216 }
217
218 #[tokio::test]
219 async fn test_grep_files_include_filter() {
220 let tmp = tempdir().expect("tempdir");
221 let ctx = ToolContext::new(tmp.path().to_path_buf());
222
223 fs::write(tmp.path().join("test.rs"), "fn test() {}\n").expect("write");
224 fs::write(tmp.path().join("test.js"), "function test() {}\n").expect("write");
225
226 let tool = GrepFilesTool;
227 let result = tool
228 .execute(json!({"pattern": "test", "include": ["*.rs"]}), &ctx)
229 .await
230 .expect("execute");
231
232 assert!(result.success);
233 // Should only match .rs file
234 let parsed: Value = serde_json::from_str(&result.content).unwrap();
235 let matches = parsed["matches"].as_array().unwrap();
236 assert_eq!(matches.len(), 1);
237 let file = matches[0]["file"].as_str().unwrap();
238 assert!(
239 file.rsplit('.')
240 .next()
241 .is_some_and(|ext| ext.eq_ignore_ascii_case("rs"))
242 );
243 }
244
245 #[tokio::test]
246 #[cfg(unix)]
247 async fn test_grep_files_does_not_follow_symlinked_files() {
248 let tmp = tempdir().expect("tempdir");
249 let root = tmp.path().join("workspace");
250 let outside = tmp.path().join("outside");
251 std::fs::create_dir_all(&root).expect("mkdir workspace");
252 std::fs::create_dir_all(&outside).expect("mkdir outside");
253 let outside_file = outside.join("secret.txt");
254 fs::write(&outside_file, "NEEDLE\n").expect("write outside");
255 std::os::unix::fs::symlink(&outside_file, root.join("secret.txt")).expect("symlink");
256
257 let ctx = ToolContext::new(root);
258 let tool = GrepFilesTool;
259 let result = tool
260 .execute(json!({"pattern": "NEEDLE"}), &ctx)
261 .await
262 .expect("execute");
263
264 assert!(result.success);
265 let parsed: Value = serde_json::from_str(&result.content).unwrap();
266 assert_eq!(parsed["total_matches"].as_u64().unwrap(), 0);
267 assert_eq!(parsed["files_searched"].as_u64().unwrap(), 0);
268 }
269
270 #[tokio::test]
271 #[cfg(unix)]
272 async fn test_grep_files_default_mode_skips_symlinked_directories_but_keeps_real_files() {
273 let tmp = tempdir().expect("tempdir");
274 let workspace = tmp.path().join("workspace");
275 let real_dir = workspace.join("real");
276 std::fs::create_dir_all(&real_dir).expect("mkdir workspace");
277 fs::write(real_dir.join("needle.txt"), "NEEDLE\n").expect("write real file");
278 std::os::unix::fs::symlink(&workspace, real_dir.join("loop")).expect("symlink loop");
279
280 let ctx = ToolContext::new(workspace);
281 let tool = GrepFilesTool;
282 let result = tool
283 .execute(json!({"pattern": "NEEDLE"}), &ctx)
284 .await
285 .expect("execute");
286
287 assert!(result.success);
288 let parsed: Value = serde_json::from_str(&result.content).unwrap();
289 assert_eq!(parsed["total_matches"].as_u64().unwrap(), 1);
290 assert_eq!(parsed["files_searched"].as_u64().unwrap(), 1);
291 let matches = parsed["matches"].as_array().unwrap();
292 assert_eq!(matches.len(), 1);
293 assert!(
294 matches[0]["file"]
295 .as_str()
296 .unwrap()
297 .ends_with("real/needle.txt")
298 );
299 }
300
301 #[tokio::test]
302 #[cfg(unix)]
303 async fn test_grep_files_follow_symlinks_avoids_directory_cycles() {
304 let tmp = tempdir().expect("tempdir");
305 let workspace = tmp.path().join("workspace");
306 let real_dir = workspace.join("real");
307 fs::create_dir_all(&real_dir).expect("mkdir");
308 fs::write(real_dir.join("needle.txt"), "NEEDLE\n").expect("write");
309 std::os::unix::fs::symlink(&workspace, real_dir.join("loop")).expect("symlink loop");
310
311 let ctx = ToolContext::new(workspace).with_follow_symlinks(true);
312 let tool = GrepFilesTool;
313 let result = tool
314 .execute(json!({"pattern": "NEEDLE"}), &ctx)
315 .await
316 .expect("execute");
317
318 assert!(result.success);
319 let parsed: Value = serde_json::from_str(&result.content).unwrap();
320 assert_eq!(parsed["total_matches"].as_u64().unwrap(), 1);
321 assert_eq!(parsed["files_searched"].as_u64().unwrap(), 1);
322 let matches = parsed["matches"].as_array().unwrap();
323 assert!(matches[0]["file"].as_str().unwrap().ends_with("needle.txt"));
324 }
325
326 #[tokio::test]
327 async fn test_grep_files_invalid_regex() {
328 let tmp = tempdir().expect("tempdir");
329 let ctx = ToolContext::new(tmp.path().to_path_buf());
330
331 let tool = GrepFilesTool;
332 let result = tool.execute(json!({"pattern": "[invalid"}), &ctx).await;
333
334 assert!(result.is_err());
335 }
336
337 #[tokio::test]
338 async fn test_grep_files_respects_cancel_token() {
339 let tmp = tempdir().expect("tempdir");
340 fs::write(tmp.path().join("test.txt"), "needle\n").expect("write");
341 let cancel_token = CancellationToken::new();
342 cancel_token.cancel();
343 let ctx = ToolContext::new(tmp.path().to_path_buf()).with_cancel_token(cancel_token);
344
345 let tool = GrepFilesTool;
346 let err = tool
347 .execute(json!({"pattern": "needle"}), &ctx)
348 .await
349 .expect_err("cancelled grep should return an error");
350
351 assert!(
352 format!("{err:?}").contains("cancelled"),
353 "unexpected error: {err:?}"
354 );
355 }
356
357 #[tokio::test]
358 async fn test_grep_files_streaming_stops_at_max_results() {
359 let tmp = tempdir().expect("tempdir");
360 let ctx = ToolContext::new(tmp.path().to_path_buf());
361
362 // Two files with many matches each; the walk must stop once the
363 // budget is exhausted without dropping context for the last match.
364 for name in ["a.txt", "b.txt"] {
365 let body: String = (1..=20).map(|n| format!("needle {n}\n")).collect();
366 fs::write(tmp.path().join(name), body).expect("write");
367 }
368
369 let tool = GrepFilesTool;
370 let result = tool
371 .execute(
372 json!({"pattern": "needle", "max_results": 5, "context_lines": 2}),
373 &ctx,
374 )
375 .await
376 .expect("execute");
377
378 assert!(result.success);
379 let parsed: Value = serde_json::from_str(&result.content).unwrap();
380 let matches = parsed["matches"].as_array().unwrap();
381 assert_eq!(matches.len(), 5);
382 assert_eq!(parsed["total_matches"].as_u64().unwrap(), 5);
383 // All five matches must come from the first file walked, in file
384 // order (streaming preserves walk order).
385 let first_file = matches[0]["file"].as_str().unwrap().to_string();
386 for m in matches {
387 assert_eq!(m["file"].as_str().unwrap(), first_file);
388 }
389 // The final in-budget match still gets its full after-context even
390 // though the match budget was exhausted on it.
391 assert_eq!(
392 matches[4]["context_after"],
393 json!(["needle 6", "needle 7"]),
394 "last match must keep after-context lines"
395 );
396 }
397
398 #[tokio::test]
399 async fn test_grep_files_ring_buffer_context_matches_full_read() {
400 let tmp = tempdir().expect("tempdir");
401 let ctx = ToolContext::new(tmp.path().to_path_buf());
402
403 // Matches at the start, middle, and end of the file exercise the
404 // partial before-context (ring not yet full) and truncated
405 // after-context (EOF) paths.
406 fs::write(
407 tmp.path().join("ctx.txt"),
408 "MATCH first\nb1\nb2\nb3\nMATCH mid\na1\na2\na3\nMATCH last\n",
409 )
410 .expect("write");
411
412 let tool = GrepFilesTool;
413 let result = tool
414 .execute(json!({"pattern": "MATCH", "context_lines": 2}), &ctx)
415 .await
416 .expect("execute");
417
418 let parsed: Value = serde_json::from_str(&result.content).unwrap();
419 let matches = parsed["matches"].as_array().unwrap();
420 assert_eq!(matches.len(), 3);
421 assert_eq!(matches[0]["context_before"], json!([]));
422 assert_eq!(matches[0]["context_after"], json!(["b1", "b2"]));
423 assert_eq!(matches[1]["context_before"], json!(["b2", "b3"]));
424 assert_eq!(matches[1]["context_after"], json!(["a1", "a2"]));
425 assert_eq!(matches[2]["context_before"], json!(["a2", "a3"]));
426 assert_eq!(matches[2]["context_after"], json!([]));
427 assert_eq!(matches[2]["line_number"].as_u64().unwrap(), 9);
428 }
429
430 #[tokio::test]
431 async fn test_grep_files_streaming_skips_invalid_utf8_files() {
432 let tmp = tempdir().expect("tempdir");
433 let ctx = ToolContext::new(tmp.path().to_path_buf());
434
435 // Invalid UTF-8 after a matching line: the whole file must be
436 // skipped, matching the historical read_to_string behavior.
437 fs::write(
438 tmp.path().join("binary.txt"),
439 [b"needle\n".as_slice(), &[0xFF, 0xFE, 0x00]].concat(),
440 )
441 .expect("write");
442 fs::write(tmp.path().join("clean.txt"), "needle\n").expect("write");
443
444 let tool = GrepFilesTool;
445 let result = tool
446 .execute(json!({"pattern": "needle"}), &ctx)
447 .await
448 .expect("execute");
449
450 let parsed: Value = serde_json::from_str(&result.content).unwrap();
451 assert_eq!(parsed["total_matches"].as_u64().unwrap(), 1);
452 assert_eq!(parsed["files_searched"].as_u64().unwrap(), 1);
453 let matches = parsed["matches"].as_array().unwrap();
454 assert!(matches[0]["file"].as_str().unwrap().ends_with("clean.txt"));
455 }
456
457 #[test]
458 fn test_grep_files_tool_properties() {
459 let tool = GrepFilesTool;
460 assert_eq!(tool.name(), "grep_files");
461 assert!(tool.is_read_only());
462 assert!(tool.is_sandboxable());
463 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Auto);
464 }
465
466 #[test]
467 fn test_parallel_support_flags() {
468 let tool = GrepFilesTool;
469 assert!(tool.supports_parallel());
470 }
471
472 #[test]
473 fn double_star_exclude_prefix_stops_at_a_path_component() {
474 // Directory excludes still cover the directory and everything under it.
475 assert!(matches_glob("build", "build/**"));
476 assert!(matches_glob("build/out.o", "build/**"));
477 assert!(matches_glob(".git/config", ".git/**"));
478 // A same-prefix sibling file or directory is a different path.
479 assert!(!matches_glob("build.rs", "build/**"));
480 assert!(!matches_glob("build.gradle", "build/**"));
481 assert!(!matches_glob("builders/x.rs", "build/**"));
482 assert!(!matches_glob(".github/workflows/ci.yml", ".git/**"));
483 assert!(!matches_glob(".gitignore", ".git/**"));
484 assert!(!matches_glob("targets/a.rs", "target/**"));
485 }
486
487 #[tokio::test]
488 async fn grep_files_reports_truncation_when_matches_exceed_the_cap() {
489 let tmp = tempdir().expect("tempdir");
490 let ctx = ToolContext::new(tmp.path().to_path_buf());
491 // Three files, two matches each: six matches against a cap of 3.
492 for name in ["a.txt", "b.txt", "c.txt"] {
493 fs::write(tmp.path().join(name), "needle\nneedle\n").expect("write");
494 }
495
496 let capped = GrepFilesTool
497 .execute(json!({"pattern": "needle", "max_results": 3}), &ctx)
498 .await
499 .expect("execute");
500 let capped: Value = serde_json::from_str(&capped.content).unwrap();
501 assert_eq!(capped["matches"].as_array().unwrap().len(), 3);
502 assert_eq!(capped["truncated"], json!(true), "{capped}");
503
504 // Exactly at the cap with nothing more is complete, not truncated.
505 let exact = GrepFilesTool
506 .execute(json!({"pattern": "needle", "max_results": 6}), &ctx)
507 .await
508 .expect("execute");
509 let exact: Value = serde_json::from_str(&exact.content).unwrap();
510 assert_eq!(exact["matches"].as_array().unwrap().len(), 6);
511 assert_eq!(exact["truncated"], json!(false), "{exact}");
512 }
513
514 #[cfg(unix)]
515 #[tokio::test]
516 async fn grep_files_skips_an_unreadable_subdirectory() {
517 use std::os::unix::fs::PermissionsExt;
518
519 let tmp = tempdir().expect("tempdir");
520 let ctx = ToolContext::new(tmp.path().to_path_buf());
521 fs::write(tmp.path().join("found.txt"), "needle\n").expect("write");
522 let locked = tmp.path().join("locked");
523 fs::create_dir(&locked).expect("mkdir");
524 fs::write(locked.join("hidden.txt"), "needle\n").expect("write");
525 fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("chmod");
526 if fs::read_dir(&locked).is_ok() {
527 // Running with privileges that ignore directory modes; nothing to prove.
528 fs::set_permissions(&locked, fs::Permissions::from_mode(0o755)).expect("chmod");
529 return;
530 }
531
532 let result = GrepFilesTool
533 .execute(json!({"pattern": "needle"}), &ctx)
534 .await;
535 fs::set_permissions(&locked, fs::Permissions::from_mode(0o755)).expect("chmod");
536
537 let result = result.expect("an unreadable subdirectory must not fail the search");
538 let parsed: Value = serde_json::from_str(&result.content).unwrap();
539 let matches = parsed["matches"].as_array().unwrap();
540 assert_eq!(matches.len(), 1, "{parsed}");
541 assert!(
542 matches[0]["file"]
543 .as_str()
544 .is_some_and(|file| file.ends_with("found.txt")),
545 "{parsed}"
546 );
547 assert_eq!(parsed["unreadable_paths_skipped"], json!(1), "{parsed}");
548 }
549
550 #[test]
551 fn double_star_without_a_directory_boundary_is_a_string_prefix() {
552 assert!(matches_glob("src/test_foo.rs", "src/test_**"));
553 assert!(matches_glob("src/test_dir/a.rs", "src/test_**"));
554 assert!(!matches_glob("src/other.rs", "src/test_**"));
555 }
556
557 #[tokio::test]
558 async fn grep_files_include_directory_glob_matches_nested_files() {
559 let tmp = tempdir().expect("tempdir");
560 let ctx = ToolContext::new(tmp.path().to_path_buf());
561 fs::create_dir_all(tmp.path().join("src").join("inner")).expect("mkdir");
562 fs::create_dir_all(tmp.path().join("srcs")).expect("mkdir");
563 fs::write(
564 tmp.path().join("src").join("inner").join("a.rs"),
565 "needle\n",
566 )
567 .expect("write");
568 fs::write(tmp.path().join("srcs").join("b.rs"), "needle\n").expect("write");
569
570 let result = GrepFilesTool
571 .execute(json!({"pattern": "needle", "include": ["src/**"]}), &ctx)
572 .await
573 .expect("execute");
574 let parsed: Value = serde_json::from_str(&result.content).unwrap();
575 let files: Vec<&str> = parsed["matches"]
576 .as_array()
577 .unwrap()
578 .iter()
579 .filter_map(|m| m["file"].as_str())
580 .collect();
581 assert_eq!(files.len(), 1, "{parsed}");
582 assert!(
583 files[0].replace('\\', "/").ends_with("src/inner/a.rs"),
584 "{parsed}"
585 );
586 }
587
588 #[tokio::test]
589 async fn grep_files_stops_at_the_cap_without_scanning_further_files() {
590 let tmp = tempdir().expect("tempdir");
591 let ctx = ToolContext::new(tmp.path().to_path_buf());
592 for name in ["a.txt", "b.txt", "c.txt", "d.txt", "e.txt"] {
593 fs::write(tmp.path().join(name), "needle\n").expect("write");
594 }
595
596 let result = GrepFilesTool
597 .execute(json!({"pattern": "needle", "max_results": 2}), &ctx)
598 .await
599 .expect("execute");
600 let parsed: Value = serde_json::from_str(&result.content).unwrap();
601 assert_eq!(parsed["matches"].as_array().unwrap().len(), 2, "{parsed}");
602 // The budget fills exactly at the end of the second file; the walk
603 // must stop there rather than scan on looking for one more match.
604 assert_eq!(parsed["files_searched"], json!(2), "{parsed}");
605 assert_eq!(parsed["truncated"], json!(true), "{parsed}");
606 }
607
608 #[cfg(unix)]
609 #[tokio::test]
610 async fn grep_files_counts_an_unreadable_file() {
611 use std::os::unix::fs::PermissionsExt;
612
613 let tmp = tempdir().expect("tempdir");
614 let ctx = ToolContext::new(tmp.path().to_path_buf());
615 fs::write(tmp.path().join("found.txt"), "needle\n").expect("write");
616 let locked = tmp.path().join("locked.txt");
617 fs::write(&locked, "needle\n").expect("write");
618 fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("chmod");
619 if fs::File::open(&locked).is_ok() {
620 // Running with privileges that ignore file modes; nothing to prove.
621 fs::set_permissions(&locked, fs::Permissions::from_mode(0o644)).expect("chmod");
622 return;
623 }
624
625 let result = GrepFilesTool
626 .execute(json!({"pattern": "needle"}), &ctx)
627 .await;
628 fs::set_permissions(&locked, fs::Permissions::from_mode(0o644)).expect("chmod");
629
630 let parsed: Value = serde_json::from_str(&result.expect("execute").content).unwrap();
631 assert_eq!(parsed["matches"].as_array().unwrap().len(), 1, "{parsed}");
632 assert_eq!(parsed["unreadable_paths_skipped"], json!(1), "{parsed}");
633 }
634
635 #[test]
636 fn pathological_globs_stay_bounded() {
637 let started = std::time::Instant::now();
638
639 let nested = "{{a},c0,c1,c2,c3,c4,c5,c6,c7,c8,c9}".repeat(10);
640 assert!(!matches_glob("file.txt", &nested));
641 assert!(matches_glob("c3c7.txt", "{{a},c3}{{b},c7}.txt"));
642
643 let deep = format!("{}x/b", "d/".repeat(30));
644 let repeated = format!("{}x/b", "**/".repeat(10));
645 assert!(matches_glob(&deep, &repeated));
646 assert!(!matches_glob(&format!("{}x/c", "d/".repeat(30)), &repeated));
647
648 let deep_nesting = format!("{}x{}", "{".repeat(8000), ",y}".repeat(8000));
649 assert!(!matches_glob("x", &deep_nesting));
650
651 assert!(matches_glob("src/a/src", "src/**/**/src"));
652 assert!(!matches_glob("src", "src/**/**/src"));
653 assert!(!matches_glob("src/foo.rs", "src/**/**/src"));
654 assert!(matches_glob("src1/a/b/file.rs", "src*/**/**/file.rs"));
655
656 let many_stars = format!("{}b", "*a".repeat(10));
657 let a40 = "a".repeat(40);
658 assert!(!matches_glob(&format!("{a40}.rs"), &many_stars));
659 assert!(matches_glob(&format!("{a40}b"), &many_stars));
660
661 assert!(
662 started.elapsed() < std::time::Duration::from_secs(2),
663 "took {:?}",
664 started.elapsed()
665 );
666 }
667
668 #[tokio::test]
669 async fn grep_files_defaults_to_zero_context_and_appends_excludes() {
670 let tmp = tempdir().expect("tempdir");
671 let ctx = ToolContext::new(tmp.path().to_path_buf());
672 fs::create_dir_all(tmp.path().join("target").join("debug")).expect("mkdir target");
673 fs::create_dir_all(tmp.path().join("fixtures")).expect("mkdir fixtures");
674 fs::create_dir_all(tmp.path().join("src")).expect("mkdir src");
675 fs::write(
676 tmp.path().join("target").join("debug").join("gen.rs"),
677 "before\nneedle\nafter\n",
678 )
679 .expect("write target");
680 fs::write(
681 tmp.path().join("fixtures").join("skip.rs"),
682 "before\nneedle\nafter\n",
683 )
684 .expect("write fixtures");
685 fs::write(
686 tmp.path().join("src").join("lib.rs"),
687 "before\nneedle\nafter\n",
688 )
689 .expect("write src");
690
691 let appended = GrepFilesTool
692 .execute(
693 json!({"pattern": "needle", "exclude": ["fixtures/**"]}),
694 &ctx,
695 )
696 .await
697 .expect("append excludes");
698 let appended: Value = serde_json::from_str(&appended.content).expect("json");
699 let matches = appended["matches"].as_array().expect("matches");
700 assert_eq!(matches.len(), 1, "{appended}");
701 assert_eq!(
702 matches[0]["file"].as_str().unwrap().replace('\\', "/"),
703 "src/lib.rs"
704 );
705 assert!(matches[0].get("context_before").is_none(), "{appended}");
706 assert!(matches[0].get("context_after").is_none(), "{appended}");
707
708 let replaced = GrepFilesTool
709 .execute(
710 json!({
711 "pattern": "needle",
712 "exclude": ["fixtures/**"],
713 "replace_default_excludes": true
714 }),
715 &ctx,
716 )
717 .await
718 .expect("replace excludes");
719 let replaced: Value = serde_json::from_str(&replaced.content).expect("json");
720 let mut files: Vec<String> = replaced["matches"]
721 .as_array()
722 .expect("matches")
723 .iter()
724 .filter_map(|m| m["file"].as_str().map(|path| path.replace('\\', "/")))
725 .collect();
726 files.sort_unstable();
727 assert_eq!(files, vec!["src/lib.rs", "target/debug/gen.rs"]);
728 }
729
730 #[tokio::test]
731 async fn grep_files_supports_files_only_and_count_modes() {
732 let tmp = tempdir().expect("tempdir");
733 let ctx = ToolContext::new(tmp.path().to_path_buf());
734 fs::write(tmp.path().join("a.rs"), "needle\nneedle\nneedle\n").expect("write a");
735 fs::write(tmp.path().join("b.rs"), "needle\nother\n").expect("write b");
736 fs::write(tmp.path().join("c.rs"), "nothing here\n").expect("write c");
737
738 let files_only = GrepFilesTool
739 .execute(json!({"pattern": "needle", "mode": "files_only"}), &ctx)
740 .await
741 .expect("files_only");
742 let files_only: Value = serde_json::from_str(&files_only.content).expect("json");
743 assert_eq!(files_only["files"], json!(["a.rs", "b.rs"]));
744 assert_eq!(files_only["total_files"], json!(2));
745 assert_eq!(files_only["truncated"], json!(false));
746 assert!(files_only.get("matches").is_none(), "{files_only}");
747
748 let files_only_capped = GrepFilesTool
749 .execute(
750 json!({"pattern": "needle", "mode": "files_only", "max_results": 1}),
751 &ctx,
752 )
753 .await
754 .expect("files_only capped");
755 let files_only_capped: Value = serde_json::from_str(&files_only_capped.content).expect("json");
756 assert_eq!(files_only_capped["files"].as_array().unwrap().len(), 1);
757 assert_eq!(files_only_capped["total_files"], json!(1));
758 assert_eq!(files_only_capped["truncated"], json!(true));
759
760 let count = GrepFilesTool
761 .execute(json!({"pattern": "needle", "mode": "count"}), &ctx)
762 .await
763 .expect("count");
764 let count: Value = serde_json::from_str(&count.content).expect("json");
765 assert_eq!(
766 count["counts"],
767 json!([
768 {"file": "a.rs", "count": 3},
769 {"file": "b.rs", "count": 1}
770 ])
771 );
772 assert_eq!(count["total_matches"], json!(4));
773 assert_eq!(count["total_files"], json!(2));
774 assert_eq!(count["truncated"], json!(false));
775
776 let count_capped = GrepFilesTool
777 .execute(
778 json!({"pattern": "needle", "mode": "count", "max_results": 1}),
779 &ctx,
780 )
781 .await
782 .expect("count capped");
783 let count_capped: Value = serde_json::from_str(&count_capped.content).expect("json");
784 assert_eq!(count_capped["counts"].as_array().unwrap().len(), 1);
785 assert_eq!(count_capped["total_files"], json!(1));
786 assert_eq!(count_capped["truncated"], json!(true));
787
788 let invalid = GrepFilesTool
789 .execute(json!({"pattern": "needle", "mode": "bogus"}), &ctx)
790 .await
791 .expect_err("invalid mode must fail");
792 assert!(invalid.to_string().contains("bogus"), "{invalid}");
793 }
794
795 #[tokio::test]
796 async fn test_grep_files_clips_huge_single_line_matches_around_the_match() {
797 let tmp = tempdir().expect("tempdir");
798 let ctx = ToolContext::new(tmp.path().to_path_buf());
799 let line = format!("{}NEEDLE{}", "é".repeat(60_000), "x".repeat(60_000));
800 fs::write(
801 tmp.path().join("fixture.jsonl"),
802 format!("{}\n{line}\n{}\n", "a".repeat(50_000), "b".repeat(50_000)),
803 )
804 .expect("write");
805
806 let result = GrepFilesTool
807 .execute(json!({"pattern": "NEEDLE", "context_lines": 1}), &ctx)
808 .await
809 .expect("execute");
810
811 assert!(result.success);
812 assert!(result.content.len() < 4_000, "{}", result.content.len());
813 let parsed: Value = serde_json::from_str(&result.content).expect("valid json");
814 let text = parsed.to_string();
815 assert!(text.contains("NEEDLE"), "{text}");
816 assert!(text.contains("bytes]"), "{text}");
817 }
818
819 #[tokio::test]
820 async fn test_grep_blocking_wrapper_cancels_worker_on_timeout() {
821 use std::time::Duration;
822
823 let (finished, worker_finished) = tokio::sync::oneshot::channel();
824 let err = super::run_blocking_grep(Duration::from_millis(1), None, move |cancel_token| {
825 while !cancel_token.is_cancelled() {
826 std::thread::sleep(Duration::from_millis(1));
827 }
828 let _ = finished.send(cancel_token.is_cancelled());
829 Err(super::grep_cancelled())
830 })
831 .await
832 .expect_err("slow grep_files worker should time out");
833
834 assert!(
835 matches!(err, crate::tools::spec::ToolError::Timeout { seconds: 1 }),
836 "unexpected error: {err:?}"
837 );
838 assert!(
839 tokio::time::timeout(Duration::from_secs(1), worker_finished)
840 .await
841 .expect("timed-out worker must stop")
842 .expect("worker completion"),
843 "timeout must cancel the worker without a parent cancellation token"
844 );
845
846 // Timeout with a parent token must cancel only the worker child token.
847 let parent = CancellationToken::new();
848 let (finished2, worker_finished2) = tokio::sync::oneshot::channel();
849 let err2 = super::run_blocking_grep(
850 Duration::from_millis(1),
851 Some(parent.clone()),
852 move |cancel_token| {
853 while !cancel_token.is_cancelled() {
854 std::thread::sleep(Duration::from_millis(1));
855 }
856 let _ = finished2.send(cancel_token.is_cancelled());
857 Err(super::grep_cancelled())
858 },
859 )
860 .await
861 .expect_err("slow grep_files worker with parent token should time out");
862
863 assert!(
864 matches!(err2, crate::tools::spec::ToolError::Timeout { seconds: 1 }),
865 "unexpected error: {err2:?}"
866 );
867 assert!(
868 tokio::time::timeout(Duration::from_secs(1), worker_finished2)
869 .await
870 .expect("timed-out worker must stop")
871 .expect("worker completion"),
872 );
873 assert!(
874 !parent.is_cancelled(),
875 "timeout must not cancel the caller's parent token"
876 );
877 }
878
879 #[tokio::test]
880 async fn test_grep_files_clamps_oversized_max_results() {
881 let tmp = tempdir().expect("tempdir");
882 let ctx = ToolContext::new(tmp.path().to_path_buf());
883 let content = "needle\n".repeat(super::MAX_RESULTS_LIMIT + 50);
884 fs::write(tmp.path().join("many.txt"), content).expect("write");
885
886 let result = GrepFilesTool
887 .execute(json!({"pattern": "needle", "max_results": 1_000_000}), &ctx)
888 .await
889 .expect("execute");
890 assert!(result.success);
891 let parsed: Value = serde_json::from_str(&result.content).expect("valid json");
892 assert_eq!(
893 parsed["matches"].as_array().expect("matches").len(),
894 super::MAX_RESULTS_LIMIT
895 );
896 assert_eq!(parsed["total_matches"], json!(super::MAX_RESULTS_LIMIT));
897 assert_eq!(parsed["truncated"], json!(true));
898 }
899
900 #[allow(clippy::await_holding_lock)]
901 #[tokio::test]
902 async fn grep_files_skips_codewhale_credential_files_and_refuses_hardlink_and_swapped_symlink() {
903 let _env_lock = crate::test_support::lock_test_env();
904 let parent = tempdir().expect("parent");
905 let workspace = parent.path().join("ws");
906 let outside = parent.path().join("outside");
907 fs::create_dir_all(&workspace).expect("mkdir ws");
908 fs::create_dir_all(&outside).expect("mkdir outside");
909 let ws_canon = workspace.canonicalize().expect("canon ws");
910 let cw_home = ws_canon.join("cw-home");
911 fs::create_dir_all(cw_home.join("secrets")).expect("mkdir cw-home");
912 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
913 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
914 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
915
916 fs::write(ws_canon.join("visible.txt"), "NEEDLE_VISIBLE\n").expect("write visible");
917 fs::write(cw_home.join("config.toml"), "api_key = \"NEEDLE_CONFIG\"\n").expect("write config");
918 fs::write(cw_home.join("secrets").join("tok.txt"), "NEEDLE_SECRET\n").expect("write secret");
919 let outside_secret = outside.join("secret.txt");
920 fs::write(&outside_secret, "NEEDLE_HARDLINK\n").expect("write outside");
921 fs::hard_link(&outside_secret, ws_canon.join("linked.txt")).expect("hardlink");
922
923 let ctx = ToolContext::new(&ws_canon);
924 let result = GrepFilesTool
925 .execute(json!({"pattern": "NEEDLE_"}), &ctx)
926 .await
927 .expect("grep workspace");
928 let parsed: Value = serde_json::from_str(&result.content).expect("valid json");
929 let matches = parsed["matches"].as_array().expect("matches");
930 assert_eq!(matches.len(), 1, "{parsed}");
931 assert_eq!(matches[0]["file"], json!("visible.txt"), "{parsed}");
932 assert_eq!(parsed["files_searched"], json!(1), "{parsed}");
933 assert_eq!(parsed["unreadable_paths_skipped"], json!(1), "{parsed}");
934
935 let trusted_ctx = ToolContext::new(&ws_canon).with_trust_mode(true);
936 let cred_err = GrepFilesTool
937 .execute(
938 json!({
939 "pattern": "NEEDLE_",
940 "path": cw_home.join("config.toml").to_string_lossy()
941 }),
942 &trusted_ctx,
943 )
944 .await
945 .expect_err("direct grep on CODEWHALE_HOME/config.toml must fail");
946 assert!(
947 matches!(
948 cred_err,
949 crate::tools::spec::ToolError::PermissionDenied { .. }
950 ),
951 "{cred_err:?}"
952 );
953
954 let mut strict_trusted_ctx = ToolContext::new(&ws_canon).with_trust_mode(true);
955 strict_trusted_ctx.strict_workspace_confinement = true;
956 let escape_err = GrepFilesTool
957 .execute(
958 json!({
959 "pattern": "NEEDLE_",
960 "path": outside.to_string_lossy()
961 }),
962 &strict_trusted_ctx,
963 )
964 .await
965 .expect_err("strict confinement must refuse outside search root even in trust mode");
966 assert!(
967 matches!(
968 escape_err,
969 crate::tools::spec::ToolError::PathEscape { .. }
970 | crate::tools::spec::ToolError::PermissionDenied { .. }
971 ),
972 "{escape_err:?}"
973 );
974
975 #[cfg(unix)]
976 {
977 let swap_path = ws_canon.join("swap.txt");
978 fs::write(&swap_path, "benign\n").expect("write swap");
979 let boundary = crate::tools::file::OpenedReadBoundary::from_context(
980 &ctx,
981 "grep_files",
982 ".",
983 ws_canon.clone(),
984 None,
985 true,
986 )
987 .await;
988 fs::remove_file(&swap_path).expect("remove swap");
989 std::os::unix::fs::symlink(&outside_secret, &swap_path).expect("symlink swap");
990 let swap_err = crate::tools::file::open_verified_search_file(&swap_path, &boundary, false)
991 .expect_err("swapped symlink must be refused by open_verified_search_file");
992 assert!(
993 matches!(
994 swap_err,
995 crate::tools::spec::ToolError::PermissionDenied { .. }
996 ),
997 "{swap_err:?}"
998 );
999
1000 let swapped_parent = ws_canon.join("swapped_parent");
1001 std::os::unix::fs::symlink(&outside, &swapped_parent).expect("symlink parent");
1002 let parent_swap_err = crate::tools::file::open_verified_search_file(
1003 &swapped_parent.join("secret.txt"),
1004 &boundary,
1005 false,
1006 )
1007 .expect_err("non-strict anchored search open must refuse swapped parent symlink");
1008 assert!(
1009 matches!(
1010 parent_swap_err,
1011 crate::tools::spec::ToolError::PermissionDenied { .. }
1012 ),
1013 "{parent_swap_err:?}"
1014 );
1015
1016 fs::write(ws_canon.join(".env"), "SECRET=1\n").expect("write .env");
1017 let follow_env_link = ws_canon.join("link_env.txt");
1018 std::os::unix::fs::symlink(ws_canon.join(".env"), &follow_env_link).expect("symlink .env");
1019 let follow_cred_link = ws_canon.join("link_cred.txt");
1020 std::os::unix::fs::symlink(cw_home.join("config.toml"), &follow_cred_link)
1021 .expect("symlink config.toml");
1022 for link in [&follow_env_link, &follow_cred_link] {
1023 let follow_err = crate::tools::file::open_verified_search_file(link, &boundary, true)
1024 .expect_err("follow_symlinks search open must refuse denied/credential target");
1025 assert!(
1026 matches!(
1027 follow_err,
1028 crate::tools::spec::ToolError::PermissionDenied { .. }
1029 ),
1030 "{}: {follow_err:?}",
1031 link.display()
1032 );
1033 }
1034 }
1035 }
1036
1036 lines RUST