返回 CodeWhale
tests.rs
根目录 / crates / engine / src / tools / file / tests.rs
1 use super::*;
2 use serde_json::json;
3 use std::time::Duration;
4
5 #[tokio::test]
6 async fn missing_pdf_path_precedes_unavailable_helper() {
7 let temporary = tempfile::tempdir().expect("tempdir");
8 let missing = temporary.path().join("definitely-not-pdftotext");
9 let context = ToolContext::new(temporary.path());
10 let error = ReadFileTool::execute_legacy_read_with_pdf(
11 json!({"path": "missing.pdf"}),
12 &context,
13 super::super::pdf::PdfTextCommand::test(missing.as_os_str(), Duration::from_secs(1), None),
14 )
15 .await
16 .expect_err("missing path must fail before the missing helper is launched");
17
18 match error {
19 ToolError::ExecutionFailed { message, .. } => {
20 assert!(message.contains("Failed to read"), "{message}");
21 assert!(message.contains("missing.pdf"), "{message}");
22 }
23 other => panic!("expected ordinary read failure, got {other:?}"),
24 }
25 }
26
27 #[tokio::test]
28 async fn read_file_missing_pdftotext_is_a_failed_typed_outcome() {
29 let temporary = tempfile::tempdir().expect("tempdir");
30 let missing = temporary.path().join("definitely-not-pdftotext");
31
32 let error = read_pdf_bytes_with_command(
33 b"%PDF-1.7\n%%EOF",
34 None,
35 super::super::pdf::PdfTextCommand::test(missing.as_os_str(), Duration::from_secs(1), None),
36 )
37 .await
38 .expect_err("missing helper must fail the tool call");
39 let payload = match &error {
40 ToolError::NotAvailable { message } => {
41 serde_json::from_str::<Value>(message).expect("structured unavailable payload")
42 }
43 other => panic!("unexpected error: {other:?}"),
44 };
45 assert_eq!(payload["type"], "binary_unavailable");
46 assert_eq!(
47 crate::tools::spec::ToolExecutionOutcome::from_legacy(Err(error)).status,
48 crate::tools::spec::ToolTerminalStatus::Failed
49 );
50 }
51
52 /// An omitted limit reads the first READ_LIMIT_LINES lines even
53 /// when the byte cap is barely touched; continuation is by line offset.
54 #[tokio::test]
55 async fn contract_read_defaults_to_the_line_limit() {
56 let _workshop_guard = codewhale_runtime::active_workshop::active_workshop_test_guard();
57 let lines = (0..5_000)
58 .map(|index| format!("line-{index}"))
59 .collect::<Vec<_>>();
60 let content = lines.join("\n") + "\n";
61 assert!(
62 content.len() < READ_DEFAULT_MAX_BYTES,
63 "fixture fits the byte cap"
64 );
65
66 let temporary = tempfile::tempdir().expect("tempdir");
67 std::fs::write(temporary.path().join("many.txt"), &content).expect("fixture");
68 let context = ToolContext::new(temporary.path());
69 let result = ReadFileTool::execute_contract_read(json!({"path": "many.txt"}), &context)
70 .await
71 .expect("read result");
72 let expected_numbered = lines[..2_000]
73 .iter()
74 .enumerate()
75 .map(|(index, line)| format!("{}: {line}", index + 1))
76 .collect::<Vec<_>>()
77 .join("\n");
78 assert_eq!(
79 result.content,
80 format!(
81 "[lines 1-2000 of 5000 | {} bytes | truncated=true]\n{}\n\n[Showing lines 1-2000 of 5000. Continue with offset=2001.]",
82 content.len(),
83 expected_numbered
84 )
85 );
86 let metadata = result.metadata.clone().expect("paging metadata");
87 assert_eq!(metadata["truncated"], true);
88 assert_eq!(metadata["line_count"], 5_000);
89 }
90
91 #[tokio::test]
92 async fn contract_read_returns_an_ordinary_source_file_whole_without_a_footer() {
93 let temporary = tempfile::tempdir().expect("tempdir");
94 let content = "fn main() {\n println!(\"hi\");\n}\n";
95 std::fs::write(temporary.path().join("main.rs"), content).expect("fixture");
96 let context = ToolContext::new(temporary.path());
97 let result = ReadFileTool::execute_contract_read(json!({"path": "main.rs"}), &context)
98 .await
99 .expect("read result");
100 assert_eq!(
101 result.content,
102 format!(
103 "[lines 1-3 of 3 | {} bytes | truncated=false]\n1: fn main() {{\n2: println!(\"hi\");\n3: }}",
104 content.len()
105 )
106 );
107 }
108
109 #[test]
110 fn contract_read_truncates_long_lines_at_a_char_boundary() {
111 let first = "é".repeat(30_000);
112 let second = "z".repeat(60_000);
113 let window = contract_read_window(
114 &format!("{first}\n{second}"),
115 1,
116 2,
117 true,
118 READ_DEFAULT_MAX_BYTES,
119 );
120 assert!(window.line_truncated);
121 assert!(!window.truncated_by_bytes);
122 assert_eq!(
123 window.content,
124 format!(
125 "1: {}... [line truncated at 2000 chars]\n2: {}... [line truncated at 2000 chars]",
126 "é".repeat(2_000),
127 "z".repeat(2_000)
128 )
129 );
130 assert!(std::str::from_utf8(window.content.as_bytes()).is_ok());
131 }
132
133 #[test]
134 fn read_byte_cap_is_workshop_then_default() {
135 let _workshop_guard = codewhale_runtime::active_workshop::active_workshop_test_guard();
136
137 codewhale_runtime::active_workshop::install_active_workshop(None);
138 assert_eq!(effective_read_max_bytes(), READ_DEFAULT_MAX_BYTES);
139
140 codewhale_runtime::active_workshop::install_active_workshop(Some(
141 &codewhale_config::WorkshopConfig {
142 read_result_max_bytes: Some(700_000),
143 ..Default::default()
144 },
145 ));
146 assert_eq!(effective_read_max_bytes(), 700_000);
147 // The workshop override keeps the 2 MiB absolute ceiling.
148 codewhale_runtime::active_workshop::install_active_workshop(Some(
149 &codewhale_config::WorkshopConfig {
150 read_result_max_bytes: Some(READ_RESULT_ABSOLUTE_MAX_BYTES * 4),
151 ..Default::default()
152 },
153 ));
154 assert_eq!(effective_read_max_bytes(), READ_RESULT_ABSOLUTE_MAX_BYTES);
155 codewhale_runtime::active_workshop::install_active_workshop(None);
156 }
157
158 #[tokio::test]
159 async fn contract_read_has_no_model_byte_budget_knob() {
160 let _workshop_guard = codewhale_runtime::active_workshop::active_workshop_test_guard();
161 let temporary = tempfile::tempdir().expect("tempdir");
162 let line = "y".repeat(199);
163 let content = std::iter::repeat_n(line.as_str(), 1_500)
164 .collect::<Vec<_>>()
165 .join("\n");
166 assert!(content.len() > READ_DEFAULT_MAX_BYTES);
167 std::fs::write(temporary.path().join("wide.txt"), &content).expect("fixture");
168 let context = ToolContext::new(temporary.path());
169
170 let capped = ReadFileTool::execute_contract_read(json!({"path": "wide.txt"}), &context)
171 .await
172 .expect("default read");
173 assert!(
174 capped.content.starts_with(&format!(
175 "[lines 1-250 of 1500 | {} bytes | truncated=true]\n1: ",
176 content.len()
177 )),
178 "{}",
179 capped.content
180 );
181 assert!(
182 capped.content.contains(
183 "[Showing lines 1-250 of 1500; output cap reached. Continue with offset=251.]"
184 ),
185 "{}",
186 capped.content
187 );
188
189 // The model cannot raise the cap: `max_bytes` is not a read parameter.
190 let refused = ReadFileTool::execute_contract_read(
191 json!({"path": "wide.txt", "max_bytes": 400_000}),
192 &context,
193 )
194 .await;
195 assert!(refused.is_err(), "max_bytes must be refused: {refused:?}");
196 }
197
198 #[tokio::test]
199 async fn contract_read_paginates_an_oversized_file_with_an_honest_budget_footer() {
200 let _workshop_guard = codewhale_runtime::active_workshop::active_workshop_test_guard();
201 let temporary = tempfile::tempdir().expect("tempdir");
202 let line = "z".repeat(999);
203 let content = std::iter::repeat_n(line.as_str(), 2_000)
204 .collect::<Vec<_>>()
205 .join("\n");
206 std::fs::write(temporary.path().join("big.txt"), &content).expect("fixture");
207 let context = ToolContext::new(temporary.path());
208
209 let first = ReadFileTool::execute_contract_read(json!({"path": "big.txt"}), &context)
210 .await
211 .expect("first page");
212 let footer = first
213 .content
214 .rsplit_once("\n\n")
215 .expect("footer present")
216 .1
217 .to_string();
218 assert_eq!(
219 footer,
220 "[Showing lines 1-51 of 2000; output cap reached. Continue with offset=52.]"
221 );
222 let body_with_header = first.content.rsplit_once("\n\n").expect("body").0;
223 let (header, shown) = body_with_header.split_once('\n').expect("header line");
224 assert_eq!(
225 header,
226 format!(
227 "[lines 1-51 of 2000 | {} bytes | truncated=true]",
228 content.len()
229 )
230 );
231 assert_eq!(shown.lines().count(), 51);
232
233 // The named continuation offset is exact: page two starts on line 52.
234 let second =
235 ReadFileTool::execute_contract_read(json!({"path": "big.txt", "offset": 52}), &context)
236 .await
237 .expect("second page");
238 assert!(
239 second.content.starts_with(&format!(
240 "[lines 52-101 of 2000 | {} bytes | truncated=true]\n52: {line}",
241 content.len()
242 )),
243 "second page starts at the named offset"
244 );
245 assert!(
246 second.content.contains("Continue with offset=102"),
247 "{}",
248 second.content
249 );
250 }
251
252 /// #6283 AC1: a >10 MiB file read without paging params returns page one
253 /// plus the file's size, line count, and truncated flag — never the whole
254 /// file.
255 #[tokio::test]
256 async fn contract_read_reports_size_and_truncation_for_huge_files() {
257 let _workshop_guard = codewhale_runtime::active_workshop::active_workshop_test_guard();
258 let temporary = tempfile::tempdir().expect("tempdir");
259 let line = "x".repeat(99);
260 let content = std::iter::repeat_n(line.as_str(), 110_000)
261 .collect::<Vec<_>>()
262 .join("\n");
263 assert!(
264 content.len() > 10 * 1024 * 1024,
265 "fixture exceeds 10 MiB: {}",
266 content.len()
267 );
268 std::fs::write(temporary.path().join("huge.bin.txt"), &content).expect("fixture");
269 let context = ToolContext::new(temporary.path());
270
271 let first = ReadFileTool::execute_contract_read(json!({"path": "huge.bin.txt"}), &context)
272 .await
273 .expect("first page");
274 let metadata = first.metadata.clone().expect("paging metadata");
275 assert_eq!(metadata["size"], content.len() as u64);
276 assert_eq!(metadata["truncated"], true);
277 assert_eq!(metadata["line_count"], 110_000);
278 assert!(
279 first.content.len() < content.len(),
280 "page one must never be the whole file"
281 );
282 assert!(
283 first.content.len() <= READ_DEFAULT_MAX_BYTES + 1_024,
284 "page one stays within the default budget plus footer slack: {}",
285 first.content.len()
286 );
287 assert!(
288 first.content.contains("output cap reached")
289 && first.content.contains("Continue with offset="),
290 "footer names the cap and the continuation: {}",
291 first
292 .content
293 .rsplit_once("\n\n")
294 .map(|(_, f)| f)
295 .unwrap_or("")
296 );
297 }
298
299 /// #6283 AC2: paging through a file keeps every response bounded and
300 /// terminates with an untruncated page whose union is the whole file.
301 #[tokio::test]
302 async fn contract_read_pages_stay_bounded_and_cover_the_whole_file() {
303 let _workshop_guard = codewhale_runtime::active_workshop::active_workshop_test_guard();
304 let temporary = tempfile::tempdir().expect("tempdir");
305 let content = (0..3_000)
306 .map(|index| format!("paged-line-{index:05}"))
307 .collect::<Vec<_>>()
308 .join("\n");
309 std::fs::write(temporary.path().join("paged.txt"), &content).expect("fixture");
310 let context = ToolContext::new(temporary.path());
311
312 let mut seen: Vec<String> = Vec::new();
313 let mut offset = 1usize;
314 for page in 0..100 {
315 let result = ReadFileTool::execute_contract_read(
316 json!({"path": "paged.txt", "offset": offset, "limit": 500}),
317 &context,
318 )
319 .await
320 .expect("page read");
321 let metadata = result.metadata.clone().expect("paging metadata");
322 assert_eq!(metadata["size"], content.len() as u64);
323 assert!(
324 result.content.len() <= READ_DEFAULT_MAX_BYTES + 1_024,
325 "page {page} bounded: {}",
326 result.content.len()
327 );
328 let body_with_header = result
329 .content
330 .rsplit_once("\n\n[")
331 .map(|(body, _)| body)
332 .unwrap_or(&result.content);
333 let (_, body) = body_with_header.split_once('\n').expect("header line");
334 for (idx, line) in body.lines().enumerate() {
335 let expected_prefix = format!("{}: ", offset + idx);
336 let stripped = line
337 .strip_prefix(&expected_prefix)
338 .unwrap_or_else(|| panic!("expected prefix {expected_prefix:?}, got {line:?}"));
339 seen.push(stripped.to_string());
340 }
341 let truncated = metadata["truncated"].as_bool().expect("truncated flag");
342 if !truncated {
343 break;
344 }
345 offset += 500;
346 assert!(page < 99, "paging must terminate");
347 }
348 assert_eq!(seen.len(), 3_000);
349 assert_eq!(seen.join("\n"), content);
350 }
351
352 /// #6283: ordinary whole reads carry the same paging metadata (with
353 /// truncated=false) and keep their footer-free shape.
354 #[tokio::test]
355 async fn contract_read_metadata_for_ordinary_whole_read() {
356 let temporary = tempfile::tempdir().expect("tempdir");
357 let content = "alpha\nbeta\ngamma\n";
358 std::fs::write(temporary.path().join("small.txt"), content).expect("fixture");
359 let context = ToolContext::new(temporary.path());
360
361 let result = ReadFileTool::execute_contract_read(json!({"path": "small.txt"}), &context)
362 .await
363 .expect("read result");
364 assert_eq!(
365 result.content,
366 format!(
367 "[lines 1-3 of 3 | {} bytes | truncated=false]\n1: alpha\n2: beta\n3: gamma",
368 content.len()
369 )
370 );
371 let metadata = result.metadata.clone().expect("paging metadata");
372 assert_eq!(metadata["size"], content.len() as u64);
373 assert_eq!(metadata["truncated"], false);
374 assert_eq!(metadata["line_count"], 3);
375 }
376
377 /// #6283 AC3: grep-then-read flow — locate a marker with `grep_files`,
378 /// then read exactly that line range. (`grep_files` in the child surface
379 /// is pinned by `an_explicit_parent_tool_scope_is_enforced_by_the_child_registry`.)
380 #[tokio::test]
381 async fn grep_then_read_flow_targets_matched_lines() {
382 use crate::tools::spec::ToolSpec;
383
384 let temporary = tempfile::tempdir().expect("tempdir");
385 let mut lines: Vec<String> = (0..200)
386 .map(|index| format!("filler line {index}"))
387 .collect();
388 lines[150] = "the needle marker lives here".to_string();
389 std::fs::write(temporary.path().join("haystack.txt"), lines.join("\n")).expect("fixture");
390 let context = ToolContext::new(temporary.path());
391
392 let grep = crate::tools::search::GrepFilesTool
393 .execute(
394 json!({"pattern": "needle marker", "path": ".", "context_lines": 1}),
395 &context,
396 )
397 .await
398 .expect("grep result");
399 let payload: serde_json::Value =
400 serde_json::from_str(&grep.content).expect("grep JSON envelope");
401 assert_eq!(payload["total_matches"], 1);
402 let matched = &payload["matches"][0];
403 assert_eq!(matched["line_number"], 151);
404
405 let read = ReadFileTool::execute_contract_read(
406 json!({
407 "path": matched["file"].as_str().expect("match file"),
408 "offset": matched["line_number"].as_u64().expect("match line"),
409 "limit": 1,
410 }),
411 &context,
412 )
413 .await
414 .expect("targeted read");
415 assert!(
416 read.content.contains("the needle marker lives here"),
417 "{}",
418 read.content
419 );
420 }
421
422 #[tokio::test]
423 async fn contract_read_truncates_a_huge_first_line_with_a_marker() {
424 let _workshop_guard = codewhale_runtime::active_workshop::active_workshop_test_guard();
425 let temporary = tempfile::tempdir().expect("tempdir");
426 let size = READ_DEFAULT_MAX_BYTES + 1;
427 std::fs::write(temporary.path().join("huge.txt"), "x".repeat(size)).expect("fixture");
428 let context = ToolContext::new(temporary.path());
429 let result = ReadFileTool::execute_contract_read(json!({"path": "huge.txt"}), &context)
430 .await
431 .expect("read result");
432 assert_eq!(
433 result.content,
434 format!(
435 "[lines 1-1 of 1 | {size} bytes | truncated=true]\n1: {}... [line truncated at 2000 chars]",
436 "x".repeat(READ_MAX_LINE_CHARS)
437 )
438 );
439 }
440
441 #[tokio::test]
442 async fn contract_read_offset_oob_and_limit_continuation_match_contract() {
443 let temporary = tempfile::tempdir().expect("tempdir");
444 std::fs::write(temporary.path().join("lines.txt"), "one\ntwo\nthree").expect("fixture");
445 let context = ToolContext::new(temporary.path());
446
447 let limited = ReadFileTool::execute_contract_read(
448 json!({"path": "lines.txt", "offset": 2, "limit": 1}),
449 &context,
450 )
451 .await
452 .expect("limited read");
453 assert_eq!(
454 limited.content,
455 "[lines 2-2 of 3 | 13 bytes | truncated=true]\n2: two\n\n[Showing lines 2-2 of 3. Continue with offset=3.]"
456 );
457
458 let error =
459 ReadFileTool::execute_contract_read(json!({"path": "lines.txt", "offset": 4}), &context)
460 .await
461 .expect_err("offset beyond EOF");
462 assert_eq!(
463 error.to_string(),
464 "Failed to execute tool: Offset 4 is beyond end of file (3 lines total)"
465 );
466 }
467
468 /// Regression: grok-4.7 serializes every JSON number as a float, so its
469 /// ranged reads arrive as `{"offset": 2.0, "limit": 1.0}`. Those used to
470 /// fail with "offset must be a non-negative integer" on every call.
471 #[tokio::test]
472 async fn contract_read_accepts_whole_number_floats_and_still_refuses_fractions() {
473 let temporary = tempfile::tempdir().expect("tempdir");
474 std::fs::write(temporary.path().join("lines.txt"), "one\ntwo\nthree").expect("fixture");
475 let context = ToolContext::new(temporary.path());
476
477 let ranged = ReadFileTool::execute_contract_read(
478 json!({"path": "lines.txt", "offset": 2.0, "limit": 1.0}),
479 &context,
480 )
481 .await
482 .expect("float-typed ranged read");
483 assert_eq!(
484 ranged.content,
485 "[lines 2-2 of 3 | 13 bytes | truncated=true]\n2: two\n\n[Showing lines 2-2 of 3. Continue with offset=3.]"
486 );
487
488 for (key, bad) in [
489 ("offset", json!(-1.0)),
490 ("offset", json!(2.5)),
491 ("limit", json!("2")),
492 ("limit", json!([2])),
493 ] {
494 let error =
495 ReadFileTool::execute_contract_read(json!({"path": "lines.txt", key: bad}), &context)
496 .await
497 .expect_err("non-integer must be refused");
498 assert!(
499 error
500 .to_string()
501 .contains(&format!("{key} must be a non-negative integer")),
502 "{error}"
503 );
504 }
505 }
506
507 #[tokio::test]
508 async fn contract_read_uses_magic_not_extension_for_images() {
509 let temporary = tempfile::tempdir().expect("tempdir");
510 std::fs::write(temporary.path().join("plain.png"), "ordinary text").expect("text fixture");
511 std::fs::write(
512 temporary.path().join("renamed.data"),
513 crate::image_attach::test_support::PNG_1X1,
514 )
515 .expect("image fixture");
516 std::fs::write(
517 temporary.path().join("truncated.png"),
518 [b"\x89PNG\r\n\x1a\n".as_slice(), b"\0\0\0\rIHDR".as_slice()].concat(),
519 )
520 .expect("truncated image fixture");
521 let context = ToolContext::new(temporary.path());
522
523 let text = ReadFileTool::execute_contract_read(json!({"path": "plain.png"}), &context)
524 .await
525 .expect("fake extension remains text");
526 assert_eq!(
527 text.content,
528 "[lines 1-1 of 1 | 13 bytes | truncated=false]\n1: ordinary text"
529 );
530 let image = ReadFileTool::execute_contract_read(json!({"path": "renamed.data"}), &context)
531 .await
532 .expect("real image uses typed transport");
533 assert_eq!(image.content_blocks.len(), 1);
534 assert!(matches!(
535 &image.content_blocks[0],
536 codewhale_tools::ToolResultContentBlock::Image { mime_type, .. }
537 if mime_type == "image/png"
538 ));
539 let truncated = ReadFileTool::execute_contract_read(json!({"path": "truncated.png"}), &context)
540 .await
541 .expect("invalid image retains an omission receipt");
542 assert!(truncated.content_blocks.is_empty());
543 assert!(truncated.content.contains("Image omitted"));
544 }
545
546 #[test]
547 fn contract_edit_preparation_accepts_string_and_legacy_recovery_forms() {
548 let encoded = prepare_contract_edit_input(json!({
549 "path": "doc.txt",
550 "edits": "[{\"oldText\":\"a\",\"newText\":\"b\"}]"
551 }))
552 .expect("encoded edits");
553 assert_eq!(encoded["edits"][0], json!({"oldText": "a", "newText": "b"}));
554
555 let recovered = prepare_contract_edit_input(json!({
556 "path": "doc.txt",
557 "edits": {"malformed": true},
558 "oldText": "a",
559 "newText": "b"
560 }))
561 .expect("legacy recovery");
562 assert_eq!(
563 recovered["edits"],
564 json!([{"oldText": "a", "newText": "b"}])
565 );
566 assert!(recovered.get("oldText").is_none());
567 assert!(recovered.get("newText").is_none());
568 }
569
570 #[test]
571 fn contract_edit_fuzzy_normalization_preserves_untouched_lines() {
572 let original = "untouched line \nShe said “hello”—today. \ntail \n";
573 let updated = apply_contract_edits(
574 original,
575 &[ContractEdit {
576 index: 0,
577 old_text: "She said \"hello\"-today.".to_string(),
578 new_text: "She said hello.".to_string(),
579 }],
580 "doc.txt",
581 false,
582 )
583 .expect("fuzzy edit");
584 assert_eq!(updated, "untouched line \nShe said hello.\ntail \n");
585 }
586
587 #[test]
588 fn contract_edit_fuzzy_match_keeps_the_rest_of_the_touched_line() {
589 let original = "PRICE = \"价格:100元(含税)\" # “促销”\n";
590 let updated = apply_contract_edits(
591 original,
592 &[ContractEdit {
593 index: 0,
594 old_text: "# \"促销\"".to_string(),
595 new_text: "# \"特价\"".to_string(),
596 }],
597 "notes.py",
598 false,
599 )
600 .expect("fuzzy edit");
601 assert_eq!(updated, "PRICE = \"价格:100元(含税)\" # \"特价\"\n");
602 }
603
604 #[test]
605 fn contract_edit_fuzzy_adjacent_matches_do_not_overlap_at_trimmed_whitespace() {
606 for (replacement, expected) in [("\nY", "X\nY\n"), ("", "X\n")] {
607 let updated = apply_contract_edits(
608 "“A” \nB\n",
609 &[
610 ContractEdit {
611 index: 0,
612 old_text: "\"A\"".to_string(),
613 new_text: "X".to_string(),
614 },
615 ContractEdit {
616 index: 1,
617 old_text: "\nB".to_string(),
618 new_text: replacement.to_string(),
619 },
620 ],
621 "notes.txt",
622 false,
623 )
624 .expect("fuzzy edit");
625 assert_eq!(updated, expected);
626 }
627 }
628
629 #[tokio::test]
630 async fn contract_edit_preserves_bom_and_crlf_without_prior_read() {
631 let temporary = tempfile::tempdir().expect("tempdir");
632 let path = temporary.path().join("doc.txt");
633 std::fs::write(&path, "\u{FEFF}alpha\r\nbeta\r\n").expect("fixture");
634 let context = ToolContext::new(temporary.path());
635 let result = EditFileTool::execute_contract_edits(
636 json!({
637 "path": "doc.txt",
638 "edits": [{"oldText": "alpha\nbeta", "newText": "one\ntwo"}]
639 }),
640 &context,
641 )
642 .await
643 .expect("edit");
644 assert_eq!(
645 result.content.lines().next(),
646 Some("Successfully replaced 1 block(s) in doc.txt.")
647 );
648 assert!(
649 result.content.contains("--- a/doc.txt"),
650 "{}",
651 result.content
652 );
653 assert!(result.content.contains("-beta"), "{}", result.content);
654 assert!(result.content.contains("+two"), "{}", result.content);
655 assert_eq!(
656 std::fs::read(&path).expect("updated"),
657 "\u{FEFF}one\r\ntwo\r\n".as_bytes()
658 );
659 // The receipt describes the bytes written (BOM and CRLF included), not
660 // the edited text, so a turn artifact's revision matches the file read.
661 let on_disk = std::fs::read(&path).expect("updated");
662 assert_eq!(
663 result.metadata.as_ref().expect("metadata")["mutation"]["files"],
664 json!([{
665 "path": "doc.txt",
666 "outcome": "updated",
667 "size": on_disk.len(),
668 "sha256": codewhale_runtime::hashing::sha256_hex(&on_disk),
669 }])
670 );
671 }
672
673 #[tokio::test]
674 async fn contract_write_receipt_carries_written_size_and_sha256() {
675 let temporary = tempfile::tempdir().expect("tempdir");
676 let context = ToolContext::new(temporary.path());
677 let result = WriteFileTool::execute_contract_write(
678 json!({"path": "notes/out.md", "content": "# Title\n"}),
679 &context,
680 )
681 .await
682 .expect("write");
683 let on_disk = std::fs::read(temporary.path().join("notes/out.md")).expect("written");
684 assert_eq!(
685 result.metadata.as_ref().expect("metadata")["mutation"]["files"],
686 json!([{
687 "path": "notes/out.md",
688 "outcome": "created",
689 "size": on_disk.len(),
690 "sha256": codewhale_runtime::hashing::sha256_hex(&on_disk),
691 }])
692 );
693 }
694
695 /// B6: bytes that are not UTF-8 survive an edit elsewhere in the file.
696 #[tokio::test]
697 async fn contract_edit_keeps_non_utf8_bytes() {
698 let temporary = tempfile::tempdir().expect("tempdir");
699 let path = temporary.path().join("latin1.txt");
700 let mut original = b"caf\xe9 \xff\xfe tail\n".to_vec();
701 original.extend_from_slice(b"change me\n");
702 std::fs::write(&path, &original).expect("fixture");
703 let context = ToolContext::new(temporary.path());
704 EditFileTool::execute_contract_edits(
705 json!({"path": "latin1.txt", "edits": [{"oldText": "change me", "newText": "changed"}]}),
706 &context,
707 )
708 .await
709 .expect("edit");
710 assert_eq!(
711 std::fs::read(&path).expect("updated"),
712 b"caf\xe9 \xff\xfe tail\nchanged\n".to_vec()
713 );
714 }
715
716 /// A valid UTF-8 file may use the placeholder range itself (Nerd Font
717 /// Material Design icons are U+F0000..U+F00FF). Those characters are text,
718 /// not raw bytes, and an edit elsewhere must keep them.
719 #[tokio::test]
720 async fn contract_edit_keeps_placeholder_range_characters_in_utf8_files() {
721 let temporary = tempfile::tempdir().expect("tempdir");
722 let path = temporary.path().join("starship.toml");
723 let original = "icon = \"\u{F0026}\"\nwide = \"\u{F00A0}\"\ncolor = \"red\"\n";
724 std::fs::write(&path, original).expect("fixture");
725 let context = ToolContext::new(temporary.path());
726 EditFileTool::execute_contract_edits(
727 json!({"path": "starship.toml", "edits": [{"oldText": "red", "newText": "blue"}]}),
728 &context,
729 )
730 .await
731 .expect("edit");
732 assert_eq!(
733 std::fs::read_to_string(&path).expect("still UTF-8"),
734 original.replace("red", "blue")
735 );
736 }
737
738 /// B6: in a file with mixed line endings, only the lines an edit wrote take
739 /// the dominant ending; every untouched line keeps its own.
740 #[tokio::test]
741 async fn contract_edit_keeps_untouched_line_endings() {
742 let temporary = tempfile::tempdir().expect("tempdir");
743 let path = temporary.path().join("mixed.txt");
744 std::fs::write(&path, "one\r\ntwo\nthree\r\nfour\rfive\n").expect("fixture");
745 let context = ToolContext::new(temporary.path());
746 EditFileTool::execute_contract_edits(
747 json!({"path": "mixed.txt", "edits": [{"oldText": "three", "newText": "THREE\nand more"}]}),
748 &context,
749 )
750 .await
751 .expect("edit");
752 assert_eq!(
753 std::fs::read_to_string(&path).expect("updated"),
754 "one\r\ntwo\nTHREE\r\nand more\r\nfour\rfive\n"
755 );
756 }
757
758 #[tokio::test]
759 async fn queued_parallel_contract_edits_preserve_both_changes() {
760 let temporary = tempfile::tempdir().expect("tempdir");
761 let path = temporary.path().join("doc.txt");
762 std::fs::write(&path, "alpha\nbeta\ngamma\n").expect("fixture");
763 let context = ToolContext::new(temporary.path());
764 let first_context = context.clone();
765 let second_context = context.clone();
766
767 let first = tokio::spawn(async move {
768 EditFileTool::execute_contract_edits(
769 json!({"path": "doc.txt", "edits": [{"oldText": "alpha", "newText": "A"}]}),
770 &first_context,
771 )
772 .await
773 });
774 let second = tokio::spawn(async move {
775 EditFileTool::execute_contract_edits(
776 json!({"path": "doc.txt", "edits": [{"oldText": "gamma", "newText": "G"}]}),
777 &second_context,
778 )
779 .await
780 });
781 first.await.expect("first task").expect("first edit");
782 second.await.expect("second task").expect("second edit");
783 assert_eq!(
784 std::fs::read_to_string(path).expect("updated"),
785 "A\nbeta\nG\n"
786 );
787 }
788
789 #[tokio::test]
790 async fn cancelled_queued_pi_write_never_starts() {
791 let temporary = tempfile::tempdir().expect("tempdir");
792 let context = ToolContext::new(temporary.path());
793 let path = context.resolve_path("queued.txt").expect("resolved path");
794 let held = file_mutation_lock(&path).expect("queue").lock_owned().await;
795 let cancellation = CancellationToken::new();
796 let queued_context = context.clone().with_cancel_token(cancellation.clone());
797 let queued = tokio::spawn(async move {
798 WriteFileTool::execute_contract_write(
799 json!({"path": "queued.txt", "content": "must-not-land"}),
800 &queued_context,
801 )
802 .await
803 });
804 tokio::task::yield_now().await;
805 cancellation.cancel();
806 let error = queued
807 .await
808 .expect("queued task")
809 .expect_err("queued write must cancel");
810 assert!(matches!(error, ToolError::Cancelled { .. }));
811 assert!(!path.exists());
812 drop(held);
813 }
814
815 #[cfg(unix)]
816 #[tokio::test]
817 async fn contract_write_preserves_unreadable_existing_file() {
818 use std::os::unix::fs::PermissionsExt;
819
820 let temporary = tempfile::tempdir().expect("tempdir");
821 let path = temporary.path().join("write-only.txt");
822 std::fs::write(&path, "original\n").expect("fixture");
823 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o200))
824 .expect("make unreadable");
825 let context = ToolContext::new(temporary.path());
826 let result = WriteFileTool::execute_contract_write(
827 json!({"path": "write-only.txt", "content": "replacement\n"}),
828 &context,
829 )
830 .await;
831 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
832 .expect("restore permissions");
833
834 let error = result.expect_err("cannot overwrite without the prior contents");
835 assert!(error.to_string().contains("Failed to read"), "{error}");
836 assert_eq!(
837 std::fs::read_to_string(path).expect("unchanged"),
838 "original\n"
839 );
840 }
841
842 #[cfg(unix)]
843 #[tokio::test]
844 async fn compatibility_write_preserves_unreadable_existing_file() {
845 use std::os::unix::fs::PermissionsExt;
846
847 let temporary = tempfile::tempdir().expect("tempdir");
848 let path = temporary.path().join("write-only.txt");
849 let context = ToolContext::new(temporary.path());
850 std::fs::write(&path, "original\n").expect("fixture");
851 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o200))
852 .expect("make unreadable");
853 let result = WriteFileTool
854 .execute(
855 json!({"path": "write-only.txt", "content": "replacement\n"}),
856 &context,
857 )
858 .await;
859 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
860 .expect("restore permissions");
861
862 let error = result.expect_err("cannot overwrite without the prior contents");
863 assert!(error.to_string().contains("Failed to read"), "{error}");
864 assert_eq!(
865 std::fs::read_to_string(&path).expect("unchanged"),
866 "original\n"
867 );
868 }
869
870 #[tokio::test]
871 async fn compatibility_write_preserves_non_utf8_existing_file() {
872 let temporary = tempfile::tempdir().expect("tempdir");
873 let path = temporary.path().join("latin1.txt");
874 let original = b"caf\xe9\n";
875 std::fs::write(&path, original).expect("fixture");
876 let context = ToolContext::new(temporary.path());
877 let error = WriteFileTool
878 .execute(
879 json!({"path": "latin1.txt", "content": "replacement\n"}),
880 &context,
881 )
882 .await
883 .expect_err("must decode original");
884 assert!(error.to_string().contains("Failed to read"), "{error}");
885 assert_eq!(std::fs::read(&path).expect("unchanged"), original);
886 }
887
888 #[cfg(unix)]
889 #[tokio::test]
890 async fn contract_edit_rejects_read_only_target_before_atomic_replace() {
891 use std::os::unix::fs::PermissionsExt;
892
893 let temporary = tempfile::tempdir().expect("tempdir");
894 let path = temporary.path().join("readonly.txt");
895 std::fs::write(&path, "alpha\n").expect("fixture");
896 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o444)).expect("readonly");
897 let context = ToolContext::new(temporary.path());
898 let result = EditFileTool::execute_contract_edits(
899 json!({"path": "readonly.txt", "edits": [{"oldText": "alpha", "newText": "beta"}]}),
900 &context,
901 )
902 .await;
903 std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644))
904 .expect("restore permissions");
905 let error = result.expect_err("read-only target must fail");
906 assert!(error.to_string().contains("readable and writable"));
907 assert_eq!(std::fs::read_to_string(path).expect("unchanged"), "alpha\n");
908 }
909
910 async fn run_contract_bounds_operation(
911 operation: &str,
912 path: &str,
913 context: &ToolContext,
914 ) -> Result<(), ToolError> {
915 match operation {
916 "read" => ReadFileTool::execute_contract_read(
917 json!({"path": path, "offset": 1, "limit": 1}),
918 context,
919 )
920 .await
921 .map(|_| ()),
922 "write" => WriteFileTool::execute_contract_write(
923 json!({"path": path, "content": "replacement"}),
924 context,
925 )
926 .await
927 .map(|_| ()),
928 "edit" => EditFileTool::execute_contract_edits(
929 json!({"path": path, "edits": [{"oldText": "seed", "newText": "replacement"}]}),
930 context,
931 )
932 .await
933 .map(|_| ()),
934 _ => unreachable!(),
935 }
936 }
937
938 #[tokio::test]
939 async fn contract_source_cap_refuses_sparse_files_without_paging_or_mutation() {
940 use std::io::{Read as _, Write as _};
941 let temporary = tempfile::tempdir().unwrap();
942 let path = temporary.path().join("large.txt");
943 let mut file = fs::File::create(&path).unwrap();
944 file.write_all(b"seed").unwrap();
945 file.set_len(CONTRACT_FILE_MAX_BYTES as u64 + 1).unwrap();
946 drop(file);
947 let context = ToolContext::new(temporary.path());
948 for operation in ["read", "write", "edit"] {
949 let error = tokio::time::timeout(
950 Duration::from_secs(2),
951 run_contract_bounds_operation(operation, "large.txt", &context),
952 )
953 .await
954 .expect("bounded refusal")
955 .expect_err("source cap");
956 let message = error.to_string();
957 assert!(
958 message.contains("16 MiB processing cap"),
959 "{operation}: {message}"
960 );
961 assert!(
962 !message.contains("offset=") && !message.contains("max_bytes"),
963 "{message}"
964 );
965 assert_eq!(
966 fs::metadata(&path).unwrap().len(),
967 CONTRACT_FILE_MAX_BYTES as u64 + 1
968 );
969 let mut prefix = [0; 4];
970 fs::File::open(&path)
971 .unwrap()
972 .read_exact(&mut prefix)
973 .unwrap();
974 assert_eq!(&prefix, b"seed");
975 assert!(context.require_fresh_file_read(&path, "large.txt").is_err());
976 }
977 }
978
979 #[test]
980 fn contract_source_actual_reads_stop_at_cap_plus_one_and_poll_cancellation() {
981 use std::io::Read as _;
982 let mut exact = std::io::repeat(b'x').take(CONTRACT_FILE_MAX_BYTES as u64);
983 assert_eq!(
984 read_contract_source(&mut exact, None).unwrap().len(),
985 CONTRACT_FILE_MAX_BYTES
986 );
987
988 struct Reader {
989 consumed: usize,
990 cancel: Option<CancellationToken>,
991 }
992 impl std::io::Read for Reader {
993 fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {
994 bytes.fill(b'x');
995 self.consumed += bytes.len();
996 if let Some(cancel) = &self.cancel {
997 cancel.cancel();
998 }
999 Ok(bytes.len())
1000 }
1001 }
1002 // No metadata shortcut: this represents a growing/virtual regular file.
1003 let mut growing = Reader {
1004 consumed: 0,
1005 cancel: None,
1006 };
1007 assert!(read_contract_source(&mut growing, None).is_err());
1008 assert_eq!(growing.consumed, CONTRACT_FILE_MAX_BYTES + 1);
1009
1010 let token = CancellationToken::new();
1011 let mut interrupted = Reader {
1012 consumed: 0,
1013 cancel: Some(token.clone()),
1014 };
1015 assert!(matches!(
1016 read_contract_source(&mut interrupted, Some(&token)),
1017 Err(ToolError::Cancelled { .. })
1018 ));
1019 assert_eq!(interrupted.consumed, 64 * 1024);
1020 interrupted.consumed = 0;
1021 assert!(matches!(
1022 read_contract_source(&mut interrupted, Some(&token)),
1023 Err(ToolError::Cancelled { .. })
1024 ));
1025 assert_eq!(interrupted.consumed, 0);
1026 }
1027
1028 #[tokio::test]
1029 async fn contract_source_directory_and_cancelled_calls_leave_targets_untouched() {
1030 let temporary = tempfile::tempdir().unwrap();
1031 fs::create_dir(temporary.path().join("directory")).unwrap();
1032 let path = temporary.path().join("plain.txt");
1033 fs::write(&path, b"seed").unwrap();
1034 let context = ToolContext::new(temporary.path());
1035 for operation in ["read", "write", "edit"] {
1036 assert!(
1037 run_contract_bounds_operation(operation, "directory", &context)
1038 .await
1039 .is_err()
1040 );
1041 }
1042 let token = CancellationToken::new();
1043 token.cancel();
1044 let cancelled = context.with_cancel_token(token);
1045 for operation in ["read", "write", "edit"] {
1046 let error = run_contract_bounds_operation(operation, "plain.txt", &cancelled)
1047 .await
1048 .unwrap_err();
1049 assert!(
1050 matches!(error, ToolError::Cancelled { .. }),
1051 "{operation}: {error}"
1052 );
1053 assert_eq!(fs::read(&path).unwrap(), b"seed");
1054 assert!(
1055 cancelled
1056 .require_fresh_file_read(&path, "plain.txt")
1057 .is_err()
1058 );
1059 }
1060 }
1061
1062 #[cfg(unix)]
1063 #[tokio::test]
1064 async fn contract_source_fifo_without_writer_and_hard_links_are_refused_promptly() {
1065 use std::os::unix::ffi::OsStrExt as _;
1066 let temporary = tempfile::tempdir().unwrap();
1067 let fifo = temporary.path().join("pipe");
1068 let cpath = std::ffi::CString::new(fifo.as_os_str().as_bytes()).unwrap();
1069 assert_eq!(unsafe { libc::mkfifo(cpath.as_ptr(), 0o600) }, 0);
1070 let plain = temporary.path().join("plain.txt");
1071 fs::write(&plain, b"seed").unwrap();
1072 fs::hard_link(&plain, temporary.path().join("linked.txt")).unwrap();
1073 let context = ToolContext::new(temporary.path());
1074 for path in ["pipe", "linked.txt"] {
1075 for operation in ["read", "write", "edit"] {
1076 let error = tokio::time::timeout(
1077 Duration::from_secs(2),
1078 run_contract_bounds_operation(operation, path, &context),
1079 )
1080 .await
1081 .expect("must not block opening a FIFO")
1082 .expect_err("regular single-link target only");
1083 assert!(
1084 error.to_string().contains("regular"),
1085 "{operation}: {error}"
1086 );
1087 }
1088 }
1089 assert_eq!(fs::read(&plain).unwrap(), b"seed");
1090 }
1091
1092 #[tokio::test]
1093 async fn contract_read_newline_dense_ranges_preserve_trailing_and_empty_lines() {
1094 let temporary = tempfile::tempdir().unwrap();
1095 let text = "\n".repeat(2 * 1024 * 1024);
1096 fs::write(temporary.path().join("dense.txt"), &text).unwrap();
1097 let context = ToolContext::new(temporary.path());
1098 let result = ReadFileTool::execute_contract_read(
1099 json!({"path": "dense.txt", "offset": text.len() - 1, "limit": 2}),
1100 &context,
1101 )
1102 .await
1103 .unwrap();
1104 assert_eq!(
1105 result.content,
1106 format!(
1107 "[lines {}-{} of {} | {} bytes | truncated=false]\n{}: \n{}: ",
1108 text.len() - 1,
1109 text.len(),
1110 text.len(),
1111 text.len(),
1112 text.len() - 1,
1113 text.len()
1114 )
1115 );
1116 let metadata = result.metadata.as_ref().unwrap();
1117 assert_eq!(metadata["size"], text.len());
1118 assert_eq!(metadata["line_count"], text.len());
1119 assert_eq!(metadata["truncated"], false);
1120 let empty = ReadFileTool::execute_contract_read(
1121 json!({"path": "dense.txt", "offset": text.len(), "limit": 0}),
1122 &context,
1123 )
1124 .await
1125 .unwrap();
1126 // limit=0 selects nothing; there is no line range to footer about.
1127 assert_eq!(
1128 empty.content,
1129 format!(
1130 "[lines 0-0 of {} | {} bytes | truncated=true]",
1131 text.len(),
1132 text.len()
1133 )
1134 );
1135 }
1136
1137 #[tokio::test]
1138 async fn contract_read_handles_empty_file_and_pdf_pages() {
1139 let temporary = tempfile::tempdir().expect("tempdir");
1140 fs::write(temporary.path().join("empty.txt"), "").expect("empty fixture");
1141 fs::write(temporary.path().join("plain.txt"), "hello\n").expect("plain fixture");
1142 let pdf_path = temporary.path().join("doc.pdf");
1143 fs::write(&pdf_path, b"%PDF-1.7\n%%EOF").expect("pdf fixture");
1144 let context = ToolContext::new(temporary.path());
1145
1146 let empty = ReadFileTool::execute_contract_read(json!({"path": "empty.txt"}), &context)
1147 .await
1148 .expect("empty file read");
1149 assert_eq!(
1150 empty.content,
1151 "[lines 0-0 of 0 | 0 bytes | truncated=false]"
1152 );
1153 let empty_meta = empty.metadata.as_ref().expect("metadata");
1154 assert_eq!(empty_meta["size"], 0);
1155 assert_eq!(empty_meta["line_count"], 0);
1156 assert_eq!(empty_meta["truncated"], false);
1157
1158 let oob =
1159 ReadFileTool::execute_contract_read(json!({"path": "empty.txt", "offset": 2}), &context)
1160 .await
1161 .expect_err("offset beyond empty file");
1162 assert!(oob.to_string().contains("(0 lines total)"), "{oob}");
1163
1164 let plain_with_pages =
1165 ReadFileTool::execute_contract_read(json!({"path": "plain.txt", "pages": "1-2"}), &context)
1166 .await
1167 .expect("pages ignored for non-pdf");
1168 assert_eq!(
1169 plain_with_pages.content,
1170 "[lines 1-1 of 1 | 6 bytes | truncated=false]\n1: hello"
1171 );
1172
1173 let missing_bin = temporary.path().join("missing-pdftotext");
1174 let invalid_pages = ReadFileTool::execute_contract_read_with_pdf(
1175 json!({"path": "doc.pdf", "pages": "5-2"}),
1176 &context,
1177 super::super::pdf::PdfTextCommand::test(
1178 missing_bin.as_os_str(),
1179 Duration::from_secs(1),
1180 None,
1181 ),
1182 )
1183 .await
1184 .expect_err("invalid pdf page range must fail");
1185 assert!(
1186 matches!(invalid_pages, ToolError::InvalidInput { .. }),
1187 "{invalid_pages:?}"
1188 );
1189
1190 #[cfg(unix)]
1191 {
1192 use std::os::unix::fs::PermissionsExt;
1193
1194 let fake_pdf = temporary.path().join("fake-pdftotext");
1195 fs::write(
1196 &fake_pdf,
1197 "#!/bin/sh\nprintf 'args:%s\\nsecond line\\n' \"$*\"\n",
1198 )
1199 .expect("fake pdftotext");
1200 fs::set_permissions(&fake_pdf, fs::Permissions::from_mode(0o755)).expect("chmod");
1201 let extracted = ReadFileTool::execute_contract_read_with_pdf(
1202 json!({"path": "doc.pdf", "pages": "2-4"}),
1203 &context,
1204 super::super::pdf::PdfTextCommand::test(
1205 fake_pdf.as_os_str(),
1206 Duration::from_secs(5),
1207 None,
1208 ),
1209 )
1210 .await
1211 .expect("pdf read with pages");
1212 assert!(
1213 extracted.content.starts_with(
1214 "[lines 1-2 of 2 | 14 bytes | truncated=false]\n1: args:-layout -f 2 -l 4 "
1215 ),
1216 "{}",
1217 extracted.content
1218 );
1219 assert!(
1220 extracted.content.ends_with("\n2: second line"),
1221 "{}",
1222 extracted.content
1223 );
1224 let meta = extracted.metadata.as_ref().expect("pdf metadata");
1225 assert_eq!(meta["size"], 14);
1226 assert_eq!(meta["line_count"], 2);
1227 assert_eq!(meta["truncated"], false);
1228 }
1229 }
1230
1231 #[tokio::test]
1232 async fn contract_read_rejects_images_on_unsupported_route_but_reads_text() {
1233 let temporary = tempfile::tempdir().expect("tempdir");
1234 fs::write(
1235 temporary.path().join("shot.png"),
1236 crate::image_attach::test_support::PNG_1X1,
1237 )
1238 .expect("png fixture");
1239 fs::write(temporary.path().join("plain.png"), "not an image\n").expect("text fixture");
1240 let mut context = ToolContext::new(temporary.path());
1241 context.route_capabilities.image_input = codewhale_config::route::CapabilityState::Unsupported;
1242
1243 let error = ReadFileTool::execute_contract_read(json!({"path": "shot.png"}), &context)
1244 .await
1245 .expect_err("image read must fail on non-vision route");
1246 let message = error.to_string();
1247 assert!(
1248 message.contains("does not support image input") && message.contains("/model"),
1249 "{message}"
1250 );
1251 assert!(
1252 context
1253 .require_fresh_file_read(&temporary.path().join("shot.png"), "shot.png")
1254 .is_err()
1255 );
1256
1257 let text = ReadFileTool::execute_contract_read(json!({"path": "plain.png"}), &context)
1258 .await
1259 .expect("non-image text file still reads on text-only route");
1260 assert_eq!(
1261 text.content,
1262 "[lines 1-1 of 1 | 13 bytes | truncated=false]\n1: not an image"
1263 );
1264 }
1265
1266 #[tokio::test]
1267 async fn contract_write_and_edit_reject_payload_or_line_ending_growth_before_mutation() {
1268 let temporary = tempfile::tempdir().unwrap();
1269 let path = temporary.path().join("plain.txt");
1270 let context = ToolContext::new(temporary.path());
1271 fs::write(&path, b"seed\r\n").unwrap();
1272 let resolved = context.resolve_path("plain.txt").unwrap();
1273 context.note_file_read(&resolved);
1274 let error = WriteFileTool::execute_contract_write(
1275 json!({"path": "plain.txt", "content": "x".repeat(CONTRACT_FILE_MAX_BYTES + 1)}),
1276 &context,
1277 )
1278 .await
1279 .unwrap_err();
1280 assert!(error.to_string().contains("16 MiB processing cap"));
1281 for operation in ["write", "edit"] {
1282 let newlines = "\n".repeat(CONTRACT_FILE_MAX_BYTES / 2 + 1);
1283 let result = if operation == "write" {
1284 WriteFileTool::execute_contract_write(
1285 json!({"path": "plain.txt", "content": newlines}),
1286 &context,
1287 )
1288 .await
1289 } else {
1290 EditFileTool::execute_contract_edits(
1291 json!({"path": "plain.txt", "edits": [{"oldText": "seed", "newText": newlines}]}),
1292 &context,
1293 )
1294 .await
1295 };
1296 assert!(
1297 result
1298 .unwrap_err()
1299 .to_string()
1300 .contains("16 MiB processing cap")
1301 );
1302 assert_eq!(fs::read(&path).unwrap(), b"seed\r\n");
1303 assert!(
1304 context
1305 .require_fresh_file_read(&resolved, "plain.txt")
1306 .is_ok()
1307 );
1308 }
1309 }
1310
1311 #[tokio::test]
1312 async fn contract_edit_rejects_oversized_intermediate_replacement_even_if_later_edit_shrinks() {
1313 let temporary = tempfile::tempdir().unwrap();
1314 let path = temporary.path().join("plain.txt");
1315 fs::write(&path, b"ab").unwrap();
1316 let context = ToolContext::new(temporary.path());
1317 let error = EditFileTool::execute_contract_edits(
1318 json!({"path": "plain.txt", "edits": [
1319 {"oldText": "a", "newText": ""},
1320 {"oldText": "b", "newText": "x".repeat(CONTRACT_FILE_MAX_BYTES)}
1321 ]}),
1322 &context,
1323 )
1324 .await
1325 .unwrap_err();
1326 assert!(error.to_string().contains("16 MiB processing cap"));
1327 assert_eq!(fs::read(&path).unwrap(), b"ab");
1328 }
1329
1330 #[tokio::test]
1331 async fn contract_read_admits_only_an_image_the_user_attached_from_outside_the_workspace() {
1332 let workspace = tempfile::tempdir().expect("workspace");
1333 let outside = tempfile::tempdir().expect("outside");
1334 let shot = outside.path().join("Screenshot 2026-10-04 at 22.25.47.png");
1335 std::fs::write(&shot, crate::image_attach::test_support::PNG_1X1).expect("fixture");
1336 let stray = outside.path().join("stray.png");
1337 std::fs::write(&stray, crate::image_attach::test_support::PNG_1X1).expect("fixture");
1338 let prompt = codewhale_models::Message {
1339 role: codewhale_models::Role::User,
1340 content: vec![codewhale_models::ContentBlock::Text {
1341 text: format!("what is this?\n[Attached image: {}]", shot.display()),
1342 cache_control: None,
1343 }],
1344 };
1345 let context = ToolContext::new(workspace.path()).with_session_objects(
1346 crate::rlm::session::SessionObjectSnapshot::new(
1347 "session".to_string(),
1348 "model".to_string(),
1349 workspace.path().to_path_buf(),
1350 None,
1351 vec![prompt],
1352 ),
1353 );
1354
1355 let image =
1356 ReadFileTool::execute_contract_read(json!({"path": shot.display().to_string()}), &context)
1357 .await
1358 .expect("the attached screenshot is readable");
1359 assert_eq!(image.content_blocks.len(), 1);
1360
1361 let error =
1362 ReadFileTool::execute_contract_read(json!({"path": stray.display().to_string()}), &context)
1363 .await
1364 .expect_err("an outside image the user never attached stays refused");
1365 assert!(matches!(error, ToolError::PathEscape { .. }), "{error:?}");
1366 }
1367
1368 #[tokio::test]
1369 async fn contract_edit_returns_bounded_unified_diff_and_truncates_large_diffs() {
1370 let temporary = tempfile::tempdir().expect("tempdir");
1371 let context = ToolContext::new(temporary.path());
1372
1373 let rs_path = temporary.path().join("sample.rs");
1374 std::fs::write(&rs_path, "fn main() {\n let x = 1;\n}\n").expect("fixture");
1375 let small = EditFileTool::execute_contract_edits(
1376 json!({
1377 "path": "sample.rs",
1378 "edits": [{"oldText": "let x = 1;", "newText": "let x=2;"}]
1379 }),
1380 &context,
1381 )
1382 .await
1383 .expect("small edit");
1384 assert_eq!(
1385 small.content.lines().next(),
1386 Some("Successfully replaced 1 block(s) in sample.rs.")
1387 );
1388 assert!(
1389 small.content.contains("--- a/sample.rs"),
1390 "{}",
1391 small.content
1392 );
1393 assert!(
1394 small.content.contains("+++ b/sample.rs"),
1395 "{}",
1396 small.content
1397 );
1398 assert!(
1399 small.content.contains("- let x = 1;"),
1400 "{}",
1401 small.content
1402 );
1403 let final_rs = std::fs::read_to_string(&rs_path).expect("read rs");
1404 let expected_line = final_rs
1405 .lines()
1406 .find(|line| line.contains('2'))
1407 .expect("updated line");
1408 assert!(
1409 small.content.contains(&format!("+{expected_line}")),
1410 "{}",
1411 small.content
1412 );
1413
1414 let big_before: String = (0..220).map(|i| format!("before_line_{i:03}\n")).collect();
1415 let big_after: String = (0..220).map(|i| format!("after_line_{i:03}\n")).collect();
1416 let big_path = temporary.path().join("big.txt");
1417 std::fs::write(&big_path, &big_before).expect("fixture");
1418 let big = EditFileTool::execute_contract_edits(
1419 json!({
1420 "path": "big.txt",
1421 "edits": [{"oldText": big_before, "newText": big_after}]
1422 }),
1423 &context,
1424 )
1425 .await
1426 .expect("large edit");
1427 assert_eq!(
1428 big.content.lines().next(),
1429 Some("Successfully replaced 1 block(s) in big.txt.")
1430 );
1431 assert!(big.content.contains("diff truncated:"), "{}", big.content);
1432 assert!(big.content.contains("+220/-220"), "{}", big.content);
1433 assert!(
1434 big.content.len() <= CONTRACT_DIFF_MAX_BYTES + 512,
1435 "content too large: {}",
1436 big.content.len()
1437 );
1438 let full_meta_diff = big.metadata.as_ref().expect("metadata")["mutation"]["diff"]
1439 .as_str()
1440 .expect("diff string");
1441 assert!(full_meta_diff.contains("+after_line_219"));
1442
1443 let created_body: String = (0..180).map(|i| format!("created_line_{i:03}\n")).collect();
1444 let created = WriteFileTool::execute_contract_write(
1445 json!({"path": "brand_new.txt", "content": created_body}),
1446 &context,
1447 )
1448 .await
1449 .expect("create large file");
1450 assert!(
1451 created.content.starts_with("Successfully wrote "),
1452 "{}",
1453 created.content
1454 );
1455 assert!(
1456 created.content.contains("created file has 180 lines"),
1457 "{}",
1458 created.content
1459 );
1460 assert!(
1461 created.content.len() <= CONTRACT_CREATE_PREVIEW_MAX_BYTES + 512,
1462 "created content too large: {}",
1463 created.content.len()
1464 );
1465
1466 let updated = WriteFileTool::execute_contract_write(
1467 json!({"path": "sample.rs", "content": "fn main() {\n let x = 99;\n}\n"}),
1468 &context,
1469 )
1470 .await
1471 .expect("update existing file");
1472 assert!(
1473 updated.content.starts_with("Successfully wrote "),
1474 "{}",
1475 updated.content
1476 );
1477 assert!(
1478 updated.content.contains("+ let x = 99;"),
1479 "{}",
1480 updated.content
1481 );
1482 }
1483
1484 #[test]
1485 fn apply_contract_edits_accepts_unique_exact_match_despite_fuzzy_ambiguity() {
1486 let base = "let a = \"hi\";\nlet a = “hi”;\n";
1487 let updated = apply_contract_edits(
1488 base,
1489 &[ContractEdit {
1490 index: 0,
1491 old_text: "let a = \"hi\";".to_string(),
1492 new_text: "let a = \"bye\";".to_string(),
1493 }],
1494 "quotes.rs",
1495 false,
1496 )
1497 .expect("unique exact match must succeed even when fuzzy matches 2");
1498 assert_eq!(updated, "let a = \"bye\";\nlet a = “hi”;\n");
1499
1500 let ws_base = "line one\nline one \n";
1501 let ws_updated = apply_contract_edits(
1502 ws_base,
1503 &[ContractEdit {
1504 index: 0,
1505 old_text: "line one\n".to_string(),
1506 new_text: "LINE ONE\n".to_string(),
1507 }],
1508 "spaces.txt",
1509 false,
1510 )
1511 .expect("unique exact match with trailing-space twin must succeed");
1512 assert_eq!(ws_updated, "LINE ONE\nline one \n");
1513 }
1514
1515 #[test]
1516 fn apply_contract_edits_uses_fuzzy_fallback_per_edit_without_mutating_exact_items() {
1517 let base = "alpha “keep” \nmid\nShe said “hello”—today.\n";
1518 let updated = apply_contract_edits(
1519 base,
1520 &[
1521 ContractEdit {
1522 index: 0,
1523 old_text: "alpha".to_string(),
1524 new_text: "ALPHA".to_string(),
1525 },
1526 ContractEdit {
1527 index: 1,
1528 old_text: "She said \"hello\"-today.".to_string(),
1529 new_text: "She said hello.".to_string(),
1530 },
1531 ],
1532 "mixed.txt",
1533 false,
1534 )
1535 .expect("mixed exact + fuzzy batch");
1536 assert_eq!(updated, "ALPHA “keep” \nmid\nShe said hello.\n");
1537
1538 let overlap = apply_contract_edits(
1539 "She said “hello” today\n",
1540 &[
1541 ContractEdit {
1542 index: 0,
1543 old_text: "She said".to_string(),
1544 new_text: "He said".to_string(),
1545 },
1546 ContractEdit {
1547 index: 1,
1548 old_text: "said \"hello\"".to_string(),
1549 new_text: "whispered hi".to_string(),
1550 },
1551 ],
1552 "overlap.txt",
1553 false,
1554 )
1555 .expect_err("overlapping exact and fuzzy edits must fail");
1556 assert!(overlap.to_string().contains("overlap"), "{overlap}");
1557 }
1558
1559 #[test]
1560 fn contract_edit_not_found_includes_closest_match_snippet() {
1561 let base = "fn alpha() {\n let count = 1;\n println!(\"{count}\");\n}\n";
1562 let error = apply_contract_edits(
1563 base,
1564 &[ContractEdit {
1565 index: 0,
1566 old_text: "fn alpha() {\n let count = 2;\n println!(\"{count}\");\n}".to_string(),
1567 new_text: "fn alpha() {}".to_string(),
1568 }],
1569 "src/lib.rs",
1570 false,
1571 )
1572 .expect_err("mismatch must fail");
1573 let message = error.to_string();
1574 assert!(
1575 message.contains("Could not find the exact text in src/lib.rs."),
1576 "{message}"
1577 );
1578 assert!(message.contains("Closest match (lines 1-4"), "{message}");
1579 assert!(message.contains("2\t let count = 1;"), "{message}");
1580 assert!(
1581 message.contains("first differing line is line 2"),
1582 "{message}"
1583 );
1584
1585 let first_line_wrong = apply_contract_edits(
1586 base,
1587 &[ContractEdit {
1588 index: 0,
1589 old_text: "// stale comment\n let count = 1;\n println!(\"{count}\");\n}"
1590 .to_string(),
1591 new_text: "fn beta() {}".to_string(),
1592 }],
1593 "src/lib.rs",
1594 false,
1595 )
1596 .expect_err("first-line mismatch must fail");
1597 let first_msg = first_line_wrong.to_string();
1598 assert!(
1599 first_msg.contains("Closest match (lines 1-4"),
1600 "{first_msg}"
1601 );
1602 assert!(
1603 first_msg.contains("first differing line is line 1"),
1604 "{first_msg}"
1605 );
1606 }
1607
1608 #[tokio::test]
1609 async fn contract_read_on_a_directory_names_it_and_points_to_listing_tools() {
1610 let temporary = tempfile::tempdir().expect("tempdir");
1611 std::fs::create_dir(temporary.path().join("src")).expect("mkdir");
1612 let context = ToolContext::new(temporary.path());
1613
1614 let error = ReadFileTool::execute_contract_read(json!({"path": "src"}), &context)
1615 .await
1616 .expect_err("directory read must fail")
1617 .to_string();
1618 assert!(error.contains("path is a directory"), "{error}");
1619 assert!(error.contains("list_dir"), "{error}");
1620 }
1621
1622 #[cfg(unix)]
1623 #[test]
1624 fn symlinked_parent_directory_is_refused_by_read_and_read_file() {
1625 use std::os::unix::fs::symlink;
1626
1627 let _env_lock = crate::test_support::lock_test_env();
1628 let workspace = tempfile::tempdir().expect("workspace");
1629 let outside = tempfile::tempdir().expect("outside");
1630 let denied = tempfile::tempdir().expect("denied");
1631 let outside_secret = outside.path().join("secret.txt");
1632 let denied_secret = denied.path().join("vault.txt");
1633 fs::write(&outside_secret, "outside-secret\n").expect("write outside");
1634 fs::write(&denied_secret, "denied-vault-secret\n").expect("write denied");
1635
1636 symlink(outside.path(), workspace.path().join("escape_parent")).expect("escape symlink");
1637 symlink(denied.path(), workspace.path().join("denied_parent")).expect("denied symlink");
1638
1639 let real_parent = workspace.path().join("swapped_parent");
1640 fs::create_dir(&real_parent).expect("create real parent");
1641 fs::write(real_parent.join("vault.txt"), "benign\n").expect("write benign");
1642
1643 let denylist = codewhale_sandbox::read_guard::ReadDenylist::build(
1644 true,
1645 &[denied.path().to_path_buf()],
1646 &[],
1647 );
1648 codewhale_sandbox::read_guard::with_test_active_denylist(denylist, || {
1649 let rt = tokio::runtime::Builder::new_current_thread()
1650 .enable_all()
1651 .build()
1652 .expect("runtime");
1653 rt.block_on(async {
1654 let ctx = ToolContext::new(workspace.path());
1655 let trusted_ctx = ToolContext::new(workspace.path()).with_trust_mode(true);
1656
1657 let escape_contract = ReadFileTool::execute_contract_read(
1658 json!({"path": "escape_parent/secret.txt"}),
1659 &ctx,
1660 )
1661 .await
1662 .expect_err("symlinked parent outside workspace must be refused by read");
1663 assert!(
1664 matches!(
1665 escape_contract,
1666 ToolError::PathEscape { .. } | ToolError::PermissionDenied { .. }
1667 ),
1668 "{escape_contract:?}"
1669 );
1670
1671 let escape_legacy = ReadFileTool
1672 .execute(json!({"path": "escape_parent/secret.txt"}), &ctx)
1673 .await
1674 .expect_err("symlinked parent outside workspace must be refused by read_file");
1675 assert!(
1676 matches!(
1677 escape_legacy,
1678 ToolError::PathEscape { .. } | ToolError::PermissionDenied { .. }
1679 ),
1680 "{escape_legacy:?}"
1681 );
1682
1683 for (label, current_ctx) in [("default", &ctx), ("trust_mode", &trusted_ctx)] {
1684 let denied_contract = ReadFileTool::execute_contract_read(
1685 json!({"path": "denied_parent/vault.txt"}),
1686 current_ctx,
1687 )
1688 .await
1689 .expect_err("symlinked parent into denied dir must be refused by read");
1690 assert!(
1691 matches!(denied_contract, ToolError::PermissionDenied { .. }),
1692 "{label}: {denied_contract:?}"
1693 );
1694 assert!(
1695 !denied_contract
1696 .to_string()
1697 .contains(&denied.path().display().to_string()),
1698 "{label}: {denied_contract}"
1699 );
1700
1701 let denied_legacy = ReadFileTool
1702 .execute(json!({"path": "denied_parent/vault.txt"}), current_ctx)
1703 .await
1704 .expect_err("symlinked parent into denied dir must be refused by read_file");
1705 assert!(
1706 matches!(denied_legacy, ToolError::PermissionDenied { .. }),
1707 "{label}: {denied_legacy:?}"
1708 );
1709 assert!(
1710 !denied_legacy
1711 .to_string()
1712 .contains(&denied.path().display().to_string()),
1713 "{label}: {denied_legacy}"
1714 );
1715 }
1716
1717 let plan =
1718 resolve_read_open_plan(&ctx, "swapped_parent/vault.txt", "read", false, true)
1719 .await
1720 .expect("plan resolved while parent is a real directory");
1721 fs::remove_dir_all(&real_parent).expect("remove real parent");
1722 symlink(denied.path(), &real_parent).expect("swap parent with denied symlink");
1723 let raced = open_verified_read_handle(&plan, true, true, true)
1724 .expect_err("parent directory swapped for symlink must fail at openat");
1725 assert!(
1726 matches!(raced, ToolError::PermissionDenied { .. }),
1727 "{raced:?}"
1728 );
1729 });
1730 });
1731 }
1732
1733 #[tokio::test]
1734 async fn verify_opened_read_file_catches_denied_descriptor_and_outside_descriptor() {
1735 let _env_lock = crate::test_support::lock_test_env();
1736 let workspace = tempfile::tempdir().expect("workspace");
1737 let denied = tempfile::tempdir().expect("denied");
1738 let outside = tempfile::tempdir().expect("outside");
1739 let denied_file = denied.path().join("token.txt");
1740 let outside_file = outside.path().join("other.txt");
1741 fs::write(&denied_file, "secret-token\n").expect("write denied");
1742 fs::write(&outside_file, "outside-data\n").expect("write outside");
1743
1744 let workspace_canonical = workspace.path().canonicalize().expect("canonical ws");
1745 let trusted_ctx = ToolContext::new(workspace.path()).with_trust_mode(true);
1746 let trusted_boundary = OpenedReadBoundary::from_context(
1747 &trusted_ctx,
1748 "read",
1749 "innocuous.txt",
1750 workspace_canonical.clone(),
1751 None,
1752 true,
1753 )
1754 .await;
1755 let default_ctx = ToolContext::new(workspace.path());
1756 let default_boundary = OpenedReadBoundary::from_context(
1757 &default_ctx,
1758 "read_file",
1759 "notes.txt",
1760 workspace_canonical,
1761 None,
1762 true,
1763 )
1764 .await;
1765 let denylist = codewhale_sandbox::read_guard::ReadDenylist::build(
1766 true,
1767 &[denied.path().to_path_buf()],
1768 &[],
1769 );
1770 codewhale_sandbox::read_guard::with_test_active_denylist(denylist, || {
1771 let denied_handle = fs::File::open(&denied_file).expect("open denied fixture");
1772 let err = verify_opened_read_file(&denied_handle, &trusted_boundary)
1773 .expect_err("opened fd inside denied directory must be refused");
1774 assert!(matches!(err, ToolError::PermissionDenied { .. }), "{err:?}");
1775 assert!(err.to_string().contains("innocuous.txt"), "{err}");
1776 assert!(
1777 !err.to_string()
1778 .contains(&denied.path().display().to_string()),
1779 "{err}"
1780 );
1781
1782 let outside_handle = fs::File::open(&outside_file).expect("open outside fixture");
1783 let outside_err = verify_opened_read_file(&outside_handle, &default_boundary)
1784 .expect_err("opened fd outside allowed roots must be refused");
1785 assert!(
1786 matches!(outside_err, ToolError::PermissionDenied { .. }),
1787 "{outside_err:?}"
1788 );
1789 });
1790 }
1791
1792 #[cfg(unix)]
1793 #[tokio::test]
1794 async fn pdf_read_with_pages_uses_verified_staged_bytes_instead_of_reopening_path() {
1795 use std::os::unix::fs::PermissionsExt as _;
1796
1797 let workspace = tempfile::tempdir().expect("workspace");
1798 let pdf_path = workspace.path().join("report.pdf");
1799 let payload = b"%PDF-1.7\nverified-body\n%%EOF";
1800 fs::write(&pdf_path, payload).expect("write pdf");
1801 let fake_pdf = workspace.path().join("fake-pdftotext");
1802 fs::write(
1803 &fake_pdf,
1804 "#!/bin/sh\nprintf 'args:%s\\n' \"$*\"\ncat \"$6\"\n",
1805 )
1806 .expect("write fake pdftotext");
1807 fs::set_permissions(&fake_pdf, fs::Permissions::from_mode(0o755)).expect("chmod");
1808
1809 let context = ToolContext::new(workspace.path());
1810 let command =
1811 super::super::pdf::PdfTextCommand::test(fake_pdf.as_os_str(), Duration::from_secs(5), None);
1812
1813 let contract = ReadFileTool::execute_contract_read_with_pdf(
1814 json!({"path": "report.pdf", "pages": "2-4"}),
1815 &context,
1816 command,
1817 )
1818 .await
1819 .expect("contract pdf read");
1820 assert!(
1821 contract.content.contains("-layout -f 2 -l 4 "),
1822 "{}",
1823 contract.content
1824 );
1825 assert!(
1826 contract.content.contains("verified-body"),
1827 "{}",
1828 contract.content
1829 );
1830 assert!(
1831 !contract.content.contains(&pdf_path.display().to_string()),
1832 "pdftotext must read staged bytes, not reopen the workspace path: {}",
1833 contract.content
1834 );
1835
1836 let legacy = ReadFileTool::execute_legacy_read_with_pdf(
1837 json!({"path": "report.pdf", "pages": "2-4"}),
1838 &context,
1839 command,
1840 )
1841 .await
1842 .expect("legacy pdf read");
1843 assert!(
1844 legacy.content.contains("-layout -f 2 -l 4 "),
1845 "{}",
1846 legacy.content
1847 );
1848 assert!(
1849 legacy.content.contains("verified-body"),
1850 "{}",
1851 legacy.content
1852 );
1853 assert!(
1854 !legacy.content.contains(&pdf_path.display().to_string()),
1855 "legacy read_file pdftotext must read staged bytes, not reopen the workspace path: {}",
1856 legacy.content
1857 );
1858 }
1859
1860 #[cfg(unix)]
1861 #[allow(clippy::await_holding_lock)]
1862 #[tokio::test]
1863 async fn verify_opened_read_file_blocks_unlinked_credential_file_behind_symlinked_home() {
1864 let _env_lock = crate::test_support::lock_test_env();
1865 let root = tempfile::tempdir().expect("tempdir");
1866 let real_home = root.path().join("real-home");
1867 let alias_home = root.path().join("alias-home");
1868 let workspace = root.path().join("workspace");
1869 fs::create_dir_all(&real_home).expect("real home");
1870 fs::create_dir_all(&workspace).expect("workspace");
1871 std::os::unix::fs::symlink(&real_home, &alias_home).expect("symlink home");
1872 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &alias_home);
1873 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
1874 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
1875
1876 let config_file = real_home.join("config.toml");
1877 fs::write(&config_file, "api_key = \"secret\"\n").expect("write config");
1878 let opened = fs::File::open(&config_file).expect("open config");
1879 fs::remove_file(&config_file).expect("unlink config while held open");
1880
1881 let workspace_canonical = workspace.canonicalize().expect("canonical ws");
1882 let ctx = ToolContext::new(&workspace).with_trust_mode(true);
1883 let boundary = OpenedReadBoundary::from_context(
1884 &ctx,
1885 "read",
1886 "config.toml",
1887 workspace_canonical,
1888 None,
1889 true,
1890 )
1891 .await;
1892 let err = verify_opened_read_file(&opened, &boundary)
1893 .expect_err("unlinked config.toml behind symlinked home must stay blocked");
1894 assert!(matches!(err, ToolError::PermissionDenied { .. }), "{err:?}");
1895 assert!(
1896 err.to_string()
1897 .contains("cannot expose Codewhale configuration or credential-store"),
1898 "{err}"
1899 );
1900 }
1901
1902 #[cfg(unix)]
1903 #[tokio::test]
1904 async fn read_file_refuses_hardlink_outside_workspace_and_classifies_workspace_directory() {
1905 let workspace = tempfile::tempdir().expect("workspace");
1906 let outside = tempfile::tempdir().expect("outside");
1907 let subdir = workspace.path().join("subdir");
1908 fs::create_dir_all(&subdir).expect("subdir");
1909
1910 let original = outside.path().join("secret.txt");
1911 let linked = outside.path().join("alias.txt");
1912 fs::write(&original, "secret\n").expect("write original");
1913 fs::hard_link(&original, &linked).expect("hardlink outside");
1914
1915 let ctx = ToolContext::new(workspace.path()).with_trust_mode(true);
1916 let link_err = ReadFileTool
1917 .execute(json!({"path": linked.to_string_lossy()}), &ctx)
1918 .await
1919 .expect_err("hardlinked outside file must be refused by read_file");
1920 assert!(
1921 matches!(link_err, ToolError::PermissionDenied { .. }),
1922 "{link_err:?}"
1923 );
1924
1925 let dir_err = ReadFileTool
1926 .execute(json!({"path": "subdir"}), &ctx)
1927 .await
1928 .expect_err("directory must fail with directory error");
1929 assert!(
1930 matches!(dir_err, ToolError::ExecutionFailed { .. })
1931 && dir_err.to_string().contains("path is a directory"),
1932 "{dir_err:?}"
1933 );
1934 }
1935
1936 #[tokio::test]
1937 async fn list_dir_reads_trusted_external_and_read_only_root_and_preserves_error_contracts() {
1938 let workspace = tempfile::tempdir().expect("workspace");
1939 let trusted = tempfile::tempdir().expect("trusted");
1940 let ro_root = tempfile::tempdir().expect("read-only root");
1941
1942 fs::write(trusted.path().join("alpha.txt"), "hello").expect("write alpha");
1943 fs::create_dir_all(trusted.path().join("nested")).expect("mkdir nested");
1944 fs::write(ro_root.path().join("guide.md"), "# guide").expect("write guide");
1945
1946 let trusted_canon = trusted.path().canonicalize().expect("canon trusted");
1947 let ro_canon = ro_root.path().canonicalize().expect("canon ro");
1948 let ctx = ToolContext::new(workspace.path())
1949 .with_trusted_external_paths(vec![trusted_canon.clone()])
1950 .with_read_only_roots(vec![ro_canon.clone()]);
1951
1952 let trusted_out = ListDirTool
1953 .execute(json!({"path": trusted_canon.to_string_lossy()}), &ctx)
1954 .await
1955 .expect("trusted external dir should list");
1956 let trusted_json: Value =
1957 serde_json::from_str(&trusted_out.content).expect("trusted list_dir json");
1958 let trusted_entries = trusted_json.as_array().expect("trusted entries array");
1959 assert!(
1960 trusted_entries
1961 .iter()
1962 .any(|e| e["name"] == "alpha.txt" && e["is_dir"] == false),
1963 "{trusted_json}"
1964 );
1965 assert!(
1966 trusted_entries
1967 .iter()
1968 .any(|e| e["name"] == "nested" && e["is_dir"] == true),
1969 "{trusted_json}"
1970 );
1971
1972 let ro_out = ListDirTool
1973 .execute(json!({"path": ro_canon.to_string_lossy()}), &ctx)
1974 .await
1975 .expect("read-only root should list");
1976 let ro_json: Value = serde_json::from_str(&ro_out.content).expect("ro list_dir json");
1977 assert!(
1978 ro_json
1979 .as_array()
1980 .expect("ro entries array")
1981 .iter()
1982 .any(|e| e["name"] == "guide.md" && e["is_dir"] == false),
1983 "{ro_json}"
1984 );
1985
1986 let file_err = ListDirTool
1987 .execute(
1988 json!({"path": trusted_canon.join("alpha.txt").to_string_lossy()}),
1989 &ctx,
1990 )
1991 .await
1992 .expect_err("regular file must fail list_dir");
1993 assert!(
1994 matches!(file_err, ToolError::ExecutionFailed { .. })
1995 && file_err.to_string().contains("Failed to read directory"),
1996 "{file_err:?}"
1997 );
1998
1999 let missing_err = ListDirTool
2000 .execute(json!({"path": "does-not-exist"}), &ctx)
2001 .await
2002 .expect_err("missing dir must fail list_dir");
2003 assert!(
2004 matches!(missing_err, ToolError::ExecutionFailed { .. })
2005 && missing_err.to_string().contains("Failed to read directory"),
2006 "{missing_err:?}"
2007 );
2008
2009 let cancel = CancellationToken::new();
2010 cancel.cancel();
2011 let cancelled_ctx = ctx.with_cancel_token(cancel);
2012 let cancel_err = ListDirTool
2013 .execute(
2014 json!({"path": trusted_canon.to_string_lossy()}),
2015 &cancelled_ctx,
2016 )
2017 .await
2018 .expect_err("cancelled list_dir must fail");
2019 assert!(
2020 matches!(cancel_err, ToolError::Cancelled { .. }),
2021 "{cancel_err:?}"
2022 );
2023 }
2024
2025 #[cfg(unix)]
2026 #[tokio::test]
2027 async fn list_dir_refuses_post_plan_symlink_swap_for_workspace_and_outside_targets() {
2028 let workspace = tempfile::tempdir().expect("workspace");
2029 let trusted = tempfile::tempdir().expect("trusted");
2030 let secret = tempfile::tempdir().expect("secret");
2031 fs::write(secret.path().join("flag.txt"), "secret").expect("write secret");
2032
2033 let ws_sub = workspace.path().join("sub");
2034 fs::create_dir_all(&ws_sub).expect("mkdir sub");
2035 fs::write(ws_sub.join("ok.txt"), "ok").expect("write ok");
2036
2037 let trusted_child = trusted.path().join("child");
2038 fs::create_dir_all(&trusted_child).expect("mkdir child");
2039 fs::write(trusted_child.join("ok.txt"), "ok").expect("write trusted ok");
2040
2041 let trusted_canon = trusted.path().canonicalize().expect("canon trusted");
2042 let ctx =
2043 ToolContext::new(workspace.path()).with_trusted_external_paths(vec![trusted_canon.clone()]);
2044
2045 let ws_plan = resolve_dir_open_plan(&ctx, "sub").await.expect("plan ws");
2046 fs::remove_dir_all(&ws_sub).expect("remove sub");
2047 std::os::unix::fs::symlink(secret.path(), &ws_sub).expect("swap ws symlink");
2048 let ws_err = list_dir_from_plan(&ws_plan, None)
2049 .expect_err("swapped workspace dir symlink must be refused");
2050 assert!(
2051 matches!(ws_err, ToolError::PermissionDenied { .. }),
2052 "{ws_err:?}"
2053 );
2054
2055 let outside_plan = resolve_dir_open_plan(&ctx, &trusted_canon.join("child").to_string_lossy())
2056 .await
2057 .expect("plan outside");
2058 fs::remove_dir_all(&trusted_child).expect("remove child");
2059 std::os::unix::fs::symlink(secret.path(), &trusted_child).expect("swap outside symlink");
2060 let outside_err = list_dir_from_plan(&outside_plan, None)
2061 .expect_err("swapped outside dir symlink must be refused");
2062 assert!(
2063 matches!(outside_err, ToolError::PermissionDenied { .. }),
2064 "{outside_err:?}"
2065 );
2066
2067 let cancel = CancellationToken::new();
2068 cancel.cancel();
2069 let cancel_err = list_dir_from_plan(&outside_plan, Some(&cancel))
2070 .expect_err("cancelled outside plan must fail");
2071 assert!(
2072 matches!(cancel_err, ToolError::Cancelled { .. }),
2073 "{cancel_err:?}"
2074 );
2075 }
2076
2077 #[allow(clippy::await_holding_lock)]
2078 #[tokio::test]
2079 async fn non_strict_write_and_edit_refuse_credential_and_denied_pre_reads() {
2080 let _env_lock = crate::test_support::lock_test_env();
2081 let workspace = tempfile::tempdir().expect("workspace");
2082 let ws_canon = workspace.path().canonicalize().expect("canon ws");
2083 let cw_home = ws_canon.join("cw-home");
2084 fs::create_dir_all(&cw_home).expect("mkdir cw-home");
2085 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
2086 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
2087 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
2088
2089 let config_file = cw_home.join("config.toml");
2090 let config_original = "api_key = \"sk-secret\"\n";
2091 fs::write(&config_file, config_original).expect("write config");
2092 let env_file = ws_canon.join(".env");
2093 let env_original = "SECRET=topsecret\n";
2094 fs::write(&env_file, env_original).expect("write .env");
2095
2096 let trusted_ctx = ToolContext::new(&ws_canon).with_trust_mode(true);
2097 trusted_ctx.note_file_read(&config_file);
2098 trusted_ctx.note_file_read(&env_file);
2099
2100 for target in [
2101 config_file.to_string_lossy().to_string(),
2102 ".env".to_string(),
2103 ] {
2104 let write_err = WriteFileTool
2105 .execute(
2106 json!({"path": &target, "content": "overwritten\n"}),
2107 &trusted_ctx,
2108 )
2109 .await
2110 .expect_err("write_file must refuse protected target");
2111 assert!(
2112 matches!(write_err, ToolError::PermissionDenied { .. }),
2113 "{target}: {write_err:?}"
2114 );
2115
2116 let contract_write_err = WriteFileTool::execute_contract_write(
2117 json!({"path": &target, "content": "overwritten\n"}),
2118 &trusted_ctx,
2119 )
2120 .await
2121 .expect_err("contract write must refuse protected target");
2122 assert!(
2123 matches!(contract_write_err, ToolError::PermissionDenied { .. }),
2124 "{target}: {contract_write_err:?}"
2125 );
2126
2127 let edit_err = EditFileTool
2128 .execute(
2129 json!({"path": &target, "search": "secret", "replace": "hacked"}),
2130 &trusted_ctx,
2131 )
2132 .await
2133 .expect_err("edit_file must refuse protected target");
2134 assert!(
2135 matches!(edit_err, ToolError::PermissionDenied { .. }),
2136 "{target}: {edit_err:?}"
2137 );
2138
2139 let contract_edit_err = EditFileTool::execute_contract_edits(
2140 json!({"path": &target, "edits": [{"oldText": "secret", "newText": "hacked"}]}),
2141 &trusted_ctx,
2142 )
2143 .await
2144 .expect_err("contract edit must refuse protected target");
2145 assert!(
2146 matches!(contract_edit_err, ToolError::PermissionDenied { .. }),
2147 "{target}: {contract_edit_err:?}"
2148 );
2149 }
2150
2151 let default_ctx = ToolContext::new(&ws_canon);
2152 default_ctx.note_file_read(&config_file);
2153 default_ctx.note_file_read(&env_file);
2154 for target in ["cw-home/config.toml", ".env"] {
2155 let confined_err = WriteFileTool
2156 .execute(
2157 json!({"path": target, "content": "overwritten\n"}),
2158 &default_ctx,
2159 )
2160 .await
2161 .expect_err("confined write_file must refuse existing protected target");
2162 assert!(
2163 matches!(confined_err, ToolError::PermissionDenied { .. }),
2164 "{target}: {confined_err:?}"
2165 );
2166 let confined_contract_err = WriteFileTool::execute_contract_write(
2167 json!({"path": target, "content": "overwritten\n"}),
2168 &default_ctx,
2169 )
2170 .await
2171 .expect_err("confined contract write must refuse existing protected target");
2172 assert!(
2173 matches!(confined_contract_err, ToolError::PermissionDenied { .. }),
2174 "{target}: {confined_contract_err:?}"
2175 );
2176 }
2177
2178 assert_eq!(
2179 fs::read_to_string(&config_file).expect("read config"),
2180 config_original
2181 );
2182 assert_eq!(
2183 fs::read_to_string(&env_file).expect("read .env"),
2184 env_original
2185 );
2186
2187 WriteFileTool
2188 .execute(
2189 json!({"path": "fresh/notes.txt", "content": "hello\n"}),
2190 &trusted_ctx,
2191 )
2192 .await
2193 .expect("non-strict write_file creates new file");
2194 WriteFileTool::execute_contract_write(
2195 json!({"path": "fresh/contract.txt", "content": "world\n"}),
2196 &trusted_ctx,
2197 )
2198 .await
2199 .expect("non-strict contract write creates new file");
2200 let editable = ws_canon.join("editable.txt");
2201 fs::write(&editable, "alpha\nbeta\n").expect("write editable");
2202 trusted_ctx.note_file_read(&editable);
2203 EditFileTool
2204 .execute(
2205 json!({"path": "editable.txt", "search": "alpha", "replace": "ALPHA"}),
2206 &trusted_ctx,
2207 )
2208 .await
2209 .expect("non-strict edit_file succeeds");
2210 EditFileTool::execute_contract_edits(
2211 json!({"path": "editable.txt", "edits": [{"oldText": "beta", "newText": "BETA"}]}),
2212 &trusted_ctx,
2213 )
2214 .await
2215 .expect("non-strict contract edit succeeds");
2216 assert_eq!(
2217 fs::read_to_string(&editable).expect("read editable"),
2218 "ALPHA\nBETA\n"
2219 );
2220 }
2221
2222 #[allow(clippy::await_holding_lock)]
2223 #[tokio::test]
2224 async fn write_allows_brand_new_dotenv_while_refusing_missing_credentials_and_contract_links() {
2225 let _env_lock = crate::test_support::lock_test_env();
2226 let workspace = tempfile::tempdir().expect("workspace");
2227 let ws_canon = workspace.path().canonicalize().expect("canon ws");
2228 let cw_home = ws_canon.join("cw-home");
2229 fs::create_dir_all(&cw_home).expect("mkdir cw-home");
2230 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
2231 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
2232 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
2233
2234 let missing_config = cw_home.join("config.toml");
2235 let default_ctx = ToolContext::new(&ws_canon);
2236 let trusted_ctx = ToolContext::new(&ws_canon).with_trust_mode(true);
2237
2238 for (ctx, target) in [
2239 (&default_ctx, "cw-home/config.toml".to_string()),
2240 (&trusted_ctx, missing_config.to_string_lossy().to_string()),
2241 ] {
2242 let w_err = WriteFileTool
2243 .execute(json!({"path": &target, "content": "hijack = true\n"}), ctx)
2244 .await
2245 .expect_err("write_file must refuse missing CODEWHALE_HOME/config.toml");
2246 assert!(
2247 matches!(w_err, ToolError::PermissionDenied { .. }),
2248 "{target}: {w_err:?}"
2249 );
2250 let cw_err = WriteFileTool::execute_contract_write(
2251 json!({"path": &target, "content": "hijack = true\n"}),
2252 ctx,
2253 )
2254 .await
2255 .expect_err("contract write must refuse missing CODEWHALE_HOME/config.toml");
2256 assert!(
2257 matches!(cw_err, ToolError::PermissionDenied { .. }),
2258 "{target}: {cw_err:?}"
2259 );
2260 }
2261 assert!(!missing_config.exists());
2262
2263 for ctx in [&default_ctx, &trusted_ctx] {
2264 let hash_err = WriteFileTool
2265 .execute(
2266 json!({"path": ".env", "content": "NEW=1\n", "expected_hash": "sha256:deadbeef"}),
2267 ctx,
2268 )
2269 .await
2270 .expect_err("expected_hash on missing .env must fail closed with PermissionDenied");
2271 assert!(
2272 matches!(hash_err, ToolError::PermissionDenied { .. }),
2273 "{hash_err:?}"
2274 );
2275 }
2276
2277 let env_ws_1 = tempfile::tempdir().expect("env_ws_1");
2278 let env_ctx_1 = ToolContext::new(env_ws_1.path()).with_trust_mode(true);
2279 WriteFileTool::execute_contract_write(
2280 json!({"path": ".env", "content": "CREATED_CONTRACT=1\n"}),
2281 &env_ctx_1,
2282 )
2283 .await
2284 .expect("non-strict contract write creates brand-new .env");
2285 assert_eq!(
2286 fs::read_to_string(env_ws_1.path().join(".env")).expect("read created .env"),
2287 "CREATED_CONTRACT=1\n"
2288 );
2289 let overwrite_1 = WriteFileTool::execute_contract_write(
2290 json!({"path": ".env", "content": "OVERWRITTEN=1\n"}),
2291 &env_ctx_1,
2292 )
2293 .await
2294 .expect_err("non-strict contract write must refuse existing .env");
2295 assert!(
2296 matches!(overwrite_1, ToolError::PermissionDenied { .. }),
2297 "{overwrite_1:?}"
2298 );
2299 assert_eq!(
2300 fs::read_to_string(env_ws_1.path().join(".env")).expect("unchanged .env"),
2301 "CREATED_CONTRACT=1\n"
2302 );
2303
2304 let env_ws_2 = tempfile::tempdir().expect("env_ws_2");
2305 let env_ctx_2 = ToolContext::new(env_ws_2.path()).with_trust_mode(true);
2306 WriteFileTool
2307 .execute(
2308 json!({"path": ".env", "content": "CREATED_LEGACY=1\n"}),
2309 &env_ctx_2,
2310 )
2311 .await
2312 .expect("non-strict write_file creates brand-new .env");
2313 assert_eq!(
2314 fs::read_to_string(env_ws_2.path().join(".env")).expect("read created .env"),
2315 "CREATED_LEGACY=1\n"
2316 );
2317 let overwrite_2 = WriteFileTool
2318 .execute(
2319 json!({"path": ".env", "content": "OVERWRITTEN=1\n"}),
2320 &env_ctx_2,
2321 )
2322 .await
2323 .expect_err("non-strict write_file must refuse existing .env");
2324 assert!(
2325 matches!(overwrite_2, ToolError::PermissionDenied { .. }),
2326 "{overwrite_2:?}"
2327 );
2328 assert_eq!(
2329 fs::read_to_string(env_ws_2.path().join(".env")).expect("unchanged .env"),
2330 "CREATED_LEGACY=1\n"
2331 );
2332
2333 #[cfg(unix)]
2334 {
2335 let outside = tempfile::tempdir().expect("outside");
2336 let outside_secret = outside.path().join("secret.txt");
2337 fs::write(&outside_secret, "outside\n").expect("write outside");
2338
2339 let original = ws_canon.join("orig.txt");
2340 let hardlinked = ws_canon.join("hardlinked.txt");
2341 fs::write(&original, "hello\n").expect("write orig");
2342 fs::hard_link(&original, &hardlinked).expect("hardlink");
2343
2344 let edit_hl_err = EditFileTool::execute_contract_edits(
2345 json!({"path": "hardlinked.txt", "edits": [{"oldText": "hello", "newText": "bye"}]}),
2346 &default_ctx,
2347 )
2348 .await
2349 .expect_err("contract edit must refuse hardlink with PermissionDenied");
2350 assert!(
2351 matches!(edit_hl_err, ToolError::PermissionDenied { .. }),
2352 "{edit_hl_err:?}"
2353 );
2354
2355 let write_hl_err = WriteFileTool::execute_contract_write(
2356 json!({"path": "hardlinked.txt", "content": "bye\n"}),
2357 &trusted_ctx,
2358 )
2359 .await
2360 .expect_err("non-strict contract write must refuse hardlink with PermissionDenied");
2361 assert!(
2362 matches!(write_hl_err, ToolError::PermissionDenied { .. }),
2363 "{write_hl_err:?}"
2364 );
2365
2366 let swap_file = ws_canon.join("swap.txt");
2367 fs::write(&swap_file, "ok\n").expect("write swap");
2368 let swap_plan = resolve_read_open_plan(&default_ctx, "swap.txt", "edit", false, false)
2369 .await
2370 .expect("plan swap");
2371 fs::remove_file(&swap_file).expect("remove swap");
2372 std::os::unix::fs::symlink(&outside_secret, &swap_file).expect("symlink swap");
2373 let swap_err = load_contract_source(swap_plan, true, &default_ctx)
2374 .await
2375 .expect_err("swapped leaf symlink must fail with PermissionDenied");
2376 assert!(
2377 matches!(swap_err, ToolError::PermissionDenied { .. }),
2378 "{swap_err:?}"
2379 );
2380
2381 let swap_dir = ws_canon.join("swap_dir");
2382 fs::create_dir(&swap_dir).expect("mkdir swap_dir");
2383 fs::write(swap_dir.join("secret.txt"), "ok\n").expect("write swap_dir file");
2384 let dir_plan =
2385 resolve_read_open_plan(&default_ctx, "swap_dir/secret.txt", "edit", false, false)
2386 .await
2387 .expect("plan swap_dir");
2388 fs::remove_dir_all(&swap_dir).expect("remove swap_dir");
2389 std::os::unix::fs::symlink(outside.path(), &swap_dir).expect("symlink swap_dir");
2390 let dir_err = load_contract_source(dir_plan, true, &default_ctx)
2391 .await
2392 .expect_err("swapped parent dir symlink must fail with PermissionDenied");
2393 assert!(
2394 matches!(dir_err, ToolError::PermissionDenied { .. }),
2395 "{dir_err:?}"
2396 );
2397 }
2398 }
2399
2399 lines RUST