返回 CodeWhale
tools.rs
根目录 / crates / engine / src / tools / file / tests / tools.rs
1 use super::*;
2 use tempfile::tempdir;
3
4 async fn read_before_edit(ctx: &ToolContext, path: &str) {
5 ReadFileTool
6 .execute(json!({"path": path}), ctx)
7 .await
8 .expect("read before edit");
9 }
10
11 #[tokio::test]
12 async fn test_read_file_tool() {
13 let tmp = tempdir().expect("tempdir");
14 let ctx = ToolContext::new(tmp.path().to_path_buf());
15
16 // Create a test file
17 let test_file = tmp.path().join("test.txt");
18 fs::write(&test_file, "hello world").expect("write");
19
20 let tool = ReadFileTool;
21 let result = tool
22 .execute(json!({"path": "test.txt"}), &ctx)
23 .await
24 .expect("execute");
25
26 assert!(result.success);
27 // #3979: a small-file read now leads with the snapshot hash the edit
28 // guard verifies against, then the contents verbatim.
29 assert_eq!(
30 result.content,
31 format!(
32 "content_hash=\"{}\"\nhello world",
33 super::content_hash(b"hello world")
34 )
35 );
36 }
37
38 // This test deliberately serializes process-global environment changes
39 // while awaiting the tool path.
40 #[allow(clippy::await_holding_lock)]
41 #[tokio::test]
42 async fn read_file_denies_codewhale_config_backups_and_secret_store() {
43 let _env_lock = crate::test_support::lock_test_env();
44 let tmp = tempdir().expect("tempdir");
45 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path());
46 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
47 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
48
49 fs::write(tmp.path().join("config.toml"), "api_key = \"secret\"\n").expect("write config");
50 fs::write(
51 tmp.path().join("config.toml.bak"),
52 "api_key = \"old-secret\"\n",
53 )
54 .expect("write config backup");
55 fs::create_dir_all(tmp.path().join("secrets")).expect("create secrets dir");
56 fs::write(
57 tmp.path().join("secrets").join("secrets.json"),
58 r#"{"provider":"secret"}"#,
59 )
60 .expect("write file keyring");
61 fs::write(tmp.path().join("notes.txt"), "ordinary workspace data")
62 .expect("write ordinary file");
63
64 let ctx = ToolContext::new(tmp.path().to_path_buf());
65 for path in ["config.toml", "config.toml.bak", "secrets/secrets.json"] {
66 let err = ReadFileTool
67 .execute(json!({"path": path}), &ctx)
68 .await
69 .expect_err("credential-bearing CodeWhale file must be denied");
70 let message = err.to_string();
71 assert!(message.contains("cannot expose Codewhale"), "{message}");
72 assert!(message.contains("codewhale config list"), "{message}");
73 }
74
75 let ordinary = ReadFileTool
76 .execute(json!({"path": "notes.txt"}), &ctx)
77 .await
78 .expect("ordinary workspace file should remain readable");
79 assert!(
80 ordinary.content.ends_with("ordinary workspace data"),
81 "{}",
82 ordinary.content
83 );
84 }
85
86 #[tokio::test]
87 async fn read_file_ocr_extracts_text_from_image_when_backend_exists() {
88 if !crate::tools::image_ocr::ocr_available() {
89 return;
90 }
91 let fixture =
92 std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/ocr_hello.png");
93 if !fixture.exists() {
94 return;
95 }
96 let tmp = tempdir().expect("tempdir");
97 fs::copy(&fixture, tmp.path().join("ocr_hello.png")).expect("copy fixture");
98 let ctx = ToolContext::new(tmp.path().to_path_buf());
99
100 let result = match ReadFileTool
101 .execute(json!({"path": "ocr_hello.png"}), &ctx)
102 .await
103 {
104 Ok(result) => result,
105 Err(err) => {
106 // Name is when_backend_exists — skip if live OCR fails after
107 // the availability probe (restricted Vision, etc.).
108 let msg = err.to_string();
109 let _skip_reason = format!("OCR backend probe passed but read_file OCR failed: {msg}");
110 let _ = &_skip_reason;
111 return;
112 }
113 };
114
115 assert!(result.success);
116 assert!(result.content.contains("<image_ocr"));
117 let normalized = result.content.to_uppercase();
118 assert!(
119 normalized.contains("HELLO") && normalized.contains("OCR"),
120 "expected OCR text in read_file result, got {:?}",
121 result.content
122 );
123 }
124
125 #[test]
126 fn parse_pages_arg_accepts_single_page() {
127 assert_eq!(parse_pages_arg("3"), Some((3, 3)));
128 assert_eq!(parse_pages_arg(" 7 "), Some((7, 7)));
129 }
130
131 #[test]
132 fn parse_pages_arg_accepts_range() {
133 assert_eq!(parse_pages_arg("1-5"), Some((1, 5)));
134 assert_eq!(parse_pages_arg("10-20"), Some((10, 20)));
135 // Whitespace around either side of the dash is tolerated so
136 // hand-typed `pages: "1 - 5"` still works.
137 assert_eq!(parse_pages_arg(" 1 - 5 "), Some((1, 5)));
138 }
139
140 #[test]
141 fn parse_pages_arg_rejects_invalid_ranges() {
142 // Caller would otherwise feed `pdftotext -f 5 -l 1`, which
143 // prints nothing — fail loudly so the model can re-issue.
144 assert!(parse_pages_arg("5-1").is_none(), "end < start must reject");
145 // 0-indexed pages aren't a thing in pdftotext; reject so the
146 // caller doesn't get a confusing "no output" silent fail.
147 assert!(
148 parse_pages_arg("0").is_none(),
149 "zero single-page must reject"
150 );
151 assert!(parse_pages_arg("0-3").is_none(), "zero start must reject");
152 // Empty / whitespace-only / non-numeric inputs must reject.
153 assert!(parse_pages_arg("").is_none());
154 assert!(parse_pages_arg(" ").is_none());
155 assert!(parse_pages_arg("abc").is_none());
156 assert!(parse_pages_arg("3.5").is_none(), "floats must reject");
157 }
158
159 #[test]
160 fn parse_pages_arg_rejects_half_open_ranges() {
161 // Half-open ranges like `1-` or `-5` are almost certainly a
162 // typo for `1-N`/`N` rather than intentional input. Reject
163 // them rather than silently extending to u32::MAX or 0.
164 assert!(parse_pages_arg("1-").is_none());
165 assert!(parse_pages_arg("-5").is_none());
166 assert!(parse_pages_arg("-").is_none());
167 }
168
169 #[test]
170 fn parse_pages_arg_rejects_negative_numbers() {
171 // u32::parse on a negative literal returns Err, so the
172 // function reports `None` rather than wrapping into a giant
173 // positive number — defensive but worth pinning.
174 assert!(parse_pages_arg("-3-5").is_none());
175 }
176
177 #[tokio::test]
178 async fn test_read_file_not_found() {
179 let tmp = tempdir().expect("tempdir");
180 let ctx = ToolContext::new(tmp.path().to_path_buf());
181
182 let tool = ReadFileTool;
183 let result = tool.execute(json!({"path": "nonexistent.txt"}), &ctx).await;
184
185 assert!(result.is_err());
186 }
187
188 #[tokio::test]
189 async fn read_file_small_file_returns_unwrapped_contents() {
190 // Small files (≤ 200 lines AND ≤ 16KB, no explicit range) keep
191 // the historical "return contents unchanged" behavior so
192 // existing prompts don't suddenly see <file> tags appear.
193 // Harvested from #1451 — pin the fast-path contract.
194 //
195 // #3979 added one `content_hash="…"` header line ahead of the contents:
196 // the guard is useless if the common read path cannot report a hash, and
197 // this branch has no `<file>` envelope to carry it as an attribute. The
198 // contents themselves are still verbatim and still unwrapped.
199 let tmp = tempdir().expect("tempdir");
200 let ctx = ToolContext::new(tmp.path().to_path_buf());
201 let file = tmp.path().join("small.txt");
202 fs::write(&file, "line 1\nline 2\nline 3\n").expect("write");
203 let tool = ReadFileTool;
204 let result = tool
205 .execute(json!({ "path": "small.txt" }), &ctx)
206 .await
207 .expect("execute");
208 assert!(result.success);
209 assert_eq!(
210 result.content,
211 format!(
212 "content_hash=\"{}\"\nline 1\nline 2\nline 3\n",
213 super::content_hash(b"line 1\nline 2\nline 3\n")
214 )
215 );
216 assert!(
217 !result.content.contains("<file"),
218 "small-file fast path must not wrap output"
219 );
220 }
221
222 #[tokio::test]
223 async fn read_file_explicit_range_wraps_in_file_tag_with_one_based_lines() {
224 let tmp = tempdir().expect("tempdir");
225 let ctx = ToolContext::new(tmp.path().to_path_buf());
226 let file = tmp.path().join("ranged.txt");
227 let body: String = (1..=10).map(|n| format!("line {n}\n")).collect();
228 fs::write(&file, &body).expect("write");
229 let tool = ReadFileTool;
230 let result = tool
231 .execute(
232 json!({ "path": "ranged.txt", "start_line": 3, "max_lines": 4 }),
233 &ctx,
234 )
235 .await
236 .expect("execute");
237 assert!(result.success);
238 assert!(
239 result.content.contains("shown_lines=\"3-6\""),
240 "1-based inclusive range must be reflected in shown_lines: {}",
241 result.content
242 );
243 assert!(
244 result.content.contains("next_start_line=\"7\""),
245 "next_start_line must point one past the last shown line: {}",
246 result.content
247 );
248 assert!(
249 result.content.contains(" 3│ line 3"),
250 "rendered lines must start at the requested line number"
251 );
252 assert!(
253 result.content.contains(" 6│ line 6"),
254 "rendered lines must end at the last in-range line"
255 );
256 assert!(
257 !result.content.contains(" 7│ line 7"),
258 "lines past max_lines must be excluded"
259 );
260 assert!(result.content.contains("truncated=\"true\""));
261 }
262
263 #[tokio::test]
264 async fn read_file_range_beyond_total_returns_no_content_sentinel() {
265 let tmp = tempdir().expect("tempdir");
266 let ctx = ToolContext::new(tmp.path().to_path_buf());
267 let file = tmp.path().join("short.txt");
268 fs::write(&file, "only\nthree\nlines\n").expect("write");
269 let tool = ReadFileTool;
270 let result = tool
271 .execute(json!({ "path": "short.txt", "start_line": 99 }), &ctx)
272 .await
273 .expect("execute");
274 assert!(
275 result.success,
276 "out-of-range must not raise — it's a sentinel"
277 );
278 assert!(result.content.contains("[NO CONTENT]"));
279 assert!(result.content.contains("shown_lines=\"none\""));
280 assert!(result.content.contains("truncated=\"false\""));
281 }
282
283 /// 2026-08-04 review: a `start_line:"1200"` string (or any wrong type) used
284 /// to fall back SILENTLY to the defaults, returning lines 1-500 — the head
285 /// of the file dressed up as the window the model asked for. Wrong types
286 /// are errors, matching the shared `optional_u64` contract.
287 #[tokio::test]
288 async fn read_file_refuses_wrongly_typed_range_params_instead_of_defaulting() {
289 let tmp = tempdir().expect("tempdir");
290 let ctx = ToolContext::new(tmp.path().to_path_buf());
291 fs::write(tmp.path().join("any.txt"), "x\ny\nz\n").expect("write");
292 let tool = ReadFileTool;
293 for bad in [json!("1200"), json!(-5), json!(2.5), json!([1200])] {
294 let err = tool
295 .execute(json!({ "path": "any.txt", "start_line": bad }), &ctx)
296 .await
297 .expect_err("wrongly typed start_line must error, never default");
298 assert!(
299 err.to_string().contains("start_line"),
300 "error names the field: {err}"
301 );
302 let err = tool
303 .execute(json!({ "path": "any.txt", "max_lines": bad }), &ctx)
304 .await
305 .expect_err("wrongly typed max_lines must error, never default");
306 assert!(
307 err.to_string().contains("max_lines"),
308 "error names the field: {err}"
309 );
310 }
311 // Null still reads as absent, consistent with the strictness lane.
312 let ok = tool
313 .execute(json!({ "path": "any.txt", "start_line": null }), &ctx)
314 .await
315 .expect("null is absence, not a type error");
316 assert!(ok.success);
317 }
318
319 #[tokio::test]
320 async fn read_file_rejects_zero_start_line_and_zero_max_lines() {
321 let tmp = tempdir().expect("tempdir");
322 let ctx = ToolContext::new(tmp.path().to_path_buf());
323 fs::write(tmp.path().join("any.txt"), "x\n").expect("write");
324 let tool = ReadFileTool;
325 let zero_start = tool
326 .execute(json!({ "path": "any.txt", "start_line": 0 }), &ctx)
327 .await;
328 assert!(zero_start.is_err(), "start_line=0 must error (1-based)");
329 let zero_max = tool
330 .execute(json!({ "path": "any.txt", "max_lines": 0 }), &ctx)
331 .await;
332 assert!(zero_max.is_err(), "max_lines=0 must error");
333 }
334
335 #[tokio::test]
336 async fn read_file_byte_truncation_keeps_head_and_tail() {
337 // Long lines force the 16 KiB bound before the line cap. The model must
338 // see both ends of the window (qwen-style head = budget/5 + tail) and the
339 // recovery note must name the original path for a re-read.
340 let tmp = tempdir().expect("tempdir");
341 let ctx = ToolContext::new(tmp.path().to_path_buf());
342 let file = tmp.path().join("wide.txt");
343 let body: String = (1..=40)
344 .map(|n| format!("LINE{n}_START {} LINE{n}_END\n", "x".repeat(600)))
345 .collect();
346 assert!(body.len() > 16 * 1024, "fixture must exceed 16KB");
347 fs::write(&file, &body).expect("write");
348
349 let tool = ReadFileTool;
350 let result = tool
351 .execute(
352 json!({ "path": "wide.txt", "start_line": 1, "max_lines": 40 }),
353 &ctx,
354 )
355 .await
356 .expect("execute");
357
358 assert!(result.success);
359 assert!(result.content.contains("truncated=\"true\""));
360 assert!(
361 result.content.contains("LINE1_START"),
362 "head of the window must survive: {}",
363 &result.content[..result.content.len().min(400)]
364 );
365 assert!(
366 result.content.contains("LINE40_END") || result.content.contains("LINE40_START"),
367 "tail of the window must survive: {}",
368 &result.content[result.content.len().saturating_sub(400)..]
369 );
370 assert!(
371 result.content.contains("[CONTENT TRUNCATED]"),
372 "head/tail separator missing: {}",
373 result.content
374 );
375 assert!(
376 result.content.contains("path=\"wide.txt\""),
377 "recovery path must name the file: {}",
378 result.content
379 );
380 assert!(
381 result
382 .content
383 .contains("Re-read narrower windows to see the middle"),
384 "byte-truncation recovery note must give actionable advice: {}",
385 result.content
386 );
387 assert!(
388 result.content.contains("offset=1 limit=20"),
389 "the note names a concrete narrower window: {}",
390 result.content
391 );
392 // Middle of the window should be the part omitted under a head+tail budget.
393 assert!(
394 !result.content.contains("LINE20_START") || result.content.contains("[CONTENT TRUNCATED]"),
395 "expected truncation of the middle: {}",
396 result.content
397 );
398 }
399
400 #[tokio::test]
401 async fn read_file_clamps_max_lines_to_hard_cap() {
402 let tmp = tempdir().expect("tempdir");
403 let ctx = ToolContext::new(tmp.path().to_path_buf());
404 let file = tmp.path().join("bigish.txt");
405 let body: String = (1..=600).map(|n| format!("L{n}\n")).collect();
406 fs::write(&file, &body).expect("write");
407 let tool = ReadFileTool;
408 let result = tool
409 .execute(json!({ "path": "bigish.txt", "max_lines": 5000 }), &ctx)
410 .await
411 .expect("execute");
412 // Hard cap is 500 lines; line 500 must appear, line 501 must not.
413 assert!(
414 result.content.contains(" 500│ L500"),
415 "line 500 should be in the window (max_lines clamped to 500)"
416 );
417 assert!(
418 !result.content.contains(" 501│ L501"),
419 "line 501 must be outside the clamped window"
420 );
421 assert!(result.content.contains("next_start_line=\"501\""));
422 assert!(result.content.contains("truncated=\"true\""));
423 }
424
425 #[tokio::test]
426 async fn read_file_large_file_without_range_uses_default_window() {
427 // A file over 200 lines / 16KB with no explicit range still
428 // gets the default window, not the unbounded raw content —
429 // this is the entire point of the patch (token-budget control).
430 let tmp = tempdir().expect("tempdir");
431 let ctx = ToolContext::new(tmp.path().to_path_buf());
432 let file = tmp.path().join("big.txt");
433 let body: String = (1..=250).map(|n| format!("row {n}\n")).collect();
434 fs::write(&file, &body).expect("write");
435 let tool = ReadFileTool;
436 let result = tool
437 .execute(json!({ "path": "big.txt" }), &ctx)
438 .await
439 .expect("execute");
440 // 250 rows is ~1.7 KB — far inside the 16 KB byte budget — so it reads in
441 // ONE call. The old 200-line default truncated here and charged a second
442 // round trip to fetch 50 lines, which is what this change removes.
443 // No `<file …>` envelope: at 250 lines / ~1.7 KB it now takes the
444 // whole-file path and comes back as plain text, which is the point.
445 assert!(result.content.contains("row 1"));
446 assert!(result.content.contains("row 250"));
447 assert!(
448 !result.content.contains("next_start_line"),
449 "a 250-line, ~1.7 KB file must not window: {}",
450 result.content
451 );
452
453 // Past the line cap it still windows, because the cap is a real guard for
454 // pathologically short lines.
455 let many = tmp.path().join("many.txt");
456 let body: String = (1..=600).map(|n| format!("row {n}\n")).collect();
457 fs::write(&many, &body).expect("write");
458 let windowed = tool
459 .execute(json!({ "path": "many.txt" }), &ctx)
460 .await
461 .expect("execute");
462 assert!(windowed.content.contains("shown_lines=\"1-500\""));
463 assert!(windowed.content.contains("next_start_line=\"501\""));
464 }
465
466 #[tokio::test]
467 async fn read_file_streamed_range_on_large_file_matches_windowed_contract() {
468 // Over 16KB forces the streamed BufRead path even without an
469 // explicit range; assert the ranged output stays byte-compatible
470 // with the historical full-read implementation.
471 let tmp = tempdir().expect("tempdir");
472 let ctx = ToolContext::new(tmp.path().to_path_buf());
473 let file = tmp.path().join("large.txt");
474 let body: String = (1..=2000)
475 .map(|n| format!("line {n} {}\n", "x".repeat(20)))
476 .collect();
477 assert!(body.len() > 16 * 1024, "fixture must exceed 16KB");
478 fs::write(&file, &body).expect("write");
479
480 let tool = ReadFileTool;
481 let result = tool
482 .execute(
483 json!({ "path": "large.txt", "start_line": 1500, "max_lines": 10 }),
484 &ctx,
485 )
486 .await
487 .expect("execute");
488
489 assert!(result.success);
490 assert!(result.content.contains("total_lines=\"2000\""));
491 assert!(result.content.contains("shown_lines=\"1500-1509\""));
492 assert!(result.content.contains("next_start_line=\"1510\""));
493 assert!(result.content.contains(" 1500│ line 1500"));
494 assert!(result.content.contains(" 1509│ line 1509"));
495 assert!(!result.content.contains(" 1510│"));
496 assert!(result.content.contains(
497 "[TRUNCATED] Showing lines 1500-1509 of 2000. To continue, call read with path=\"large.txt\" offset=1510 limit=10"
498 ));
499 assert!(!result.content.contains("read_file"), "{}", result.content);
500
501 // Default window (no range) on the same large file starts at line 1.
502 let default_window = tool
503 .execute(json!({ "path": "large.txt" }), &ctx)
504 .await
505 .expect("execute");
506 assert!(default_window.content.contains("shown_lines=\"1-500\""));
507 assert!(default_window.content.contains("next_start_line=\"501\""));
508 assert!(default_window.content.contains(" 1│ line 1"));
509
510 // Paging past EOF returns the no-content sentinel, not an error.
511 let past_end = tool
512 .execute(json!({ "path": "large.txt", "start_line": 5000 }), &ctx)
513 .await
514 .expect("execute");
515 assert!(past_end.content.contains("[NO CONTENT]"));
516 assert!(past_end.content.contains("shown_lines=\"none\""));
517 }
518
519 #[tokio::test]
520 async fn read_file_streamed_range_rejects_invalid_utf8_like_full_read() {
521 let tmp = tempdir().expect("tempdir");
522 let ctx = ToolContext::new(tmp.path().to_path_buf());
523 let file = tmp.path().join("mixed.bin");
524 // Valid first lines, invalid bytes later: the streamed path must
525 // still fail the whole read like read_to_string did.
526 let mut bytes = b"good line\n".repeat(5);
527 bytes.extend_from_slice(&[0xFF, 0xFE, b'\n']);
528 fs::write(&file, &bytes).expect("write");
529
530 let err = ReadFileTool
531 .execute(
532 json!({ "path": "mixed.bin", "start_line": 1, "max_lines": 2 }),
533 &ctx,
534 )
535 .await
536 .expect_err("invalid UTF-8 must error");
537 let message = err.to_string();
538 assert!(message.contains("Failed to read"), "{message}");
539 assert!(message.contains("valid UTF-8"), "{message}");
540 }
541
542 #[tokio::test]
543 async fn test_read_file_missing_path() {
544 let tmp = tempdir().expect("tempdir");
545 let ctx = ToolContext::new(tmp.path().to_path_buf());
546
547 let tool = ReadFileTool;
548 let result = tool.execute(json!({}), &ctx).await;
549
550 assert!(result.is_err());
551 let err = result.unwrap_err();
552 assert!(
553 err.to_string()
554 .contains("Failed to validate input: missing required field 'path'")
555 );
556 }
557
558 #[tokio::test]
559 async fn pdf_detected_by_extension() {
560 let tmp = tempdir().expect("tempdir");
561 let path = tmp.path().join("paper.PDF");
562 fs::write(&path, b"not really a pdf, but extension says yes").unwrap();
563 let mut file = fs::File::open(&path).unwrap();
564 assert!(is_pdf_handle(&mut file, &path).unwrap());
565 }
566
567 #[tokio::test]
568 async fn pdf_detected_by_magic_bytes_without_extension() {
569 let tmp = tempdir().expect("tempdir");
570 let path = tmp.path().join("blob");
571 fs::write(&path, b"%PDF-1.7\nrest of bytes").unwrap();
572 let mut file = fs::File::open(&path).unwrap();
573 assert!(is_pdf_handle(&mut file, &path).unwrap());
574 }
575
576 #[tokio::test]
577 async fn non_pdf_not_detected() {
578 let tmp = tempdir().expect("tempdir");
579 let path = tmp.path().join("notes.txt");
580 fs::write(&path, "hello").unwrap();
581 let mut file = fs::File::open(&path).unwrap();
582 assert!(!is_pdf_handle(&mut file, &path).unwrap());
583 }
584
585 #[test]
586 fn pages_arg_parses_single_and_range() {
587 assert_eq!(parse_pages_arg("5"), Some((5, 5)));
588 assert_eq!(parse_pages_arg("1-10"), Some((1, 10)));
589 assert_eq!(parse_pages_arg(" 3 - 7 "), Some((3, 7)));
590 assert_eq!(parse_pages_arg("0"), None);
591 assert_eq!(parse_pages_arg("10-3"), None);
592 assert_eq!(parse_pages_arg(""), None);
593 assert_eq!(parse_pages_arg("abc"), None);
594 }
595
596 /// Sample PDF shipped with the repo for parity tests against the
597 /// pure-Rust extractor. 38 pages, born-digital LaTeX (arXiv 2512.24601).
598 /// Path is workspace-root-relative because the fixture lives outside
599 /// the tui crate.
600 const SAMPLE_PDF_PATH: &str = "../../docs/2512.24601v2.pdf";
601
602 fn sample_pdf_present() -> bool {
603 std::path::Path::new(SAMPLE_PDF_PATH).exists()
604 }
605
606 #[test]
607 fn clean_pdf_text_collapses_consecutive_blank_lines() {
608 let raw = "line1\n\n\n\n\nline2\n\n\nline3";
609 let cleaned = super::clean_pdf_text(raw);
610 assert_eq!(cleaned, "line1\n\nline2\n\nline3");
611 }
612
613 #[test]
614 fn clean_pdf_text_replaces_nul_bytes_with_replacement_char() {
615 let raw = "hello\0world";
616 let cleaned = super::clean_pdf_text(raw);
617 assert!(!cleaned.contains('\0'));
618 assert!(cleaned.contains('\u{FFFD}'));
619 }
620
621 #[test]
622 fn clean_pdf_text_replaces_non_breaking_spaces() {
623 let raw = "hello\u{A0}world";
624 let cleaned = super::clean_pdf_text(raw);
625 assert!(!cleaned.contains('\u{A0}'));
626 assert_eq!(cleaned, "hello world");
627 }
628
629 #[test]
630 fn clean_pdf_text_trims_trailing_whitespace() {
631 let raw = "hello ";
632 let cleaned = super::clean_pdf_text(raw);
633 assert_eq!(cleaned, "hello");
634 }
635
636 #[test]
637 fn clean_pdf_text_preserves_leading_indentation() {
638 let raw = " indented line\nregular line";
639 let cleaned = super::clean_pdf_text(raw);
640 assert_eq!(cleaned, " indented line\nregular line");
641 }
642
643 #[tokio::test]
644 async fn read_file_pdf_path_uses_optional_pdftotext_adapter() {
645 if !sample_pdf_present() || codewhale_dependencies::resolve_pdftotext().is_none() {
646 return;
647 }
648 let workspace = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../");
649 let ctx = ToolContext::new(workspace);
650 let result = ReadFileTool
651 .execute(json!({"path": "docs/2512.24601v2.pdf", "pages": "1"}), &ctx)
652 .await
653 .expect("execute");
654 assert!(result.success);
655 assert!(
656 result.content.contains("Recursive Language Models"),
657 "page-1 extraction must surface the title"
658 );
659 }
660
661 #[tokio::test]
662 async fn test_write_file_tool() {
663 let tmp = tempdir().expect("tempdir");
664 let ctx = ToolContext::new(tmp.path().to_path_buf());
665
666 let tool = WriteFileTool;
667 let result = tool
668 .execute(
669 json!({"path": "output.txt", "content": "test content"}),
670 &ctx,
671 )
672 .await
673 .expect("execute");
674
675 assert!(result.success);
676 // New file → "Created …" summary; the unified diff above the summary
677 // primes the TUI's diff-aware renderer (#505).
678 assert!(result.content.contains("Created"), "{}", result.content);
679 assert!(result.content.contains("--- a/"), "{}", result.content);
680 assert!(
681 result.content.contains("+test content"),
682 "{}",
683 result.content
684 );
685 let mutation = &result.metadata.as_ref().expect("metadata")["mutation"];
686 assert_eq!(
687 mutation["files"],
688 json!([{
689 "path": "output.txt",
690 "outcome": "created",
691 "size": "test content".len(),
692 "sha256": codewhale_runtime::hashing::sha256_hex(b"test content"),
693 }])
694 );
695 assert!(
696 mutation["diff"]
697 .as_str()
698 .is_some_and(|diff| diff.contains("--- a/output.txt")),
699 "{mutation}"
700 );
701 assert!(
702 !mutation["diff"]
703 .as_str()
704 .unwrap_or_default()
705 .contains(&tmp.path().display().to_string()),
706 "receipt headers must not expose the resolved host path: {mutation}"
707 );
708
709 // Verify file was written
710 let written = fs::read_to_string(tmp.path().join("output.txt")).expect("read");
711 assert_eq!(written, "test content");
712 }
713
714 #[tokio::test]
715 async fn test_write_file_creates_dirs() {
716 let tmp = tempdir().expect("tempdir");
717 let ctx = ToolContext::new(tmp.path().to_path_buf());
718
719 let tool = WriteFileTool;
720 let result = tool
721 .execute(
722 json!({"path": "subdir/nested/file.txt", "content": "nested content"}),
723 &ctx,
724 )
725 .await
726 .expect("execute");
727
728 assert!(result.success);
729
730 // Verify nested file was created
731 let written = fs::read_to_string(tmp.path().join("subdir/nested/file.txt")).expect("read");
732 assert_eq!(written, "nested content");
733 }
734
735 #[cfg(unix)]
736 #[tokio::test]
737 async fn write_file_tool_new_file_matches_standard_creation_mode() {
738 use std::os::unix::fs::PermissionsExt;
739
740 let tmp = tempdir().expect("tempdir");
741 let ctx = ToolContext::new(tmp.path().to_path_buf());
742
743 let control = tmp.path().join("control.txt");
744 fs::write(&control, b"control").expect("write control");
745
746 WriteFileTool
747 .execute(
748 json!({"path": "created.txt", "content": "from write_file"}),
749 &ctx,
750 )
751 .await
752 .expect("execute");
753
754 let control_mode = fs::metadata(&control)
755 .expect("control metadata")
756 .permissions()
757 .mode()
758 & 0o777;
759 let created_mode = fs::metadata(tmp.path().join("created.txt"))
760 .expect("created metadata")
761 .permissions()
762 .mode()
763 & 0o777;
764 assert_eq!(created_mode, control_mode);
765 }
766
767 #[cfg(unix)]
768 #[tokio::test]
769 async fn write_file_tool_preserves_existing_mode() {
770 use std::os::unix::fs::PermissionsExt;
771
772 let tmp = tempdir().expect("tempdir");
773 let ctx = ToolContext::new(tmp.path().to_path_buf());
774 let path = tmp.path().join("shared.txt");
775 fs::write(&path, b"before").expect("initial write");
776 fs::set_permissions(&path, fs::Permissions::from_mode(0o664)).expect("set shared permissions");
777 ctx.note_file_read(&ctx.resolve_path("shared.txt").expect("resolve"));
778
779 WriteFileTool
780 .execute(json!({"path": "shared.txt", "content": "after"}), &ctx)
781 .await
782 .expect("execute");
783
784 let mode = fs::metadata(&path).expect("metadata").permissions().mode() & 0o777;
785 assert_eq!(mode, 0o664);
786 assert_eq!(fs::read_to_string(&path).expect("read"), "after");
787 }
788
789 #[tokio::test]
790 async fn write_file_over_crlf_file_preserves_crlf_line_endings() {
791 let tmp = tempdir().expect("tempdir");
792 let ctx = ToolContext::new(tmp.path().to_path_buf());
793 let path = tmp.path().join("crlf.txt");
794 fs::write(&path, b"alpha\r\nbeta\r\n").expect("initial CRLF write");
795 ctx.note_file_read(&ctx.resolve_path("crlf.txt").expect("resolve"));
796
797 WriteFileTool
798 .execute(
799 json!({"path": "crlf.txt", "content": "gamma\ndelta\n"}),
800 &ctx,
801 )
802 .await
803 .expect("execute");
804
805 let written = fs::read(&path).expect("read");
806 assert_eq!(
807 written, b"gamma\r\ndelta\r\n",
808 "write_file must preserve the existing CRLF style, like edit_file"
809 );
810 WriteFileTool
811 .execute(
812 json!({"path": "crlf.txt", "content": "one\r\ntwo\rthree\n", "line_ending": "lf"}),
813 &ctx,
814 )
815 .await
816 .expect("explicit LF");
817 assert_eq!(fs::read(&path).expect("read LF"), b"one\ntwo\nthree\n");
818 WriteFileTool
819 .execute(
820 json!({"path": "crlf.txt", "content": "one\ntwo\n", "line_ending": "crlf"}),
821 &ctx,
822 )
823 .await
824 .expect("explicit CRLF");
825 assert_eq!(fs::read(&path).expect("read CRLF"), b"one\r\ntwo\r\n");
826 assert!(
827 WriteFileTool
828 .execute(
829 json!({"path": "crlf.txt", "content": "bad", "line_ending": null}),
830 &ctx
831 )
832 .await
833 .is_err()
834 );
835 assert_eq!(fs::read(&path).expect("unchanged"), b"one\r\ntwo\r\n");
836 }
837
838 #[tokio::test]
839 async fn contract_write_over_crlf_file_preserves_crlf_line_endings() {
840 // The contract `write` path (WriteFileTool::execute_contract_write) must
841 // honor the same line-ending policy as the full write_file tool.
842 let tmp = tempdir().expect("tempdir");
843 let ctx = ToolContext::new(tmp.path().to_path_buf());
844 let path = tmp.path().join("crlf.txt");
845 fs::write(&path, b"alpha\r\nbeta\r\n").expect("initial CRLF write");
846 ctx.note_file_read(&ctx.resolve_path("crlf.txt").expect("resolve"));
847
848 WriteFileTool::execute_contract_write(
849 json!({"path": "crlf.txt", "content": "gamma\ndelta\n"}),
850 &ctx,
851 )
852 .await
853 .expect("execute");
854
855 let written = fs::read(&path).expect("read");
856 assert_eq!(
857 written, b"gamma\r\ndelta\r\n",
858 "contract write must preserve the existing CRLF style, like edit_file"
859 );
860 let result = WriteFileTool::execute_contract_write(
861 json!({"path": "crlf.txt", "content": "é\r\nbeta\r", "line_ending": "lf"}),
862 &ctx,
863 )
864 .await
865 .expect("explicit LF");
866 assert_eq!(fs::read(&path).expect("LF bytes"), "é\nbeta\n".as_bytes());
867 assert!(result.content.contains("8 bytes"));
868 assert!(result.content.contains("used LF line endings"));
869 WriteFileTool::execute_contract_write(
870 json!({"path": "new.txt", "content": "one\ntwo\r", "line_ending": "crlf"}),
871 &ctx,
872 )
873 .await
874 .expect("new CRLF");
875 assert_eq!(
876 fs::read(tmp.path().join("new.txt")).expect("CRLF bytes"),
877 b"one\r\ntwo\r\n"
878 );
879 for value in [json!("invalid"), json!(null), json!(1)] {
880 assert!(
881 WriteFileTool::execute_contract_write(
882 json!({"path": "crlf.txt", "content": "bad", "line_ending": value}),
883 &ctx
884 )
885 .await
886 .is_err()
887 );
888 assert_eq!(fs::read(&path).expect("unchanged"), "é\nbeta\n".as_bytes());
889 }
890 }
891
892 #[test]
893 fn preserve_prior_line_endings_keeps_the_prior_style() {
894 // Existing CRLF file: incoming LF content is re-emitted as CRLF.
895 assert_eq!(
896 preserve_prior_line_endings("gamma\ndelta\n", "alpha\r\nbeta\r\n"),
897 "gamma\r\ndelta\r\n"
898 );
899 // Existing LF file: incoming CRLF content is re-emitted as LF.
900 assert_eq!(
901 preserve_prior_line_endings("gamma\r\ndelta\r\n", "alpha\nbeta\n"),
902 "gamma\ndelta\n"
903 );
904 // Brand-new file (no prior content): written verbatim, including CRLF.
905 assert_eq!(
906 preserve_prior_line_endings("gamma\r\ndelta\r\n", ""),
907 "gamma\r\ndelta\r\n"
908 );
909 assert_eq!(preserve_prior_line_endings("plain", ""), "plain");
910 // A lone CR in the incoming content is normalized like edit_file does: the
911 // bare \r becomes \n, then is re-emitted as CRLF when the prior is CRLF.
912 assert_eq!(
913 preserve_prior_line_endings("alpha\rbeta\n", "x\r\ny\r\n"),
914 "alpha\r\nbeta\r\n"
915 );
916 assert_eq!(
917 preserve_prior_line_endings("alpha\rbeta\n", "x\ny\n"),
918 "alpha\nbeta\n"
919 );
920 }
921
922 #[cfg(unix)]
923 #[tokio::test]
924 async fn edit_file_tool_preserves_executable_bits() {
925 use std::os::unix::fs::PermissionsExt;
926
927 let tmp = tempdir().expect("tempdir");
928 let ctx = ToolContext::new(tmp.path().to_path_buf());
929 let path = tmp.path().join("script.sh");
930 fs::write(&path, b"#!/bin/sh\nexit 0\n").expect("initial write");
931 fs::set_permissions(&path, fs::Permissions::from_mode(0o755))
932 .expect("set executable permissions");
933 read_before_edit(&ctx, "script.sh").await;
934
935 EditFileTool
936 .execute(
937 json!({
938 "path": "script.sh",
939 "search": "exit 0",
940 "replace": "exit 1"
941 }),
942 &ctx,
943 )
944 .await
945 .expect("execute");
946
947 let mode = fs::metadata(&path).expect("metadata").permissions().mode() & 0o777;
948 assert_eq!(mode, 0o755);
949 assert_eq!(
950 fs::read_to_string(&path).expect("read"),
951 "#!/bin/sh\nexit 1\n"
952 );
953 }
954
955 /// #6205 — a sloppy edit to a rustfmt-clean file lands normalized, and the
956 /// tool result's returned diff matches the bytes on disk, so the model's next
957 /// anchor is the real text.
958 #[tokio::test]
959 async fn edit_file_normalizes_a_sloppy_edit_in_a_rustfmt_clean_file() {
960 let tmp = tempdir().expect("tempdir");
961 let ctx = ToolContext::new(tmp.path().to_path_buf());
962 let path = tmp.path().join("clean.rs");
963 fs::write(&path, "fn main() {\n let x = 1;\n}\n").expect("write");
964 read_before_edit(&ctx, "clean.rs").await;
965
966 let result = EditFileTool
967 .execute(
968 json!({
969 "path": "clean.rs",
970 "search": " let x = 1;",
971 "replace": " let x = 1;\n let y=2;",
972 }),
973 &ctx,
974 )
975 .await
976 .expect("execute");
977
978 // No skip-if-missing branch: rustfmt ships with the pinned toolchain, and a
979 // test that passes vacuously without it proves nothing.
980 assert_eq!(
981 fs::read_to_string(&path).expect("read"),
982 "fn main() {\n let x = 1;\n let y = 2;\n}\n"
983 );
984 assert!(
985 result.content.contains("rustfmt-normalized"),
986 "the result must say the content was normalized: {}",
987 result.content
988 );
989 let diff = result.metadata.as_ref().expect("metadata")["mutation"]["diff"]
990 .as_str()
991 .expect("diff")
992 .to_string();
993 assert!(
994 diff.contains("+ let y = 2;"),
995 "the returned diff must show the normalized text, not what was sent: {diff}"
996 );
997 assert!(!diff.contains("let y=2;"), "{diff}");
998 }
999
1000 /// A file the author formats by hand is never reformatted wholesale.
1001 #[tokio::test]
1002 async fn edit_file_leaves_a_hand_formatted_file_alone() {
1003 let tmp = tempdir().expect("tempdir");
1004 let ctx = ToolContext::new(tmp.path().to_path_buf());
1005 let path = tmp.path().join("handmade.rs");
1006 // Two-space indentation: rustfmt would rewrite every line of this file.
1007 fs::write(&path, "fn main() {\n let x = 1;\n}\n").expect("write");
1008 read_before_edit(&ctx, "handmade.rs").await;
1009
1010 EditFileTool
1011 .execute(
1012 json!({
1013 "path": "handmade.rs",
1014 "search": " let x = 1;",
1015 "replace": " let x = 1;\n let y = 2;",
1016 }),
1017 &ctx,
1018 )
1019 .await
1020 .expect("execute");
1021
1022 assert_eq!(
1023 fs::read_to_string(&path).expect("read"),
1024 "fn main() {\n let x = 1;\n let y = 2;\n}\n",
1025 "unrelated user formatting must survive the edit"
1026 );
1027 }
1028
1029 /// #6206 — a dependency bump that leaves `Cargo.toml` unparseable is refused
1030 /// at edit time, not discovered by the next `cargo` invocation.
1031 #[tokio::test]
1032 async fn edit_file_refuses_an_edit_that_breaks_a_cargo_manifest() {
1033 let tmp = tempdir().expect("tempdir");
1034 let ctx = ToolContext::new(tmp.path().to_path_buf());
1035 let path = tmp.path().join("Cargo.toml");
1036 let original = "[dependencies]\nserde = \"1.0\"\n";
1037 fs::write(&path, original).expect("write");
1038 read_before_edit(&ctx, "Cargo.toml").await;
1039
1040 let error = EditFileTool
1041 .execute(
1042 json!({
1043 "path": "Cargo.toml",
1044 "search": "serde = \"1.0\"",
1045 // Unterminated string: the classic half-finished version bump.
1046 "replace": "serde = \"1.0",
1047 }),
1048 &ctx,
1049 )
1050 .await
1051 .expect_err("an unparseable manifest must be refused");
1052
1053 let message = error.to_string();
1054 assert!(message.contains("TOML syntax error at line"), "{message}");
1055 assert_eq!(
1056 fs::read_to_string(&path).expect("read"),
1057 original,
1058 "a refused edit must leave the manifest unchanged"
1059 );
1060 }
1061
1062 /// A valid structured-config edit is untouched by the gate.
1063 #[tokio::test]
1064 async fn edit_file_applies_a_valid_json_edit() {
1065 let tmp = tempdir().expect("tempdir");
1066 let ctx = ToolContext::new(tmp.path().to_path_buf());
1067 let path = tmp.path().join("data.json");
1068 fs::write(&path, "{\n \"port\": 8080\n}\n").expect("write");
1069 read_before_edit(&ctx, "data.json").await;
1070
1071 EditFileTool
1072 .execute(
1073 json!({
1074 "path": "data.json",
1075 "search": "8080",
1076 "replace": "9090",
1077 }),
1078 &ctx,
1079 )
1080 .await
1081 .expect("a valid JSON edit must proceed unchanged");
1082
1083 assert_eq!(
1084 fs::read_to_string(&path).expect("read"),
1085 "{\n \"port\": 9090\n}\n"
1086 );
1087 }
1088
1089 /// #6204 — an edit that takes a parseable Rust file to an unparseable one is
1090 /// refused before the write, with a `line:column` from `syn`.
1091 #[tokio::test]
1092 async fn edit_file_refuses_an_edit_that_breaks_rust_syntax() {
1093 let tmp = tempdir().expect("tempdir");
1094 let ctx = ToolContext::new(tmp.path().to_path_buf());
1095 let path = tmp.path().join("main.rs");
1096 let original = "fn main() {\n println!(\"hi\");\n}\n";
1097 fs::write(&path, original).expect("write");
1098 read_before_edit(&ctx, "main.rs").await;
1099
1100 let error = EditFileTool
1101 .execute(
1102 json!({
1103 "path": "main.rs",
1104 // Same brace balance, so the payload-corruption heuristic has
1105 // no objection; the parenthesis is what breaks the grammar.
1106 "search": "fn main() {",
1107 "replace": "fn main( {",
1108 }),
1109 &ctx,
1110 )
1111 .await
1112 .expect_err("an edit that breaks Rust syntax must be refused");
1113
1114 let message = error.to_string();
1115 assert!(message.contains("Rust syntax error at line"), "{message}");
1116 assert!(message.contains("Nothing was written"), "{message}");
1117 assert_eq!(
1118 fs::read_to_string(&path).expect("read"),
1119 original,
1120 "a refused edit must leave the file byte-for-byte unchanged"
1121 );
1122 }
1123
1124 /// The gate catches the edit that *introduces* breakage, never the one that
1125 /// repairs it: a file that already fails to parse stays editable.
1126 #[tokio::test]
1127 async fn edit_file_still_repairs_an_already_broken_rust_file() {
1128 let tmp = tempdir().expect("tempdir");
1129 let ctx = ToolContext::new(tmp.path().to_path_buf());
1130 let path = tmp.path().join("broken.rs");
1131 fs::write(&path, "fn main( {\n println!(\"hi\");\n}\n").expect("write");
1132 read_before_edit(&ctx, "broken.rs").await;
1133
1134 EditFileTool
1135 .execute(
1136 json!({
1137 "path": "broken.rs",
1138 "search": "fn main( {",
1139 "replace": "fn main() {",
1140 }),
1141 &ctx,
1142 )
1143 .await
1144 .expect("repairing a broken file must not be gated");
1145
1146 assert_eq!(
1147 fs::read_to_string(&path).expect("read"),
1148 "fn main() {\n println!(\"hi\");\n}\n"
1149 );
1150 }
1151
1152 #[tokio::test]
1153 async fn edit_file_refuses_brace_collapsed_match_arm_payload() {
1154 let tmp = tempdir().expect("tempdir");
1155 let ctx = ToolContext::new(tmp.path().to_path_buf());
1156 let path = tmp.path().join("arm.rs");
1157 let original = r#"match outcome {
1158 SendMessageOutcome::Finished {
1159 status: TurnOutcomeStatus::Interrupted,
1160 ..
1161 } => self.pause_goal_after_interruption().await,
1162 SendMessageOutcome::Finished {
1163 status: TurnOutcomeStatus::Completed,
1164 ..
1165 } => {}
1166 }
1167 "#;
1168 fs::write(&path, original).expect("write");
1169 read_before_edit(&ctx, "arm.rs").await;
1170
1171 let search = r#"SendMessageOutcome::Finished {
1172 status: TurnOutcomeStatus::Interrupted,
1173 ..
1174 } => self.pause_goal_after_interruption().await,"#;
1175 // Corrupted host payload: brace block collapsed to empty brackets.
1176 let replace = "[
1177
1178 ] => {},";
1179 let err = EditFileTool
1180 .execute(
1181 json!({
1182 "path": "arm.rs",
1183 "search": search,
1184 "replace": replace,
1185 }),
1186 &ctx,
1187 )
1188 .await
1189 .expect_err("corrupted brace collapse must fail closed");
1190 let msg = err.to_string();
1191 assert!(
1192 msg.contains("corrupted") || msg.contains("collapsed") || msg.contains("unbalanced"),
1193 "unexpected error: {msg}"
1194 );
1195 assert_eq!(fs::read_to_string(&path).expect("read"), original);
1196 }
1197
1198 #[tokio::test]
1199 async fn edit_file_preserves_rust_match_arm_braces() {
1200 let tmp = tempdir().expect("tempdir");
1201 let ctx = ToolContext::new(tmp.path().to_path_buf());
1202 let path = tmp.path().join("arm.rs");
1203 let original = r#"match outcome {
1204 SendMessageOutcome::Finished {
1205 status: TurnOutcomeStatus::Interrupted,
1206 ..
1207 } => self.pause_goal_after_interruption().await,
1208 other => {}
1209 }
1210 "#;
1211 fs::write(&path, original).expect("write");
1212 read_before_edit(&ctx, "arm.rs").await;
1213
1214 let search = r#"SendMessageOutcome::Finished {
1215 status: TurnOutcomeStatus::Interrupted,
1216 ..
1217 } => self.pause_goal_after_interruption().await,"#;
1218 let replace = r#"SendMessageOutcome::Finished {
1219 status: TurnOutcomeStatus::Interrupted,
1220 ..
1221 } => {
1222 // stay active
1223 let _ = self.tx_event.send(Event::status("ok".into())).await;
1224 }"#;
1225 EditFileTool
1226 .execute(
1227 json!({
1228 "path": "arm.rs",
1229 "search": search,
1230 "replace": replace,
1231 }),
1232 &ctx,
1233 )
1234 .await
1235 .expect("brace-heavy replace must apply");
1236 let updated = fs::read_to_string(&path).expect("read");
1237 assert!(updated.contains("stay active"), "{updated}");
1238 assert!(
1239 updated.contains("SendMessageOutcome::Finished"),
1240 "{updated}"
1241 );
1242 assert!(
1243 !updated.contains("pause_goal_after_interruption"),
1244 "{updated}"
1245 );
1246 }
1247
1248 #[tokio::test]
1249 async fn test_edit_file_tool() {
1250 let tmp = tempdir().expect("tempdir");
1251 let ctx = ToolContext::new(tmp.path().to_path_buf());
1252
1253 // Create a file to edit
1254 let test_file = tmp.path().join("edit_me.txt");
1255 fs::write(&test_file, "hello world").expect("write");
1256 read_before_edit(&ctx, "edit_me.txt").await;
1257
1258 let tool = EditFileTool;
1259 let result = tool
1260 .execute(
1261 json!({"path": "edit_me.txt", "search": "hello", "replace": "hi"}),
1262 &ctx,
1263 )
1264 .await
1265 .expect("execute");
1266
1267 assert!(result.success);
1268 assert!(result.content.contains("Replaced 1 occurrence"));
1269 // Inline diff (#505) — the unified diff lands above the summary
1270 // line so the TUI's diff-aware renderer kicks in.
1271 assert!(result.content.contains("--- a/"), "{}", result.content);
1272 assert!(
1273 result.content.contains("-hello world"),
1274 "{}",
1275 result.content
1276 );
1277 assert!(result.content.contains("+hi world"), "{}", result.content);
1278 let mutation = &result.metadata.as_ref().expect("metadata")["mutation"];
1279 assert_eq!(
1280 mutation["files"],
1281 json!([{
1282 "path": "edit_me.txt",
1283 "outcome": "updated",
1284 "size": fs::read(tmp.path().join("edit_me.txt")).expect("edited").len(),
1285 "sha256": codewhale_runtime::hashing::sha256_hex(
1286 fs::read(tmp.path().join("edit_me.txt")).expect("edited")
1287 ),
1288 }])
1289 );
1290 let receipt_diff = mutation["diff"].as_str().expect("receipt diff");
1291 assert!(receipt_diff.contains("--- a/edit_me.txt"), "{receipt_diff}");
1292 assert!(receipt_diff.contains("-hello world"), "{receipt_diff}");
1293 assert!(receipt_diff.contains("+hi world"), "{receipt_diff}");
1294 assert!(
1295 !receipt_diff.contains(&tmp.path().display().to_string()),
1296 "receipt headers must not expose the resolved host path: {receipt_diff}"
1297 );
1298
1299 // Verify edit was applied
1300 let edited = fs::read_to_string(&test_file).expect("read");
1301 assert_eq!(edited, "hi world");
1302 }
1303
1304 #[tokio::test]
1305 async fn edit_file_matches_lf_search_in_crlf_file_and_preserves_crlf() {
1306 let tmp = tempdir().expect("tempdir");
1307 let ctx = ToolContext::new(tmp.path().to_path_buf());
1308 let test_file = tmp.path().join("crlf.py");
1309 fs::write(
1310 &test_file,
1311 b"def greet(name):\r\n print(name)\r\n\r\ndef add(a, b):\r\n return a + b\r\n",
1312 )
1313 .expect("write");
1314 read_before_edit(&ctx, "crlf.py").await;
1315
1316 let result = EditFileTool
1317 .execute(
1318 json!({
1319 "path": "crlf.py",
1320 "search": "def add(a, b):\n return a + b",
1321 "replace": "def add(a, b):\n return a * b",
1322 }),
1323 &ctx,
1324 )
1325 .await
1326 .expect("LF model input should edit a CRLF file");
1327
1328 assert!(result.success, "{}", result.content);
1329 assert_eq!(
1330 fs::read(&test_file).expect("read"),
1331 b"def greet(name):\r\n print(name)\r\n\r\ndef add(a, b):\r\n return a * b\r\n",
1332 );
1333 }
1334
1335 #[test]
1336 fn edit_file_sparse_crlf_positions_map_utf8_range_through_eof() {
1337 let original = "前\r\n尾";
1338 let (normalized, crlf_positions) = normalize_crlf_with_positions(original);
1339
1340 assert_eq!(normalized, "前\n尾");
1341 assert_eq!(crlf_positions.as_deref(), Some(&[3][..]));
1342 assert_eq!(
1343 map_normalized_range((0, normalized.len()), crlf_positions.as_deref()),
1344 (0, original.len()),
1345 );
1346 }
1347
1348 #[tokio::test]
1349 async fn edit_file_maps_utf8_crlf_match_ending_at_eof() {
1350 let tmp = tempdir().expect("tempdir");
1351 let ctx = ToolContext::new(tmp.path().to_path_buf());
1352 let test_file = tmp.path().join("utf8-eof-crlf.txt");
1353 fs::write(&test_file, "前\r\n尾").expect("write");
1354 read_before_edit(&ctx, "utf8-eof-crlf.txt").await;
1355
1356 EditFileTool
1357 .execute(
1358 json!({
1359 "path": "utf8-eof-crlf.txt",
1360 "search": "前\n尾",
1361 "replace": "始\n终",
1362 }),
1363 &ctx,
1364 )
1365 .await
1366 .expect("UTF-8 CRLF match should map through EOF");
1367
1368 assert_eq!(fs::read(&test_file).expect("read"), "始\r\n终".as_bytes(),);
1369 }
1370
1371 #[tokio::test]
1372 async fn edit_file_normalizes_multiline_replacement_for_single_line_crlf_match() {
1373 let tmp = tempdir().expect("tempdir");
1374 let ctx = ToolContext::new(tmp.path().to_path_buf());
1375 let test_file = tmp.path().join("single-line-crlf.txt");
1376 fs::write(&test_file, b"alpha\r\nomega\r\n").expect("write");
1377 read_before_edit(&ctx, "single-line-crlf.txt").await;
1378
1379 EditFileTool
1380 .execute(
1381 json!({
1382 "path": "single-line-crlf.txt",
1383 "search": "omega",
1384 "replace": "beta\ngamma",
1385 }),
1386 &ctx,
1387 )
1388 .await
1389 .expect("replacement should follow the file's CRLF style");
1390
1391 assert_eq!(
1392 fs::read(&test_file).expect("read"),
1393 b"alpha\r\nbeta\r\ngamma\r\n",
1394 );
1395 }
1396
1397 #[tokio::test]
1398 async fn edit_file_normalizes_crlf_and_mixed_replacement_for_lf_file() {
1399 let tmp = tempdir().expect("tempdir");
1400 let ctx = ToolContext::new(tmp.path().to_path_buf());
1401 let test_file = tmp.path().join("lf.txt");
1402 fs::write(&test_file, b"alpha\nomega\n").expect("write");
1403 read_before_edit(&ctx, "lf.txt").await;
1404
1405 EditFileTool
1406 .execute(
1407 json!({
1408 "path": "lf.txt",
1409 "search": "omega",
1410 "replace": "beta\r\ngamma\nfinal",
1411 }),
1412 &ctx,
1413 )
1414 .await
1415 .expect("replacement should follow the file's LF style");
1416
1417 assert_eq!(
1418 fs::read(&test_file).expect("read"),
1419 b"alpha\nbeta\ngamma\nfinal\n",
1420 );
1421 }
1422
1423 #[tokio::test]
1424 async fn edit_file_rejects_logical_duplicate_across_lf_and_crlf() {
1425 let tmp = tempdir().expect("tempdir");
1426 let ctx = ToolContext::new(tmp.path().to_path_buf());
1427 let test_file = tmp.path().join("mixed.txt");
1428 let original = b"same\nblock\r\nsame\r\nblock\r\n";
1429 fs::write(&test_file, original).expect("write");
1430 read_before_edit(&ctx, "mixed.txt").await;
1431
1432 let error = EditFileTool
1433 .execute(
1434 json!({
1435 "path": "mixed.txt",
1436 "search": "same\nblock",
1437 "replace": "changed",
1438 }),
1439 &ctx,
1440 )
1441 .await
1442 .expect_err("logical duplicates must remain non-unique");
1443
1444 assert!(error.to_string().contains("matched 2"), "{error}");
1445 assert_eq!(fs::read(&test_file).expect("read"), original);
1446 }
1447
1448 #[tokio::test]
1449 async fn edit_file_combines_crlf_and_indentation_fuzzy_matching() {
1450 let tmp = tempdir().expect("tempdir");
1451 let ctx = ToolContext::new(tmp.path().to_path_buf());
1452 let test_file = tmp.path().join("fuzzy-crlf.txt");
1453 fs::write(&test_file, "前言\r\n 数据 = 1\r\n").expect("write");
1454 read_before_edit(&ctx, "fuzzy-crlf.txt").await;
1455
1456 let result = EditFileTool
1457 .execute(
1458 json!({
1459 "path": "fuzzy-crlf.txt",
1460 "search": "前言\n 数据 = 1",
1461 "replace": "前言\n 数据 = 2",
1462 }),
1463 &ctx,
1464 )
1465 .await
1466 .expect("indentation fallback should compose with CRLF normalization");
1467
1468 assert!(
1469 result.content.contains("fuzzy indentation match"),
1470 "{}",
1471 result.content
1472 );
1473 assert_eq!(
1474 fs::read(&test_file).expect("read"),
1475 "前言\r\n 数据 = 2\r\n".as_bytes(),
1476 );
1477 }
1478
1479 #[tokio::test]
1480 async fn edit_file_combines_crlf_and_punctuation_fuzzy_matching() {
1481 let tmp = tempdir().expect("tempdir");
1482 let ctx = ToolContext::new(tmp.path().to_path_buf());
1483 let test_file = tmp.path().join("punctuation-crlf.txt");
1484 fs::write(&test_file, "前言\r\n数据 \"x\"\r\n").expect("write");
1485 read_before_edit(&ctx, "punctuation-crlf.txt").await;
1486
1487 let result = EditFileTool
1488 .execute(
1489 json!({
1490 "path": "punctuation-crlf.txt",
1491 "search": "前言\n数据 \u{201C}x\u{201D}",
1492 "replace": "前言\r\n数据 y\n下一行",
1493 }),
1494 &ctx,
1495 )
1496 .await
1497 .expect("punctuation fallback should compose with CRLF normalization");
1498
1499 assert!(
1500 result.content.contains("fuzzy punctuation match"),
1501 "{}",
1502 result.content
1503 );
1504 assert_eq!(
1505 fs::read(&test_file).expect("read"),
1506 "前言\r\n数据 y\r\n下一行\r\n".as_bytes(),
1507 );
1508 }
1509
1510 #[tokio::test]
1511 async fn edit_file_rejects_line_ending_normalized_noop() {
1512 let tmp = tempdir().expect("tempdir");
1513 let ctx = ToolContext::new(tmp.path().to_path_buf());
1514 let test_file = tmp.path().join("noop-crlf.txt");
1515 let original = b"alpha\r\nbeta\r\n";
1516 fs::write(&test_file, original).expect("write");
1517 read_before_edit(&ctx, "noop-crlf.txt").await;
1518
1519 let error = EditFileTool
1520 .execute(
1521 json!({
1522 "path": "noop-crlf.txt",
1523 "search": "alpha\nbeta",
1524 "replace": "alpha\r\nbeta",
1525 }),
1526 &ctx,
1527 )
1528 .await
1529 .expect_err("normalized no-op should be rejected");
1530
1531 assert!(error.to_string().contains("no change intended"), "{error}");
1532 assert_eq!(fs::read(&test_file).expect("read"), original);
1533 }
1534
1535 #[tokio::test]
1536 async fn edit_file_requires_prior_read() {
1537 let tmp = tempdir().expect("tempdir");
1538 let ctx = ToolContext::new(tmp.path().to_path_buf());
1539
1540 let test_file = tmp.path().join("blind.txt");
1541 fs::write(&test_file, "hello world").expect("write");
1542
1543 let err = EditFileTool
1544 .execute(
1545 json!({"path": "blind.txt", "search": "hello", "replace": "hi"}),
1546 &ctx,
1547 )
1548 .await
1549 .expect_err("edit without read should fail");
1550 let message = err.to_string();
1551 assert!(message.contains("not been read"), "{message}");
1552 assert!(
1553 message.contains(r#"call read path="blind.txt""#),
1554 "{message}"
1555 );
1556 assert!(!message.contains("read_file"), "{message}");
1557
1558 let unchanged = fs::read_to_string(&test_file).expect("read");
1559 assert_eq!(unchanged, "hello world");
1560 }
1561
1562 #[tokio::test]
1563 async fn edit_file_rejects_stale_prior_read() {
1564 let tmp = tempdir().expect("tempdir");
1565 let ctx = ToolContext::new(tmp.path().to_path_buf());
1566
1567 let test_file = tmp.path().join("stale.txt");
1568 fs::write(&test_file, "alpha beta").expect("write");
1569 read_before_edit(&ctx, "stale.txt").await;
1570 fs::write(&test_file, "alpha beta gamma").expect("external write");
1571
1572 let err = EditFileTool
1573 .execute(
1574 json!({"path": "stale.txt", "search": "alpha", "replace": "omega"}),
1575 &ctx,
1576 )
1577 .await
1578 .expect_err("stale read should fail");
1579 let message = err.to_string();
1580 assert!(message.contains("changed since"), "{message}");
1581 assert!(
1582 message.contains(r#"call read path="stale.txt""#),
1583 "{message}"
1584 );
1585 assert!(!message.contains("read_file"), "{message}");
1586
1587 let unchanged = fs::read_to_string(&test_file).expect("read");
1588 assert_eq!(unchanged, "alpha beta gamma");
1589 }
1590
1591 #[tokio::test]
1592 async fn edit_file_rejects_non_unique_exact_match() {
1593 let tmp = tempdir().expect("tempdir");
1594 let ctx = ToolContext::new(tmp.path().to_path_buf());
1595
1596 let test_file = tmp.path().join("multi.txt");
1597 fs::write(&test_file, "hello world hello").expect("write");
1598 read_before_edit(&ctx, "multi.txt").await;
1599
1600 let err = EditFileTool
1601 .execute(
1602 json!({"path": "multi.txt", "search": "hello", "replace": "hi"}),
1603 &ctx,
1604 )
1605 .await
1606 .expect_err("non-unique exact match should fail");
1607 let message = err.to_string();
1608 assert!(message.contains("non-unique"), "{message}");
1609 assert!(message.contains("matched 2"), "{message}");
1610 assert!(
1611 message.contains("call `read` with path=\"multi.txt\""),
1612 "{message}"
1613 );
1614 assert!(!message.contains("File with action=\"read\""), "{message}");
1615 assert!(!message.contains("read_file"), "{message}");
1616
1617 let unchanged = fs::read_to_string(&test_file).expect("read");
1618 assert_eq!(unchanged, "hello world hello");
1619 }
1620
1621 /// `fuzz` on `edit` was an advertised parameter with no implementation: it
1622 /// was parsed into `let _fuzz` and thrown away, and a live model read the
1623 /// schema as offering "an optional fuzzy-matching flag for the search". The
1624 /// advertisement is gone, so the name now means nothing to `edit` and is
1625 /// refused like any other name with no known meaning — the fuzzy fallbacks it
1626 /// appeared to control run unconditionally either way.
1627 #[tokio::test]
1628 async fn edit_file_refuses_the_retired_fuzz_parameter() {
1629 let tmp = tempdir().expect("tempdir");
1630 let ctx = ToolContext::new(tmp.path().to_path_buf());
1631 let test_file = tmp.path().join("fuzz_retired.txt");
1632 fs::write(&test_file, "hello world").expect("write");
1633 read_before_edit(&ctx, "fuzz_retired.txt").await;
1634
1635 let err = EditFileTool
1636 .execute(
1637 json!({
1638 "path": "fuzz_retired.txt",
1639 "search": "hello",
1640 "replace": "hi",
1641 "fuzz": true,
1642 }),
1643 &ctx,
1644 )
1645 .await
1646 .expect_err("a parameter edit does not implement must be refused");
1647 let msg = err.to_string();
1648 assert!(msg.contains("fuzz"), "must name the parameter: {msg}");
1649 assert!(
1650 msg.contains("was not performed"),
1651 "must deny having edited: {msg}"
1652 );
1653 assert_eq!(
1654 fs::read_to_string(&test_file).expect("read"),
1655 "hello world",
1656 "a refused edit must not touch the file"
1657 );
1658 }
1659
1660 #[tokio::test]
1661 async fn test_edit_file_single_match_has_no_multi_match_warning() {
1662 let tmp = tempdir().expect("tempdir");
1663 let ctx = ToolContext::new(tmp.path().to_path_buf());
1664
1665 let test_file = tmp.path().join("single.txt");
1666 fs::write(&test_file, "hello world").expect("write");
1667 read_before_edit(&ctx, "single.txt").await;
1668
1669 let tool = EditFileTool;
1670 let result = tool
1671 .execute(
1672 json!({"path": "single.txt", "search": "hello", "replace": "hi"}),
1673 &ctx,
1674 )
1675 .await
1676 .expect("execute");
1677
1678 assert!(result.success);
1679 assert!(result.content.contains("Replaced 1 occurrence"));
1680 assert!(!result.content.contains("multiple matches were replaced"));
1681 }
1682
1683 #[tokio::test]
1684 async fn test_edit_file_fuzz_tolerates_leading_whitespace() {
1685 let tmp = tempdir().expect("tempdir");
1686 let ctx = ToolContext::new(tmp.path().to_path_buf());
1687
1688 let test_file = tmp.path().join("fuzzy.txt");
1689 fs::write(
1690 &test_file,
1691 "fn main() {\n if true {\n let value = 1;\n }\n}\n",
1692 )
1693 .expect("write");
1694 read_before_edit(&ctx, "fuzzy.txt").await;
1695
1696 let tool = EditFileTool;
1697 let result = tool
1698 .execute(
1699 json!({
1700 "path": "fuzzy.txt",
1701 "search": "if true {\n let value = 1;\n}",
1702 "replace": " if true {\n let value = 2;\n }"
1703 }),
1704 &ctx,
1705 )
1706 .await
1707 .expect("execute");
1708
1709 assert!(result.success);
1710 assert!(result.content.contains("fuzzy indentation match"));
1711 let edited = fs::read_to_string(&test_file).expect("read");
1712 assert_eq!(
1713 edited,
1714 "fn main() {\n if true {\n let value = 2;\n }\n}\n"
1715 );
1716 }
1717
1718 #[tokio::test]
1719 async fn test_edit_file_fuzz_tolerates_leading_whitespace_after_multibyte_start() {
1720 let tmp = tempdir().expect("tempdir");
1721 let ctx = ToolContext::new(tmp.path().to_path_buf());
1722
1723 let test_file = tmp.path().join("fuzzy_cjk.txt");
1724 fs::write(&test_file, "数据\n").expect("write");
1725 read_before_edit(&ctx, "fuzzy_cjk.txt").await;
1726
1727 let tool = EditFileTool;
1728 let result = tool
1729 .execute(
1730 json!({
1731 "path": "fuzzy_cjk.txt",
1732 "search": " 数据",
1733 "replace": "记录"
1734 }),
1735 &ctx,
1736 )
1737 .await
1738 .expect("execute");
1739
1740 assert!(result.success, "{}", result.content);
1741 assert!(result.content.contains("fuzzy indentation match"));
1742 let edited = fs::read_to_string(&test_file).expect("read");
1743 assert_eq!(edited, "记录\n");
1744 }
1745
1746 #[tokio::test]
1747 async fn test_edit_file_fuzz_tolerates_smart_quote_substitution() {
1748 // The file on disk has ASCII quotes. The search comes from a
1749 // browser paste with curly quotes. Exact match fails; the
1750 // punctuation-normalized fallback should still land the edit.
1751 let tmp = tempdir().expect("tempdir");
1752 let ctx = ToolContext::new(tmp.path().to_path_buf());
1753
1754 let test_file = tmp.path().join("smart.rs");
1755 fs::write(&test_file, "let s = \"hello world\";\n").expect("write");
1756 read_before_edit(&ctx, "smart.rs").await;
1757
1758 let tool = EditFileTool;
1759 let result = tool
1760 .execute(
1761 json!({
1762 "path": "smart.rs",
1763 // \u{201C} \u{201D} are the curly double-quote pair.
1764 "search": "let s = \u{201C}hello world\u{201D};",
1765 "replace": "let s = \"hello universe\";"
1766 }),
1767 &ctx,
1768 )
1769 .await
1770 .expect("execute");
1771
1772 assert!(result.success, "fuzzy punctuation edit should succeed");
1773 assert!(
1774 result.content.contains("fuzzy punctuation match"),
1775 "expected punctuation-fuzz note, got: {}",
1776 result.content
1777 );
1778 let edited = fs::read_to_string(&test_file).expect("read");
1779 assert_eq!(edited, "let s = \"hello universe\";\n");
1780 }
1781
1782 #[tokio::test]
1783 async fn test_edit_file_fuzz_tolerates_smart_quote_after_multibyte_start() {
1784 let tmp = tempdir().expect("tempdir");
1785 let ctx = ToolContext::new(tmp.path().to_path_buf());
1786
1787 let test_file = tmp.path().join("smart_cjk.md");
1788 fs::write(&test_file, "数据 \"x\"\n").expect("write");
1789 read_before_edit(&ctx, "smart_cjk.md").await;
1790
1791 let tool = EditFileTool;
1792 let result = tool
1793 .execute(
1794 json!({
1795 "path": "smart_cjk.md",
1796 "search": "数据 \u{201C}x\u{201D}",
1797 "replace": "数据 y"
1798 }),
1799 &ctx,
1800 )
1801 .await
1802 .expect("execute");
1803
1804 assert!(result.success, "{}", result.content);
1805 assert!(result.content.contains("fuzzy punctuation match"));
1806 let edited = fs::read_to_string(&test_file).expect("read");
1807 assert_eq!(edited, "数据 y\n");
1808 }
1809
1810 #[tokio::test]
1811 async fn test_edit_file_fuzz_tolerates_em_dash_and_nbsp() {
1812 let tmp = tempdir().expect("tempdir");
1813 let ctx = ToolContext::new(tmp.path().to_path_buf());
1814
1815 let test_file = tmp.path().join("dash.md");
1816 // File has an ASCII hyphen and ASCII space.
1817 fs::write(&test_file, "alpha - beta\n").expect("write");
1818 read_before_edit(&ctx, "dash.md").await;
1819
1820 let tool = EditFileTool;
1821 let result = tool
1822 .execute(
1823 json!({
1824 "path": "dash.md",
1825 // Search uses em-dash + NBSP, common after a copy-paste
1826 // from a styled document.
1827 "search": "alpha\u{00A0}\u{2014}\u{00A0}beta",
1828 "replace": "alpha - gamma"
1829 }),
1830 &ctx,
1831 )
1832 .await
1833 .expect("execute");
1834
1835 assert!(result.success);
1836 let edited = fs::read_to_string(&test_file).expect("read");
1837 assert_eq!(edited, "alpha - gamma\n");
1838 }
1839
1840 #[tokio::test]
1841 async fn test_edit_file_not_found() {
1842 let tmp = tempdir().expect("tempdir");
1843 let ctx = ToolContext::new(tmp.path().to_path_buf());
1844
1845 // Create a file without the search string
1846 let test_file = tmp.path().join("no_match.txt");
1847 fs::write(&test_file, "foo bar baz").expect("write");
1848 read_before_edit(&ctx, "no_match.txt").await;
1849
1850 let tool = EditFileTool;
1851 let result = tool
1852 .execute(
1853 json!({"path": "no_match.txt", "search": "hello", "replace": "hi"}),
1854 &ctx,
1855 )
1856 .await;
1857
1858 assert!(result.is_err());
1859 let err = result.unwrap_err();
1860 assert!(err.to_string().contains("not found"));
1861 assert!(
1862 err.to_string()
1863 .contains("call `read` with path=\"no_match.txt\"")
1864 );
1865 assert!(!err.to_string().contains("File with action=\"read\""));
1866 assert!(!err.to_string().contains("read_file"));
1867 }
1868
1869 #[tokio::test]
1870 async fn test_edit_file_rejects_identical_search_and_replace() {
1871 let tmp = tempdir().expect("tempdir");
1872 let ctx = ToolContext::new(tmp.path().to_path_buf());
1873
1874 let test_file = tmp.path().join("same.txt");
1875 fs::write(&test_file, "a := \"foo\"").expect("write");
1876
1877 let tool = EditFileTool;
1878 let result = tool
1879 .execute(
1880 json!({
1881 "path": "same.txt",
1882 "search": "a := \"foo\"",
1883 "replace": "a := \"foo\""
1884 }),
1885 &ctx,
1886 )
1887 .await;
1888
1889 assert!(result.is_err());
1890 let err = result.unwrap_err().to_string();
1891 assert!(
1892 err.contains("search and replace are identical"),
1893 "error must explain the no-op input: {err}"
1894 );
1895 // #5003 - the diagnostic must help the model self-correct: it should
1896 // size the payload and point at the root cause instead of a bare
1897 // "no change intended".
1898 assert!(
1899 err.contains("10 chars"),
1900 "error should size the payload: {err}"
1901 );
1902 assert!(
1903 err.contains("Recovery: re-read the file with `read`"),
1904 "error should offer recovery using `read`: {err}"
1905 );
1906 assert!(!err.contains("File action=\"read\""), "{err}");
1907 let unchanged = fs::read_to_string(&test_file).expect("read");
1908 assert_eq!(unchanged, "a := \"foo\"");
1909 }
1910
1911 #[test]
1912 fn test_c_preprocessor_rejects_missing_close() {
1913 let before = "#if FEATURE\nold code\n#endif\n";
1914 let after = "#if FEATURE\nnew code\n";
1915 assert_eq!(
1916 invalid_preprocessor_edit(Path::new("source.c"), before, after),
1917 Some(PREPROCESSOR_CONDITIONAL_ERROR)
1918 );
1919 }
1920
1921 #[test]
1922 fn test_c_preprocessor_rejects_extra_close() {
1923 let before = "#if FEATURE\nold code\n#endif\n";
1924 let after = "#if FEATURE\nnew code\n#endif\n#endif\n";
1925 assert_eq!(
1926 invalid_preprocessor_edit(Path::new("source.hpp"), before, after),
1927 Some(PREPROCESSOR_CONDITIONAL_ERROR)
1928 );
1929 }
1930
1931 #[test]
1932 fn test_c_preprocessor_allows_balanced_block_removal_and_insertion() {
1933 let block = "#ifdef FEATURE\nfeature();\n#endif\n";
1934 assert!(invalid_preprocessor_edit(Path::new("source.cc"), block, "").is_none());
1935 assert!(invalid_preprocessor_edit(Path::new("source.cc"), "", block).is_none());
1936 }
1937
1938 #[test]
1939 fn test_c_preprocessor_allows_in_block_edit() {
1940 let before = "#if FEATURE\nold_call();\n#endif\n";
1941 let after = "#if FEATURE\nnew_call();\n#endif\n";
1942 assert!(invalid_preprocessor_edit(Path::new("source.cxx"), before, after).is_none());
1943 }
1944
1945 #[test]
1946 fn test_non_c_directive_prose_is_not_validated() {
1947 let before = "#if this example is enabled\nexplanation\n#endif\n";
1948 let after = "#if this example is enabled\nupdated explanation\n";
1949 assert!(invalid_preprocessor_edit(Path::new("guide.md"), before, after).is_none());
1950 }
1951
1952 #[test]
1953 fn test_preview_search_for_error_truncates() {
1954 let long_line = "x".repeat(200);
1955 let search = format!("{long_line}\nsecond line\nthird line\nfourth line\n");
1956 let preview = preview_search_for_error(&search);
1957 assert!(preview.lines().count() <= 3);
1958 assert!(preview.contains("..."));
1959 assert!(!preview.contains("fourth line"));
1960 }
1961
1962 #[tokio::test]
1963 async fn test_edit_file_not_found_shows_search_preview() {
1964 // #5003 - when search misses, the error should preview the search text
1965 // so the model can compare what it searched for against the file.
1966 let tmp = tempdir().expect("tempdir");
1967 let ctx = ToolContext::new(tmp.path().to_path_buf());
1968
1969 let test_file = tmp.path().join("preview.txt");
1970 fs::write(&test_file, "foo bar baz").expect("write");
1971 read_before_edit(&ctx, "preview.txt").await;
1972
1973 let tool = EditFileTool;
1974 let result = tool
1975 .execute(
1976 json!({
1977 "path": "preview.txt",
1978 "search": "first line\nsecond line\n",
1979 "replace": "changed"
1980 }),
1981 &ctx,
1982 )
1983 .await;
1984
1985 assert!(result.is_err());
1986 let err = result.unwrap_err().to_string();
1987 assert!(err.contains("Search string not found"));
1988 assert!(
1989 err.contains("first line"),
1990 "error should preview search text: {err}"
1991 );
1992 }
1993
1994 /// #6542 — a missed search returns the nearest region with line numbers and
1995 /// names a whitespace-only difference, so the retry can copy the real text.
1996 #[tokio::test]
1997 async fn edit_miss_returns_nearest_excerpt_with_line_numbers_and_whitespace_note() {
1998 let tmp = tempdir().expect("tempdir");
1999 let ctx = ToolContext::new(tmp.path().to_path_buf());
2000 fs::write(
2001 tmp.path().join("near.rs"),
2002 "fn a() {}\n\nfn compute(x: u32) -> u32 {\n x + 1\n}\n",
2003 )
2004 .expect("write");
2005 read_before_edit(&ctx, "near.rs").await;
2006
2007 let err = EditFileTool
2008 .execute(
2009 json!({
2010 "path": "near.rs",
2011 "search": "fn compute(x: u32) -> u32 { \n x + 1\n}",
2012 "replace": "fn compute(x: u32) -> u32 {\n x + 2\n}"
2013 }),
2014 &ctx,
2015 )
2016 .await
2017 .expect_err("trailing whitespace keeps the search from matching")
2018 .to_string();
2019 assert!(err.contains("Closest match (lines 3-5"), "{err}");
2020 assert!(err.contains("3\tfn compute(x: u32) -> u32 {"), "{err}");
2021 assert!(err.contains("trailing whitespace"), "{err}");
2022
2023 let err = EditFileTool
2024 .execute(
2025 json!({
2026 "path": "near.rs",
2027 "search": "completely unrelated text\nnothing like it",
2028 "replace": "x"
2029 }),
2030 &ctx,
2031 )
2032 .await
2033 .expect_err("no match")
2034 .to_string();
2035 assert!(err.contains("No similar region"), "{err}");
2036 }
2037
2038 /// #157 / #5209 — `replacement` is an unambiguous synonym for `replace`, so
2039 /// the edit the model asked for is the edit that lands. The #5209 guarantee
2040 /// being protected is that the file and the receipt agree: a reported
2041 /// replacement must correspond to a real one.
2042 #[tokio::test]
2043 async fn edit_file_accepts_replacement_alias_and_applies_the_edit() {
2044 let tmp = tempdir().expect("tempdir");
2045 let ctx = ToolContext::new(tmp.path().to_path_buf());
2046
2047 let test_file = tmp.path().join("test.txt");
2048 fs::write(&test_file, "hello world").expect("write");
2049 read_before_edit(&ctx, "test.txt").await;
2050
2051 let result = EditFileTool
2052 .execute(
2053 json!({"path": "test.txt", "search": "hello", "replacement": "hi"}),
2054 &ctx,
2055 )
2056 .await
2057 .expect("replacement alias must be honored");
2058
2059 assert!(result.success);
2060 assert_eq!(
2061 fs::read_to_string(&test_file).expect("read"),
2062 "hi world",
2063 "the receipt claimed an edit, so the file must actually carry it"
2064 );
2065 }
2066
2067 /// Every cross-harness spelling of the two edit arguments resolves to the
2068 /// same applied edit. A model that guesses from a different harness's prior
2069 /// gets its work done instead of a rejection and a wasted turn (#5209).
2070 #[tokio::test]
2071 async fn edit_file_accepts_every_cross_harness_edit_alias() {
2072 for (search_key, replace_key) in [
2073 ("old_string", "new_string"),
2074 ("old_str", "new_str"),
2075 ("oldText", "newText"),
2076 ("old_text", "new_text"),
2077 ] {
2078 let tmp = tempdir().expect("tempdir");
2079 let ctx = ToolContext::new(tmp.path().to_path_buf());
2080 let path = tmp.path().join("doc.md");
2081 fs::write(&path, "old text line\n").expect("write");
2082 read_before_edit(&ctx, "doc.md").await;
2083
2084 let result = EditFileTool
2085 .execute(
2086 json!({
2087 "path": "doc.md",
2088 search_key: "old text line",
2089 replace_key: "new text line",
2090 }),
2091 &ctx,
2092 )
2093 .await
2094 .unwrap_or_else(|err| panic!("{search_key}/{replace_key} must apply: {err}"));
2095
2096 assert!(result.success, "{search_key}/{replace_key}");
2097 assert_eq!(
2098 fs::read_to_string(&path).expect("read"),
2099 "new text line\n",
2100 "{search_key}/{replace_key} must reach the file"
2101 );
2102 }
2103 }
2104
2105 /// An alias that contradicts an explicitly supplied canonical value is
2106 /// ambiguous. Picking one would be the guess this whole path exists to
2107 /// avoid, so it fails and changes nothing.
2108 #[tokio::test]
2109 async fn edit_file_rejects_alias_conflicting_with_canonical_name() {
2110 let tmp = tempdir().expect("tempdir");
2111 let ctx = ToolContext::new(tmp.path().to_path_buf());
2112 let path = tmp.path().join("doc.md");
2113 fs::write(&path, "old text line\n").expect("write");
2114 read_before_edit(&ctx, "doc.md").await;
2115
2116 let err = EditFileTool
2117 .execute(
2118 json!({
2119 "path": "doc.md",
2120 "search": "old text line",
2121 "replace": "one thing",
2122 "new_string": "a different thing",
2123 }),
2124 &ctx,
2125 )
2126 .await
2127 .expect_err("conflicting alias must not be silently resolved");
2128
2129 let msg = err.to_string();
2130 assert!(
2131 msg.contains("`replace`") && msg.contains("`new_string`"),
2132 "must name both spellings: {msg}"
2133 );
2134 assert_eq!(
2135 fs::read_to_string(&path).expect("read"),
2136 "old text line\n",
2137 "nothing may change on an ambiguous call"
2138 );
2139 }
2140
2141 /// An alias that merely repeats the canonical value is a harmless
2142 /// duplicate, not a conflict.
2143 #[tokio::test]
2144 async fn edit_file_accepts_alias_agreeing_with_canonical_name() {
2145 let tmp = tempdir().expect("tempdir");
2146 let ctx = ToolContext::new(tmp.path().to_path_buf());
2147 let path = tmp.path().join("doc.md");
2148 fs::write(&path, "old text line\n").expect("write");
2149 read_before_edit(&ctx, "doc.md").await;
2150
2151 EditFileTool
2152 .execute(
2153 json!({
2154 "path": "doc.md",
2155 "search": "old text line",
2156 "replace": "new text line",
2157 "new_string": "new text line",
2158 }),
2159 &ctx,
2160 )
2161 .await
2162 .expect("agreeing duplicate must be accepted");
2163
2164 assert_eq!(fs::read_to_string(&path).expect("read"), "new text line\n");
2165 }
2166
2167 /// `file_path` is the other widespread spelling of `path` and is accepted on
2168 /// every file action.
2169 #[tokio::test]
2170 async fn file_actions_accept_file_path_alias() {
2171 let tmp = tempdir().expect("tempdir");
2172 let ctx = ToolContext::new(tmp.path().to_path_buf());
2173
2174 WriteFileTool
2175 .execute(json!({"file_path": "note.txt", "content": "first\n"}), &ctx)
2176 .await
2177 .expect("write must accept file_path");
2178 assert_eq!(
2179 fs::read_to_string(tmp.path().join("note.txt")).expect("read"),
2180 "first\n"
2181 );
2182
2183 let read = ReadFileTool
2184 .execute(json!({"file_path": "note.txt"}), &ctx)
2185 .await
2186 .expect("read must accept file_path");
2187 assert!(read.content.contains("first"));
2188
2189 EditFileTool
2190 .execute(
2191 json!({"file_path": "note.txt", "search": "first", "replace": "second"}),
2192 &ctx,
2193 )
2194 .await
2195 .expect("edit must accept file_path");
2196 assert_eq!(
2197 fs::read_to_string(tmp.path().join("note.txt")).expect("read"),
2198 "second\n"
2199 );
2200 }
2201
2202 /// `offset`/`limit` name the same read window as `start_line`/`max_lines`.
2203 /// Before they were translated, a wrong guess was dropped and the model
2204 /// silently got the head of the file instead of the window it asked for.
2205 #[tokio::test]
2206 async fn read_file_accepts_offset_and_limit_aliases() {
2207 let tmp = tempdir().expect("tempdir");
2208 let ctx = ToolContext::new(tmp.path().to_path_buf());
2209 let body: String = (1..=20).map(|n| format!("line {n}\n")).collect();
2210 fs::write(tmp.path().join("many.txt"), &body).expect("write");
2211
2212 let aliased = ReadFileTool
2213 .execute(json!({"path": "many.txt", "offset": 5, "limit": 3}), &ctx)
2214 .await
2215 .expect("offset/limit must be honored");
2216 let canonical = ReadFileTool
2217 .execute(
2218 json!({"path": "many.txt", "start_line": 5, "max_lines": 3}),
2219 &ctx,
2220 )
2221 .await
2222 .expect("canonical read");
2223
2224 assert_eq!(
2225 aliased.content, canonical.content,
2226 "aliases must select the same window as the canonical names"
2227 );
2228 assert!(
2229 aliased.content.contains("line 5") && !aliased.content.contains("line 1\n"),
2230 "must start at the requested offset: {}",
2231 aliased.content
2232 );
2233 }
2234
2235 /// #5209 — unknown keys on edit hard-error even when required fields are present.
2236 #[tokio::test]
2237 async fn edit_file_rejects_unexpected_parameter_names() {
2238 let tmp = tempdir().expect("tempdir");
2239 let ctx = ToolContext::new(tmp.path().to_path_buf());
2240 let path = tmp.path().join("doc.md");
2241 fs::write(&path, "hello\n").expect("write");
2242 read_before_edit(&ctx, "doc.md").await;
2243
2244 let err = EditFileTool
2245 .execute(
2246 json!({
2247 "path": "doc.md",
2248 "search": "hello",
2249 "replace": "hi",
2250 "mystery": true,
2251 }),
2252 &ctx,
2253 )
2254 .await
2255 .expect_err("unexpected params must hard-error");
2256 let msg = err.to_string();
2257 assert!(
2258 msg.contains("unexpected") && msg.contains("mystery"),
2259 "must name unexpected key: {msg}"
2260 );
2261 assert_eq!(fs::read_to_string(&path).expect("read"), "hello\n");
2262 }
2263
2264 #[test]
2265 fn edit_payload_allows_same_brace_delta_unbalanced_fragment() {
2266 // Same-delta unbalanced fragment: both sides open one more brace than
2267 // they close (typical mid-block edit).
2268 let search = " handler({\n a: 1,\n";
2269 let replace = " handler({\n a: 1,\n b: 2,\n";
2270 assert!(
2271 edit_payload_looks_corrupted(search, replace).is_none(),
2272 "same brace delta unbalanced fragment must be allowed"
2273 );
2274
2275 // Unbalanced-to-unbalanced with the same closing delta (e.g. near `});`).
2276 let search = " done();\n });\n";
2277 let replace = " done();\n cleanup();\n });\n";
2278 assert!(
2279 edit_payload_looks_corrupted(search, replace).is_none(),
2280 "unbalanced-to-unbalanced with same delta (e.g. around `}});`) must be allowed"
2281 );
2282 }
2283
2284 #[test]
2285 fn edit_payload_rejects_divergent_brace_delta() {
2286 let search = "fn f() {\n body\n}\n";
2287 let replace = "fn f() {\n body\n"; // lost closing brace
2288 let reason =
2289 edit_payload_looks_corrupted(search, replace).expect("divergent brace delta must reject");
2290 assert!(
2291 reason.contains("brace balance") || reason.contains("unbalanced"),
2292 "reason should mention brace balance: {reason}"
2293 );
2294 }
2295
2296 #[test]
2297 fn edit_payload_still_rejects_empty_bracket_collapse() {
2298 let search = r#"SendMessageOutcome::Finished {
2299 status: TurnOutcomeStatus::Interrupted,
2300 ..
2301 } => self.pause_goal_after_interruption().await,"#;
2302 let replace = "[
2303
2304 ] => {},";
2305 assert!(
2306 edit_payload_looks_corrupted(search, replace).is_some(),
2307 "empty bracket collapse must still fail closed"
2308 );
2309 }
2310
2311 #[test]
2312 fn edit_payload_still_rejects_extreme_shrinkage() {
2313 // Many nested braces in search, collapsed to a tiny stub that lost opens.
2314 let search = "fn long_match_arm() {\n".to_string()
2315 + &" if cond { statement(); }\n".repeat(20)
2316 + "}\n";
2317 let replace = "fn long_match_arm() {}\n";
2318 assert!(
2319 search.len() >= 80,
2320 "fixture must be long enough for shrinkage guard"
2321 );
2322 assert!(
2323 edit_payload_looks_corrupted(&search, replace).is_some(),
2324 "extreme shrinkage with lost braces must still fail closed"
2325 );
2326 }
2327
2328 #[tokio::test]
2329 async fn test_list_dir_tool() {
2330 let tmp = tempdir().expect("tempdir");
2331 let ctx = ToolContext::new(tmp.path().to_path_buf());
2332
2333 // Create some files and directories
2334 fs::write(tmp.path().join("file1.txt"), "").expect("write");
2335 fs::write(tmp.path().join("file2.txt"), "").expect("write");
2336 fs::create_dir(tmp.path().join("subdir")).expect("mkdir");
2337
2338 let tool = ListDirTool;
2339 let result = tool.execute(json!({}), &ctx).await.expect("execute");
2340
2341 assert!(result.success);
2342 assert!(result.content.contains("file1.txt"));
2343 assert!(result.content.contains("file2.txt"));
2344 assert!(result.content.contains("subdir"));
2345 let entries: Value = serde_json::from_str(&result.content).expect("list_dir json");
2346 assert!(entries.as_array().expect("entries").iter().any(|entry| {
2347 entry.get("name").and_then(Value::as_str) == Some("subdir")
2348 && entry.get("is_dir").and_then(Value::as_bool) == Some(true)
2349 }));
2350 }
2351
2352 #[tokio::test]
2353 async fn test_list_dir_with_path() {
2354 let tmp = tempdir().expect("tempdir");
2355 let ctx = ToolContext::new(tmp.path().to_path_buf());
2356
2357 // Create a subdirectory with files
2358 let subdir = tmp.path().join("mydir");
2359 fs::create_dir(&subdir).expect("mkdir");
2360 fs::write(subdir.join("nested.txt"), "").expect("write");
2361
2362 let tool = ListDirTool;
2363 let result = tool
2364 .execute(json!({"path": "mydir"}), &ctx)
2365 .await
2366 .expect("execute");
2367
2368 assert!(result.success);
2369 assert!(result.content.contains("nested.txt"));
2370 }
2371
2372 #[tokio::test]
2373 async fn test_list_dir_small_dir_keeps_plain_array_response() {
2374 let tmp = tempdir().expect("tempdir");
2375 let ctx = ToolContext::new(tmp.path().to_path_buf());
2376 fs::write(tmp.path().join("only.txt"), "").expect("write");
2377
2378 let tool = ListDirTool;
2379 let result = tool.execute(json!({}), &ctx).await.expect("execute");
2380
2381 let parsed: Value = serde_json::from_str(&result.content).expect("json");
2382 assert!(
2383 parsed.is_array(),
2384 "small dirs must keep the historical array shape: {parsed}"
2385 );
2386 assert_eq!(parsed.as_array().unwrap().len(), 1);
2387 }
2388
2389 #[tokio::test]
2390 async fn test_list_dir_caps_entries_with_truncation_metadata() {
2391 let tmp = tempdir().expect("tempdir");
2392 let ctx = ToolContext::new(tmp.path().to_path_buf());
2393 let extra = 7;
2394 for i in 0..LIST_DIR_MAX_ENTRIES + extra {
2395 fs::write(tmp.path().join(format!("f{i:04}.txt")), "").expect("write");
2396 }
2397
2398 let tool = ListDirTool;
2399 let result = tool.execute(json!({}), &ctx).await.expect("execute");
2400
2401 let parsed: Value = serde_json::from_str(&result.content).expect("json");
2402 assert!(parsed.is_object(), "oversized dirs return an object");
2403 assert_eq!(parsed["truncated"], json!(true));
2404 assert_eq!(
2405 parsed["listed_entries"].as_u64().unwrap() as usize,
2406 LIST_DIR_MAX_ENTRIES
2407 );
2408 assert_eq!(
2409 parsed["total_entries"].as_u64().unwrap() as usize,
2410 LIST_DIR_MAX_ENTRIES + extra
2411 );
2412 assert_eq!(
2413 parsed["entries"].as_array().unwrap().len(),
2414 LIST_DIR_MAX_ENTRIES
2415 );
2416 }
2417
2418 #[tokio::test]
2419 async fn test_list_dir_respects_cancel_token() {
2420 let tmp = tempdir().expect("tempdir");
2421 fs::write(tmp.path().join("file.txt"), "").expect("write");
2422 let cancel_token = CancellationToken::new();
2423 cancel_token.cancel();
2424 let ctx = ToolContext::new(tmp.path().to_path_buf()).with_cancel_token(cancel_token);
2425
2426 let tool = ListDirTool;
2427 let err = tool
2428 .execute(json!({}), &ctx)
2429 .await
2430 .expect_err("cancelled list_dir should return an error");
2431
2432 assert!(
2433 format!("{err:?}").contains("cancelled"),
2434 "unexpected error: {err:?}"
2435 );
2436 }
2437
2438 #[tokio::test]
2439 async fn test_list_dir_blocking_wrapper_reports_timeout() {
2440 let err = run_blocking_list_dir(Duration::from_millis(1), None, || {
2441 std::thread::sleep(Duration::from_millis(50));
2442 Ok(Value::Array(Vec::new()))
2443 })
2444 .await
2445 .expect_err("slow list_dir worker should time out");
2446
2447 assert!(
2448 matches!(err, ToolError::Timeout { seconds: 1 }),
2449 "unexpected error: {err:?}"
2450 );
2451 }
2452
2453 #[test]
2454 fn test_read_file_tool_properties() {
2455 let tool = ReadFileTool;
2456 assert_eq!(tool.name(), "read_file");
2457 assert!(tool.is_read_only());
2458 assert!(tool.is_sandboxable());
2459 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Auto);
2460 }
2461
2462 #[test]
2463 fn test_write_file_tool_properties() {
2464 let tool = WriteFileTool;
2465 assert_eq!(tool.name(), "write_file");
2466 assert!(!tool.is_read_only());
2467 assert!(tool.is_sandboxable());
2468 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Suggest);
2469 }
2470
2471 #[test]
2472 fn test_edit_file_tool_properties() {
2473 let tool = EditFileTool;
2474 assert_eq!(tool.name(), "edit_file");
2475 assert!(!tool.is_read_only());
2476 assert!(tool.is_sandboxable());
2477 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Suggest);
2478 assert!(tool.description().contains("exact search/replace"));
2479 assert!(tool.description().contains("structural"));
2480 }
2481
2482 #[test]
2483 fn test_list_dir_tool_properties() {
2484 let tool = ListDirTool;
2485 assert_eq!(tool.name(), "list_dir");
2486 assert!(tool.is_read_only());
2487 assert!(tool.is_sandboxable());
2488 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Auto);
2489 }
2490
2491 #[test]
2492 fn test_parallel_support_flags() {
2493 let read_tool = ReadFileTool;
2494 let list_tool = ListDirTool;
2495 let write_tool = WriteFileTool;
2496
2497 assert!(read_tool.supports_parallel());
2498 assert!(list_tool.supports_parallel());
2499 assert!(!write_tool.supports_parallel());
2500 }
2501
2502 #[test]
2503 fn test_input_schemas() {
2504 // Verify all tools have valid JSON schemas
2505 let read_schema = ReadFileTool.input_schema();
2506 assert!(read_schema.get("type").is_some());
2507 assert!(read_schema.get("properties").is_some());
2508
2509 let write_schema = WriteFileTool.input_schema();
2510 let required = write_schema
2511 .get("required")
2512 .and_then(|value| value.as_array())
2513 .expect("write schema should include required array");
2514 assert!(required.iter().any(|v| v.as_str() == Some("path")));
2515 assert!(required.iter().any(|v| v.as_str() == Some("content")));
2516
2517 let edit_schema = EditFileTool.input_schema();
2518 let required = edit_schema
2519 .get("required")
2520 .and_then(|value| value.as_array())
2521 .expect("edit schema should include required array");
2522 let required_fields: Vec<_> = required.iter().filter_map(|value| value.as_str()).collect();
2523 assert_eq!(required_fields, vec!["path", "search", "replace"]);
2524 assert!(!required_fields.contains(&"fuzz"));
2525 // `fuzz` was never read by `edit` — it was parsed into a discarded
2526 // binding while the schema advertised it. An unimplemented parameter has
2527 // no place in a schema the model is asked to trust.
2528 assert!(edit_schema["properties"].get("fuzz").is_none());
2529 let search_desc = edit_schema["properties"]["search"]["description"]
2530 .as_str()
2531 .expect("search description");
2532 assert!(search_desc.contains("Exact text"));
2533 assert!(search_desc.contains("whitespace"));
2534
2535 let list_schema = ListDirTool.input_schema();
2536 let required = list_schema
2537 .get("required")
2538 .and_then(|value| value.as_array())
2539 .expect("list schema should include required array");
2540 assert!(required.is_empty()); // path is optional
2541 }
2542
2543 // === Content-hash edit guards (#3979) ===
2544 //
2545 // The guard's whole value is that a stale hash stops the write *before* it
2546 // happens, so every rejection case asserts the file is byte-for-byte
2547 // unchanged — a clear error over a corrupted file is the point.
2548
2549 /// Read the hash the model would actually see, the way the model sees it:
2550 /// parsed out of the tool result's content, never out of its metadata.
2551 async fn reported_content_hash(ctx: &ToolContext, path: &str) -> String {
2552 let result = ReadFileTool
2553 .execute(json!({ "path": path }), ctx)
2554 .await
2555 .expect("read");
2556 let (_, rest) = result
2557 .content
2558 .split_once("content_hash=\"")
2559 .unwrap_or_else(|| panic!("read output carries no content_hash: {}", result.content));
2560 let (hash, _) = rest.split_once('"').expect("terminated content_hash");
2561 hash.to_string()
2562 }
2563
2564 #[tokio::test]
2565 async fn reported_hash_verifies_against_the_file_contents() {
2566 let tmp = tempdir().expect("tempdir");
2567 let ctx = ToolContext::new(tmp.path().to_path_buf());
2568 let body = "alpha\nbeta\ngamma\n";
2569 fs::write(tmp.path().join("doc.txt"), body).expect("write");
2570
2571 let reported = reported_content_hash(&ctx, "doc.txt").await;
2572 assert_eq!(reported, super::content_hash(body.as_bytes()));
2573 assert!(reported.starts_with("sha256:"), "{reported}");
2574 assert_eq!(reported.len(), "sha256:".len() + 64, "{reported}");
2575 }
2576
2577 #[tokio::test]
2578 async fn windowed_read_reports_the_whole_file_hash_not_the_window() {
2579 let tmp = tempdir().expect("tempdir");
2580 let ctx = ToolContext::new(tmp.path().to_path_buf());
2581 let body: String = (1..=40).map(|n| format!("line {n}\n")).collect();
2582 fs::write(tmp.path().join("many.txt"), &body).expect("write");
2583
2584 // A partial read must still hand back a guard for the *file*, or the
2585 // model could only ever guard edits to files it read in full.
2586 let result = ReadFileTool
2587 .execute(
2588 json!({ "path": "many.txt", "start_line": 5, "max_lines": 3 }),
2589 &ctx,
2590 )
2591 .await
2592 .expect("read");
2593 assert!(
2594 result.content.contains("shown_lines=\"5-7\""),
2595 "{}",
2596 result.content
2597 );
2598 assert!(
2599 result.content.contains(&format!(
2600 "content_hash=\"{}\"",
2601 super::content_hash(body.as_bytes())
2602 )),
2603 "{}",
2604 result.content
2605 );
2606 }
2607
2608 #[tokio::test]
2609 async fn edit_with_matching_expected_hash_proceeds() {
2610 let tmp = tempdir().expect("tempdir");
2611 let ctx = ToolContext::new(tmp.path().to_path_buf());
2612 let path = tmp.path().join("doc.txt");
2613 fs::write(&path, "alpha\nbeta\n").expect("write");
2614
2615 let hash = reported_content_hash(&ctx, "doc.txt").await;
2616 EditFileTool
2617 .execute(
2618 json!({
2619 "path": "doc.txt",
2620 "search": "alpha",
2621 "replace": "delta",
2622 "expected_hash": hash,
2623 }),
2624 &ctx,
2625 )
2626 .await
2627 .expect("matching hash must not block the edit");
2628
2629 assert_eq!(fs::read_to_string(&path).expect("read"), "delta\nbeta\n");
2630 }
2631
2632 #[tokio::test]
2633 async fn edit_with_stale_expected_hash_rejects_without_writing() {
2634 let tmp = tempdir().expect("tempdir");
2635 let ctx = ToolContext::new(tmp.path().to_path_buf());
2636 let path = tmp.path().join("doc.txt");
2637 fs::write(&path, "alpha\nbeta\n").expect("write");
2638
2639 let stale = reported_content_hash(&ctx, "doc.txt").await;
2640 // Someone else edits the file between the read and the edit.
2641 fs::write(&path, "alpha\nbeta\ngamma\n").expect("concurrent write");
2642 // Re-read so the *other* staleness gate (mtime/size) cannot be what
2643 // rejects this — the hash must be doing the work.
2644 read_before_edit(&ctx, "doc.txt").await;
2645
2646 let err = EditFileTool
2647 .execute(
2648 json!({
2649 "path": "doc.txt",
2650 "search": "alpha",
2651 "replace": "delta",
2652 "expected_hash": stale,
2653 }),
2654 &ctx,
2655 )
2656 .await
2657 .expect_err("stale hash must reject");
2658
2659 let message = err.to_string();
2660 assert!(message.contains("changed since it was read"), "{message}");
2661 assert!(
2662 message.contains("re-read") || message.contains("action=\"read\""),
2663 "{message}"
2664 );
2665 assert_eq!(
2666 fs::read_to_string(&path).expect("read"),
2667 "alpha\nbeta\ngamma\n",
2668 "a rejected edit must not modify the file"
2669 );
2670 }
2671
2672 #[tokio::test]
2673 async fn edit_without_expected_hash_is_unchanged() {
2674 let tmp = tempdir().expect("tempdir");
2675 let ctx = ToolContext::new(tmp.path().to_path_buf());
2676 let path = tmp.path().join("doc.txt");
2677 fs::write(&path, "alpha\nbeta\n").expect("write");
2678 read_before_edit(&ctx, "doc.txt").await;
2679
2680 EditFileTool
2681 .execute(
2682 json!({ "path": "doc.txt", "search": "alpha", "replace": "delta" }),
2683 &ctx,
2684 )
2685 .await
2686 .expect("absent expected_hash keeps the pre-#3979 behavior");
2687
2688 assert_eq!(fs::read_to_string(&path).expect("read"), "delta\nbeta\n");
2689 }
2690
2691 #[tokio::test]
2692 async fn write_with_stale_expected_hash_rejects_without_writing() {
2693 let tmp = tempdir().expect("tempdir");
2694 let ctx = ToolContext::new(tmp.path().to_path_buf());
2695 let path = tmp.path().join("doc.txt");
2696 fs::write(&path, "original\n").expect("write");
2697
2698 let stale = super::content_hash(b"something else entirely\n");
2699 let err = WriteFileTool
2700 .execute(
2701 json!({ "path": "doc.txt", "content": "clobbered\n", "expected_hash": stale }),
2702 &ctx,
2703 )
2704 .await
2705 .expect_err("stale hash must reject");
2706
2707 assert!(
2708 err.to_string().contains("changed since it was read"),
2709 "{err}"
2710 );
2711 assert_eq!(
2712 fs::read_to_string(&path).expect("read"),
2713 "original\n",
2714 "a rejected write must not modify the file"
2715 );
2716 }
2717
2718 #[tokio::test]
2719 async fn write_with_matching_expected_hash_proceeds() {
2720 let tmp = tempdir().expect("tempdir");
2721 let ctx = ToolContext::new(tmp.path().to_path_buf());
2722 let path = tmp.path().join("doc.txt");
2723 fs::write(&path, "original\n").expect("write");
2724
2725 let hash = reported_content_hash(&ctx, "doc.txt").await;
2726 WriteFileTool
2727 .execute(
2728 json!({ "path": "doc.txt", "content": "replaced\n", "expected_hash": hash }),
2729 &ctx,
2730 )
2731 .await
2732 .expect("matching hash must not block the write");
2733
2734 assert_eq!(fs::read_to_string(&path).expect("read"), "replaced\n");
2735 }
2736
2737 #[tokio::test]
2738 async fn write_with_expected_hash_on_a_missing_file_fails_closed() {
2739 let tmp = tempdir().expect("tempdir");
2740 let ctx = ToolContext::new(tmp.path().to_path_buf());
2741
2742 // There is no snapshot to verify, so honoring the guard is impossible.
2743 // Creating the file anyway would silently give back less safety than the
2744 // caller asked for.
2745 let err = WriteFileTool
2746 .execute(
2747 json!({
2748 "path": "new.txt",
2749 "content": "x\n",
2750 "expected_hash": super::content_hash(b"anything"),
2751 }),
2752 &ctx,
2753 )
2754 .await
2755 .expect_err("guarded write to a missing file must fail closed");
2756
2757 assert!(err.to_string().contains("does not exist"), "{err}");
2758 assert!(
2759 !tmp.path().join("new.txt").exists(),
2760 "a rejected write must not create the file"
2761 );
2762 }
2763
2764 #[tokio::test]
2765 async fn write_without_expected_hash_still_creates_files() {
2766 let tmp = tempdir().expect("tempdir");
2767 let ctx = ToolContext::new(tmp.path().to_path_buf());
2768
2769 WriteFileTool
2770 .execute(json!({ "path": "new.txt", "content": "x\n" }), &ctx)
2771 .await
2772 .expect("absent expected_hash keeps the pre-#3979 behavior");
2773
2774 assert_eq!(
2775 fs::read_to_string(tmp.path().join("new.txt")).expect("read"),
2776 "x\n"
2777 );
2778 }
2779
2780 #[tokio::test]
2781 async fn expected_hash_is_advertised_on_every_mutating_action() {
2782 for schema in [
2783 WriteFileTool.input_schema(),
2784 EditFileTool.input_schema(),
2785 crate::tools::apply_patch::ApplyPatchTool.input_schema(),
2786 ] {
2787 let description = schema["properties"]["expected_hash"]["description"]
2788 .as_str()
2789 .expect("expected_hash must be advertised");
2790 assert!(description.contains("content_hash"), "{description}");
2791 }
2792 }
2793
2794 /// S1: the in-process read tools are the *only* enforcement point for
2795 /// `read_file`/`read`/`read_media` — they call `std::fs` inside the harness
2796 /// process, so `sandbox-exec` and `bwrap` never see them. This asserts the
2797 /// refusal is an explicit permission error, not an empty result, and that it
2798 /// applies to the built-in defaults with no config required.
2799 #[test]
2800 fn read_tools_refuse_paths_under_the_default_sandbox_read_denylist() {
2801 // Take the env lock WITHOUT rebinding `HOME`. The sandbox denylist is a
2802 // process-wide `OnceLock` (sandbox/read_guard.rs:346-347, 411-416) that
2803 // snapshots the home directory the first time it is built, so pointing
2804 // `HOME` at a fixture here could never match the cached table. What this
2805 // test needs is mutual exclusion against siblings that DO rebind `HOME`,
2806 // not a home of its own.
2807 let _env_lock = crate::test_support::lock_test_env();
2808 let Some(home) = dirs::home_dir() else {
2809 // No home directory: only machine-wide rules exist and the assertion
2810 // below would be vacuous. Skip rather than pretend to have evidence.
2811 return;
2812 };
2813
2814 let error = enforce_read_denylist(&home.join(".ssh").join("id_ed25519"), "read_file")
2815 .expect_err("~/.ssh must be denied by the built-in defaults");
2816 assert!(
2817 matches!(error, ToolError::PermissionDenied { .. }),
2818 "a denied read must be an explicit refusal, never an empty or missing-file result: {error:?}"
2819 );
2820 let message = error.to_string();
2821 assert!(message.contains("read deny-list"), "{message}");
2822 assert!(
2823 message.contains("sandbox_read_denylist_exempt"),
2824 "{message}"
2825 );
2826
2827 // Ordinary source files stay readable — a coding agent must still be able
2828 // to read the user's tree, which is the whole point of the tool.
2829 let temporary = tempfile::tempdir().expect("tempdir");
2830 let source = temporary.path().join("main.rs");
2831 std::fs::write(&source, "fn main() {}\n").expect("fixture");
2832 assert!(enforce_read_denylist(&source, "read_file").is_ok());
2833 }
2834
2835 /// A symlink whose own name is innocuous but whose target is a credential
2836 /// store must be refused by the target. A deny-list a symlink walks around is
2837 /// theater, and `resolve_path` deliberately *permits* a workspace symlink that
2838 /// resolves outside the workspace.
2839 #[cfg(unix)]
2840 #[allow(clippy::await_holding_lock)]
2841 #[tokio::test]
2842 async fn read_file_refuses_a_workspace_symlink_pointing_at_a_denied_tree() {
2843 // Take the env lock WITHOUT rebinding `HOME`. The sandbox denylist is a
2844 // process-wide `OnceLock` (sandbox/read_guard.rs:346-347, 411-416) that
2845 // snapshots the home directory the first time it is built, so pointing
2846 // `HOME` at a fixture here could never match the cached table. What this
2847 // test needs is mutual exclusion against siblings that DO rebind `HOME`,
2848 // not a home of its own.
2849 let _env_lock = crate::test_support::lock_test_env();
2850 let Some(home) = dirs::home_dir() else {
2851 return;
2852 };
2853 let ssh = home.join(".ssh");
2854 if !ssh.is_dir() {
2855 // Nothing to point at; a fabricated pass here would be worse than a skip.
2856 return;
2857 }
2858
2859 let workspace = tempfile::tempdir().expect("tempdir");
2860 let link = workspace.path().join("notes.txt");
2861 std::os::unix::fs::symlink(&ssh, &link).expect("symlink");
2862
2863 let error = enforce_read_denylist(&link, "read_file")
2864 .expect_err("a symlink into ~/.ssh must be refused by its target");
2865 let message = error.to_string();
2866 assert!(message.contains("symlink"), "{message}");
2867 // The rule's *label* ("SSH keys (~/.ssh)") is named on purpose — the user
2868 // needs to know which rule to exempt. What must never appear is the
2869 // resolved absolute path, which is the location the caller was fishing for.
2870 assert!(
2871 !message.contains(&ssh.display().to_string()),
2872 "the refusal must not hand back the secret's resolved location: {message}"
2873 );
2874 }
2875
2876 /// F1: `list_dir ~/.ssh` used to hand back the key file names — enumerating a
2877 /// denied directory is a read of it, exactly what Seatbelt's
2878 /// `deny file-read*` blocks at the OS layer.
2879 #[allow(clippy::await_holding_lock)]
2880 #[tokio::test]
2881 async fn list_dir_refuses_to_enumerate_a_denied_directory() {
2882 // Take the env lock WITHOUT rebinding `HOME`. The sandbox denylist is a
2883 // process-wide `OnceLock` (sandbox/read_guard.rs:346-347, 411-416) that
2884 // snapshots the home directory the first time it is built, so pointing
2885 // `HOME` at a fixture here could never match the cached table. What this
2886 // test needs is mutual exclusion against siblings that DO rebind `HOME`,
2887 // not a home of its own.
2888 let _env_lock = crate::test_support::lock_test_env();
2889 let ctx = ToolContext::new(std::env::temp_dir());
2890
2891 // Deterministic anchor independent of the machine's home layout: the
2892 // `.env` filename rule denies any path whose file name is `.env`, so a
2893 // directory by that name is a refused listing too.
2894 let holder = tempfile::tempdir().expect("tempdir");
2895 let env_dir = holder.path().join("project");
2896 std::fs::create_dir_all(env_dir.join(".env")).expect("mkdir");
2897 let error = ListDirTool
2898 .execute(json!({ "path": env_dir.join(".env") }), &ctx)
2899 .await
2900 .expect_err("a directory named `.env` is denied by the filename rule");
2901 assert!(
2902 matches!(error, ToolError::PermissionDenied { .. }),
2903 "enumeration of a denied path must be an explicit refusal: {error:?}"
2904 );
2905
2906 let Some(home) = dirs::home_dir() else {
2907 return;
2908 };
2909 let ssh = home.join(".ssh");
2910 if !ssh.is_dir() {
2911 return;
2912 }
2913 let error = ListDirTool
2914 .execute(json!({ "path": ssh }), &ctx)
2915 .await
2916 .expect_err("`list_dir ~/.ssh` must not return the key file names");
2917 assert!(
2918 matches!(error, ToolError::PermissionDenied { .. }),
2919 "expected a permission refusal, got: {error:?}"
2920 );
2921 let message = error.to_string();
2922 assert!(message.contains("read deny-list"), "{message}");
2923 }
2924
2925 /// F2: the refusal must name the path as the caller spelled it. When a
2926 /// workspace symlink points into a denied tree, `resolve_path` hands the guard
2927 /// the secret's resolved absolute location first, and a denial raised on that
2928 /// resolved path answers the probe ("where does this link really go?") in the
2929 /// error text. The raw-spelling check runs before resolution, so it wins.
2930 #[cfg(unix)]
2931 #[allow(clippy::await_holding_lock)]
2932 #[tokio::test]
2933 async fn read_file_refusal_names_the_callers_spelling_not_the_symlink_target() {
2934 // Take the env lock WITHOUT rebinding `HOME`. The sandbox denylist is a
2935 // process-wide `OnceLock` (sandbox/read_guard.rs:346-347, 411-416) that
2936 // snapshots the home directory the first time it is built, so pointing
2937 // `HOME` at a fixture here could never match the cached table. What this
2938 // test needs is mutual exclusion against siblings that DO rebind `HOME`,
2939 // not a home of its own.
2940 let _env_lock = crate::test_support::lock_test_env();
2941 let Some(home) = dirs::home_dir() else {
2942 return;
2943 };
2944 let ssh = home.join(".ssh");
2945 if !ssh.is_dir() {
2946 return;
2947 }
2948
2949 let workspace = tempfile::tempdir().expect("tempdir");
2950 let link = workspace.path().join("notes.txt");
2951 std::os::unix::fs::symlink(&ssh, &link).expect("symlink");
2952
2953 let ctx = ToolContext::new(workspace.path().to_path_buf());
2954 let error = ReadFileTool
2955 .execute(json!({ "path": link }), &ctx)
2956 .await
2957 .expect_err("a symlink into ~/.ssh must be refused");
2958 assert!(
2959 matches!(error, ToolError::PermissionDenied { .. }),
2960 "expected a permission refusal, got: {error:?}"
2961 );
2962 let message = error.to_string();
2963 assert!(
2964 message.contains("notes.txt"),
2965 "the refusal must name the caller's spelling: {message}"
2966 );
2967 assert!(
2968 !message.contains(&ssh.display().to_string()),
2969 "the refusal must not reveal the symlink target's location: {message}"
2970 );
2971 }
2972
2973 // Reads process-global `HOME` (via `codewhale_paths::user_home`) and then resolves `~`
2974 // again through the tool, so it must hold the env lock for the whole span: any
2975 // sibling that rebinds `HOME` between those two reads makes the fixture path
2976 // stop matching the tilde path.
2977 #[allow(clippy::await_holding_lock)]
2978 #[tokio::test]
2979 async fn read_and_write_file_home_path_in_allowed_real_home_fixture() {
2980 let _env_lock = crate::test_support::lock_test_env();
2981 let home = tempfile::tempdir().expect("home tempdir");
2982 let _home = crate::test_support::EnvVarGuard::set("HOME", home.path());
2983 let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", home.path());
2984 let real_home = codewhale_paths::user_home().expect("test home must be available");
2985 let home_fixture = tempfile::Builder::new()
2986 .prefix("cw_home_tool_fixture_")
2987 .tempdir_in(&real_home)
2988 .expect("create fixture inside test home");
2989
2990 let test_file = home_fixture.path().join("home_note.txt");
2991 let rel = test_file
2992 .strip_prefix(&real_home)
2993 .expect("fixture is below test home");
2994 let tilde_path = format!("~/{}", rel.to_string_lossy());
2995
2996 let ctx = ToolContext::new(home_fixture.path().to_path_buf());
2997
2998 // 1. Write content to home-relative path
2999 let write_result = WriteFileTool
3000 .execute(
3001 json!({
3002 "path": &tilde_path,
3003 "content": "initial home content\n"
3004 }),
3005 &ctx,
3006 )
3007 .await
3008 .expect("write_file to home-relative path inside workspace should succeed");
3009 assert!(write_result.success);
3010
3011 // 2. Read content back and verify content and hash
3012 let read_result = ReadFileTool
3013 .execute(json!({ "path": &tilde_path }), &ctx)
3014 .await
3015 .expect("read_file from home-relative path should succeed");
3016 assert!(read_result.success);
3017 assert!(read_result.content.contains("initial home content\n"));
3018 let expected_hash = crate::tools::file::content_hash(b"initial home content\n");
3019 assert!(read_result.content.contains(&expected_hash));
3020
3021 // 3. Edit content with read-before-write consistency
3022 let edit_result = EditFileTool
3023 .execute(
3024 json!({
3025 "path": &tilde_path,
3026 "search": "initial home",
3027 "replace": "updated home"
3028 }),
3029 &ctx,
3030 )
3031 .await
3032 .expect("edit_file on home-relative path should succeed after read");
3033 assert!(edit_result.success);
3034
3035 // 4. Verify updated read
3036 let updated_read = ReadFileTool
3037 .execute(json!({ "path": &tilde_path }), &ctx)
3038 .await
3039 .expect("read_file after edit should succeed");
3040 assert!(updated_read.content.contains("updated home content\n"));
3041
3042 // 5. list_dir on home-relative directory
3043 let dir_rel = home_fixture.path().strip_prefix(&real_home).unwrap();
3044 let dir_tilde = format!("~/{}", dir_rel.to_string_lossy());
3045 let list_result = ListDirTool
3046 .execute(json!({ "path": &dir_tilde }), &ctx)
3047 .await
3048 .expect("list_dir on home-relative directory should succeed");
3049 assert!(list_result.success);
3050 assert!(list_result.content.contains("home_note.txt"));
3051 }
3052
3053 #[tokio::test]
3054 async fn read_file_home_path_restricted_refusal() {
3055 let workspace = tempfile::tempdir().expect("tempdir");
3056 let ctx = ToolContext::new(workspace.path().to_path_buf());
3057
3058 let error = ReadFileTool
3059 .execute(
3060 json!({ "path": "~/untrusted_outside_workspace_file_98765.txt" }),
3061 &ctx,
3062 )
3063 .await
3064 .expect_err("home path outside workspace without trust must be refused");
3065 assert!(
3066 matches!(
3067 error,
3068 ToolError::PathEscape { .. } | ToolError::ExecutionFailed { .. }
3069 ),
3070 "expected path escape or execution failed, got: {error:?}"
3071 );
3072
3073 let write_error = WriteFileTool
3074 .execute(
3075 json!({
3076 "path": "~/untrusted_outside_workspace_file_98765.txt",
3077 "content": "illegal write"
3078 }),
3079 &ctx,
3080 )
3081 .await
3082 .expect_err("write to untrusted home path must be refused");
3083 assert!(
3084 matches!(
3085 write_error,
3086 ToolError::PathEscape { .. } | ToolError::ExecutionFailed { .. }
3087 ),
3088 "expected path escape or execution failed, got: {write_error:?}"
3089 );
3090 }
3091
3092 #[allow(clippy::await_holding_lock)]
3093 #[tokio::test]
3094 async fn read_file_home_path_trusted_external_allowance() {
3095 // Take the env lock WITHOUT rebinding `HOME`. The sandbox denylist is a
3096 // process-wide `OnceLock` (sandbox/read_guard.rs:346-347, 411-416) that
3097 // snapshots the home directory the first time it is built, so pointing
3098 // `HOME` at a fixture here could never match the cached table. What this
3099 // test needs is mutual exclusion against siblings that DO rebind `HOME`,
3100 // not a home of its own.
3101 let _env_lock = crate::test_support::lock_test_env();
3102 let real_home = codewhale_paths::user_home().expect("test home must be available");
3103 let trusted_fixture = tempfile::Builder::new()
3104 .prefix("cw_home_trusted_fixture_")
3105 .tempdir_in(&real_home)
3106 .expect("create fixture inside test home");
3107
3108 let test_file = trusted_fixture.path().join("external.txt");
3109 std::fs::write(&test_file, "external trusted data\n").expect("write external");
3110 let rel = test_file
3111 .strip_prefix(&real_home)
3112 .expect("fixture is below test home");
3113 let tilde_path = format!("~/{}", rel.to_string_lossy());
3114
3115 let workspace = tempfile::tempdir().expect("tempdir");
3116 let canonical_trusted = trusted_fixture
3117 .path()
3118 .canonicalize()
3119 .unwrap_or_else(|_| trusted_fixture.path().to_path_buf());
3120 let ctx = ToolContext::new(workspace.path().to_path_buf())
3121 .with_trusted_external_paths(vec![canonical_trusted]);
3122
3123 let result = ReadFileTool
3124 .execute(json!({ "path": &tilde_path }), &ctx)
3125 .await
3126 .expect("read_file on trusted external home path should succeed");
3127 assert!(result.success);
3128 assert!(result.content.contains("external trusted data\n"));
3129 }
3130
3131 #[tokio::test]
3132 async fn read_file_literal_tilde_stays_literal() {
3133 let workspace = tempfile::tempdir().expect("tempdir");
3134 let literal_dir = workspace.path().join("~");
3135 std::fs::create_dir_all(&literal_dir).expect("create literal ~ dir");
3136 let literal_file = literal_dir.join("payload.txt");
3137 std::fs::write(&literal_file, "literal dir content").expect("write payload");
3138
3139 let ctx = ToolContext::new(workspace.path().to_path_buf());
3140 let result = ReadFileTool
3141 .execute(json!({ "path": "./~/payload.txt" }), &ctx)
3142 .await
3143 .expect("read_file on literal ./~/ path should read from workspace literal ~ directory");
3144 assert!(result.success);
3145 assert!(result.content.contains("literal dir content"));
3146 }
3147
3148 #[tokio::test]
3149 async fn read_file_no_shell_expansion() {
3150 let workspace = tempfile::tempdir().expect("tempdir");
3151 let home_var_dir = workspace.path().join("$HOME");
3152 std::fs::create_dir_all(&home_var_dir).expect("create literal $HOME dir");
3153 let var_file = home_var_dir.join("shell.txt");
3154 std::fs::write(&var_file, "literal $HOME file").expect("write var file");
3155
3156 let ctx = ToolContext::new(workspace.path().to_path_buf());
3157 let result = ReadFileTool
3158 .execute(json!({ "path": "$HOME/shell.txt" }), &ctx)
3159 .await
3160 .expect("read_file on $HOME/file should read from workspace literal $HOME directory without expanding env vars");
3161 assert!(result.success);
3162 assert!(result.content.contains("literal $HOME file"));
3163 }
3164
3165 // Seals `HOME` to a fixture: this test used to resolve `~` against the
3166 // developer's real home, so a sibling test setting `CODEWHALE_HOME` between the
3167 // tilde expansion and the guard's own lookup could flip it to a pass — and the
3168 // failure printed the developer's actual config file, credentials included.
3169 #[allow(clippy::await_holding_lock)]
3170 #[tokio::test]
3171 async fn read_file_denies_home_credential_path() {
3172 let _env_lock = crate::test_support::lock_test_env();
3173 let home = tempfile::tempdir().expect("home tempdir");
3174 let _home = crate::test_support::EnvVarGuard::set("HOME", home.path());
3175 let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", home.path());
3176 let _codewhale_home = crate::test_support::EnvVarGuard::remove("CODEWHALE_HOME");
3177 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
3178 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
3179 fs::create_dir_all(home.path().join(".codewhale")).expect("create fixture home");
3180 fs::write(
3181 home.path().join(".codewhale").join("config.toml"),
3182 "api_key = \"fixture-secret\"\n",
3183 )
3184 .expect("write fixture config");
3185
3186 let workspace = tempfile::tempdir().expect("tempdir");
3187 // Even in trust mode, credential paths must be blocked
3188 let ctx = ToolContext::new(workspace.path().to_path_buf()).with_trust_mode(true);
3189
3190 let error = ReadFileTool
3191 .execute(json!({ "path": "~/.codewhale/config.toml" }), &ctx)
3192 .await
3193 .expect_err("reading ~/.codewhale/config.toml must be denied");
3194 assert!(
3195 matches!(error, ToolError::PermissionDenied { .. }),
3196 "expected permission denied, got: {error:?}"
3197 );
3198 let message = error.to_string();
3199 assert!(
3200 message.contains("cannot expose Codewhale configuration or credential-store files"),
3201 "error message must protect credentials: {message}"
3202 );
3203 }
3204
3205 /// `CODEWHALE_HOME` relocates the runtime home. It must not un-guard the user's
3206 /// real `~/.codewhale/config.toml`: the guard derived every root from
3207 /// `codewhale_home()`, which returns the override when set, so pointing that
3208 /// variable anywhere else left the ambient config (OAuth tokens included)
3209 /// readable in trust mode. `sandbox::read_guard` only covers
3210 /// `~/.codewhale/secrets`, so nothing else was denying this file.
3211 #[allow(clippy::await_holding_lock)]
3212 #[tokio::test]
3213 async fn read_file_denies_ambient_home_config_even_when_codewhale_home_is_relocated() {
3214 let _env_lock = crate::test_support::lock_test_env();
3215 let home = tempfile::tempdir().expect("home tempdir");
3216 let relocated = tempfile::tempdir().expect("relocated home tempdir");
3217 let _home = crate::test_support::EnvVarGuard::set("HOME", home.path());
3218 let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", home.path());
3219 // The override points somewhere else entirely — the ambient store must stay guarded.
3220 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", relocated.path());
3221 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
3222 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
3223
3224 let ambient = home.path().join(".codewhale");
3225 fs::create_dir_all(&ambient).expect("create ambient home");
3226 fs::write(
3227 ambient.join("config.toml"),
3228 "[providers.openai]\napi_key = \"sk-ambient-must-not-leak\"\n",
3229 )
3230 .expect("write ambient config");
3231 fs::write(
3232 ambient.join("config.toml.bak"),
3233 "[providers.openai]\napi_key = \"sk-ambient-backup-must-not-leak\"\n",
3234 )
3235 .expect("write ambient config backup");
3236
3237 let workspace = tempfile::tempdir().expect("tempdir");
3238 let ctx = ToolContext::new(workspace.path().to_path_buf()).with_trust_mode(true);
3239
3240 for name in ["config.toml", "config.toml.bak"] {
3241 let target = ambient.join(name);
3242 let error = ReadFileTool
3243 .execute(json!({ "path": target.to_string_lossy() }), &ctx)
3244 .await
3245 .err()
3246 .unwrap_or_else(|| {
3247 panic!("reading the ambient {name} must be denied despite CODEWHALE_HOME")
3248 });
3249 assert!(
3250 matches!(error, ToolError::PermissionDenied { .. }),
3251 "expected permission denied for {name}, got: {error:?}"
3252 );
3253 assert!(
3254 !error.to_string().contains("must-not-leak"),
3255 "the denial must not echo credential content for {name}"
3256 );
3257 }
3258 }
3259
3260 #[cfg(unix)]
3261 #[allow(clippy::await_holding_lock)]
3262 #[tokio::test]
3263 async fn read_file_refusal_names_home_spelling_not_denied_symlink_target() {
3264 // Take the env lock WITHOUT rebinding `HOME`. The sandbox denylist is a
3265 // process-wide `OnceLock` (sandbox/read_guard.rs:346-347, 411-416) that
3266 // snapshots the home directory the first time it is built, so pointing
3267 // `HOME` at a fixture here could never match the cached table. What this
3268 // test needs is mutual exclusion against siblings that DO rebind `HOME`,
3269 // not a home of its own.
3270 let _env_lock = crate::test_support::lock_test_env();
3271 let real_home = codewhale_paths::user_home().expect("test home must be available");
3272 let home_fixture = tempfile::Builder::new()
3273 .prefix("cw_home_symlink_fixture_")
3274 .tempdir_in(&real_home)
3275 .expect("create fixture inside test home");
3276
3277 let denied_file = home_fixture.path().join(".env");
3278 std::fs::write(&denied_file, "SYNTHETIC_FIXTURE=not-a-secret").expect("create denied fixture");
3279 let link = home_fixture.path().join("ssh_probe");
3280 std::os::unix::fs::symlink(&denied_file, &link).expect("symlink to denied file");
3281
3282 let rel = link
3283 .strip_prefix(&real_home)
3284 .expect("fixture is below test home");
3285 let tilde_path = format!("~/{}", rel.to_string_lossy());
3286
3287 let ctx = ToolContext::new(home_fixture.path().to_path_buf());
3288 let error = ReadFileTool
3289 .execute(json!({ "path": &tilde_path }), &ctx)
3290 .await
3291 .expect_err("symlink pointing to a denied file must be refused");
3292 assert!(
3293 matches!(error, ToolError::PermissionDenied { .. }),
3294 "expected permission refusal, got: {error:?}"
3295 );
3296 let message = error.to_string();
3297 assert!(
3298 message.contains(&tilde_path),
3299 "refusal message must name caller's tilde path ({tilde_path}): {message}"
3300 );
3301 assert!(
3302 !message.contains(&denied_file.display().to_string()),
3303 "refusal message must NOT leak target path ({}): {message}",
3304 denied_file.display()
3305 );
3306 }
3307
3308 #[cfg(unix)]
3309 #[tokio::test]
3310 async fn write_file_refuses_symlinks_to_git_hooks_and_strict_trust_escape() {
3311 let workspace_dir = tempfile::tempdir().expect("workspace");
3312 let outside_dir = tempfile::tempdir().expect("outside");
3313 let workspace = workspace_dir.path().canonicalize().expect("canonical ws");
3314 let hooks_dir = workspace.join(".git/hooks");
3315 fs::create_dir_all(&hooks_dir).expect("hooks dir");
3316 fs::create_dir_all(workspace.join("notes")).expect("notes dir");
3317 let hook = hooks_dir.join("pre-commit");
3318 fs::write(&hook, "clean-hook\n").expect("write hook");
3319 let outside_target = outside_dir.path().join("outside.txt");
3320 fs::write(&outside_target, "clean-outside\n").expect("write outside");
3321
3322 let link_leaf = workspace.join("notes/hook_link");
3323 std::os::unix::fs::symlink(&hook, &link_leaf).expect("symlink leaf");
3324 let link_dir = workspace.join("linked_hooks");
3325 std::os::unix::fs::symlink(&hooks_dir, &link_dir).expect("symlink dir");
3326 let hardlink_leaf = workspace.join("notes/hook_hard");
3327 fs::hard_link(&hook, &hardlink_leaf).expect("hard link leaf");
3328
3329 let ctx = ToolContext::new(&workspace);
3330 for bad in [
3331 "notes/hook_link",
3332 "linked_hooks/new-hook",
3333 "notes/hook_hard",
3334 ] {
3335 let err = WriteFileTool
3336 .execute(json!({"path": bad, "content": "pwned\n"}), &ctx)
3337 .await
3338 .expect_err(bad);
3339 assert!(
3340 matches!(err, ToolError::PermissionDenied { .. }),
3341 "expected permission denied for {bad}, got {err:?}"
3342 );
3343 let contract_err =
3344 WriteFileTool::execute_contract_write(json!({"path": bad, "content": "pwned\n"}), &ctx)
3345 .await
3346 .expect_err(bad);
3347 assert!(
3348 matches!(contract_err, ToolError::PermissionDenied { .. }),
3349 "expected contract permission denied for {bad}, got {contract_err:?}"
3350 );
3351 }
3352
3353 let mut strict_trusted = ToolContext::with_options(&workspace, true);
3354 strict_trusted.execution.follow_symlinks = true;
3355 strict_trusted
3356 .execution
3357 .trusted_external_paths
3358 .push(outside_dir.path().to_path_buf());
3359 strict_trusted.execution.strict_workspace_confinement = true;
3360
3361 let escape_link = workspace.join("notes/escape_link");
3362 std::os::unix::fs::symlink(&outside_target, &escape_link).expect("escape symlink");
3363 let escape_dir = workspace.join("escape_dir");
3364 std::os::unix::fs::symlink(outside_dir.path(), &escape_dir).expect("escape dir");
3365
3366 for escaped in [
3367 "notes/escape_link",
3368 "escape_dir/created.txt",
3369 outside_target.to_str().expect("utf8 outside"),
3370 ] {
3371 let err = WriteFileTool
3372 .execute(
3373 json!({"path": escaped, "content": "pwned\n"}),
3374 &strict_trusted,
3375 )
3376 .await
3377 .expect_err(escaped);
3378 assert!(
3379 matches!(
3380 err,
3381 ToolError::PermissionDenied { .. } | ToolError::PathEscape { .. }
3382 ),
3383 "strict confinement must fail closed for {escaped}, got {err:?}"
3384 );
3385 }
3386
3387 assert_eq!(
3388 fs::read_to_string(&hook).expect("read hook"),
3389 "clean-hook\n"
3390 );
3391 assert!(!hooks_dir.join("new-hook").exists());
3392 assert_eq!(
3393 fs::read_to_string(&outside_target).expect("read outside"),
3394 "clean-outside\n"
3395 );
3396 assert!(!outside_dir.path().join("created.txt").exists());
3397 }
3398
3398 lines RUST