返回 CodeWhale
apply_patch.rs
根目录 / crates / engine / src / tools / apply_patch.rs
1 //! Patch tools: `apply_patch` for unified diff patching
2 //!
3 //! This tool provides precise file modifications using unified diff format,
4 //! supporting multi-hunk patches and fuzzy matching.
5
6 use std::collections::HashSet;
7 use std::fs;
8 use std::path::{Path, PathBuf};
9
10 use async_trait::async_trait;
11 use codewhale_tools::param_alias::{PATH_ALIASES, apply_param_aliases};
12 use codewhale_tools::patch_preflight::{
13 ApplyPatchPreflight, ApplyPatchPreflightKind, FilePatch, Hunk, HunkLine,
14 NormalizedApplyPatchInput, format_file_list, normalize_apply_patch_input,
15 preflight_apply_patch_plan, push_unique,
16 };
17 use serde::{Deserialize, Serialize};
18 use serde_json::{Value, json};
19 use thiserror::Error;
20
21 use super::diff_format::make_unified_diff;
22 use super::file::{EXPECTED_HASH_DESCRIPTION, PATCH_PARAMS, content_hash};
23 use super::rust_format::normalize_edit;
24 use super::spec::{
25 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
26 optional_bool, optional_str, optional_u64,
27 };
28 use super::syntax_check::guard_edit;
29
30 /// Maximum lines of context for fuzzy matching (increased for better tolerance)
31 const MAX_FUZZ: usize = 50;
32 /// Default fuzz when the caller does not specify one. Matches the tool schema's
33 /// documented default. Previously the default was `MAX_FUZZ` (50), so a hunk
34 /// with no `fuzz` argument could silently apply up to 50 lines from its stated
35 /// position — landing in the wrong region of a file with repeated blocks.
36 const DEFAULT_FUZZ: usize = 3;
37
38 /// Minimum number of expected lines (context + removed) required before a hunk
39 /// may be relocated to a unique whole-file context match when its stated line
40 /// numbers are stale (#5003). Short anchors — a lone `}` or a 1-2 line snippet
41 /// — appear in too many places to relocate safely.
42 const MIN_ANCHOR_LINES: usize = 4;
43
44 /// Reassemble hunk-processed logical lines back into file content, preserving
45 /// the base file's line-ending style (CRLF vs LF) and its trailing-newline
46 /// state. Processing round-trips through `str::lines()`, which strips both the
47 /// trailing `\n` and any `\r`; naively `join("\n")`-ing would silently delete
48 /// the file's final newline and flip a CRLF file to LF on every patch.
49 fn reassemble_preserving_newlines(lines: &[String], base_content: &str) -> String {
50 if lines.is_empty() {
51 return String::new();
52 }
53 let terminator = if base_content.contains("\r\n") {
54 "\r\n"
55 } else {
56 "\n"
57 };
58 // A newly created file (empty base) gets a conventional trailing newline;
59 // an existing file preserves whether it had one.
60 let trailing = base_content.is_empty() || base_content.ends_with('\n');
61 let mut out = lines.join(terminator);
62 if trailing {
63 out.push_str(terminator);
64 }
65 out
66 }
67 /// Limit how much context we print in error messages.
68 const HUNK_PREVIEW_LINES: usize = 4;
69 const SNIPPET_RADIUS: usize = 2;
70
71 // === Types ===
72
73 /// Result of applying a patch
74 #[derive(Debug, Clone, Serialize, Deserialize)]
75 pub struct PatchResult {
76 pub success: bool,
77 pub files_applied: usize,
78 pub files_total: usize,
79 pub hunks_applied: usize,
80 pub hunks_total: usize,
81 pub fuzz_used: usize,
82 #[serde(default)]
83 pub hunks_with_fuzz: usize,
84 #[serde(default, skip_serializing_if = "is_zero")]
85 pub hunks_relocated: usize,
86 #[serde(default, skip_serializing_if = "Vec::is_empty")]
87 pub touched_files: Vec<String>,
88 #[serde(default, skip_serializing_if = "Vec::is_empty")]
89 pub file_summaries: Vec<FileSummary>,
90 pub message: String,
91 }
92
93 /// Per-file summary for patch application output.
94 #[derive(Debug, Clone, Serialize, Deserialize)]
95 pub struct FileSummary {
96 pub path: String,
97 pub hunks: usize,
98 pub hunks_applied: usize,
99 pub fuzz_used: usize,
100 pub hunks_with_fuzz: usize,
101 #[serde(default, skip_serializing_if = "is_zero")]
102 pub hunks_relocated: usize,
103 pub created: bool,
104 pub deleted: bool,
105 }
106
107 /// Tool for applying unified diff patches to files
108 pub struct ApplyPatchTool;
109
110 #[derive(Debug, Clone)]
111 struct PendingWrite {
112 path: PathBuf,
113 content: Option<String>,
114 original: Option<String>,
115 }
116
117 #[derive(Debug, Default, Clone, Copy)]
118 struct PatchStats {
119 files_applied: usize,
120 files_total: usize,
121 hunks_applied: usize,
122 hunks_total: usize,
123 fuzz_used: usize,
124 hunks_with_fuzz: usize,
125 hunks_relocated: usize,
126 }
127
128 fn is_zero(value: &usize) -> bool {
129 *value == 0
130 }
131
132 #[derive(Debug, Default, Clone)]
133 struct PatchStatsExt {
134 stats: PatchStats,
135 touched_files: Vec<String>,
136 file_summaries: Vec<FileSummary>,
137 header_path_mismatch: Option<String>,
138 }
139
140 #[derive(Debug, Default, Clone, Copy)]
141 struct HunkApplyStats {
142 hunks_applied: usize,
143 fuzz_used: usize,
144 hunks_with_fuzz: usize,
145 hunks_relocated: usize,
146 }
147
148 /// Result of applying a single hunk: how much positional fuzz was used, and
149 /// whether the hunk had to be relocated to a unique whole-file context match
150 /// (stale line numbers after earlier edits, #5003).
151 #[derive(Debug, Default, Clone, Copy)]
152 struct HunkApplyOutcome {
153 fuzz_used: usize,
154 relocated: bool,
155 }
156
157 // === Errors ===
158
159 #[derive(Debug, Error)]
160 enum ApplyHunkError {
161 #[error(
162 "Failed to find matching location for hunk (expected at line {expected_line}, adjusted to {adjusted_line} with offset {offset:+})"
163 )]
164 NoMatch {
165 expected_line: usize,
166 adjusted_line: usize,
167 offset: isize,
168 },
169 #[error(
170 "Hunk context is ambiguous: matches at multiple locations {candidate_lines:?}, expected around line {expected_line}"
171 )]
172 ContextAmbiguous {
173 expected_line: usize,
174 candidate_lines: Vec<usize>,
175 },
176 }
177
178 #[async_trait]
179 impl ToolSpec for ApplyPatchTool {
180 fn name(&self) -> &'static str {
181 "apply_patch"
182 }
183
184 fn model_visible(&self) -> bool {
185 true
186 }
187
188 fn description(&self) -> &'static str {
189 "Apply a transactional unified-diff patch across one or more files, with fuzzy context matching and a rendered diff."
190 }
191
192 fn input_schema(&self) -> Value {
193 json!({
194 "type": "object",
195 "properties": {
196 "path": {
197 "type": "string",
198 "description": "Path to the file to patch (relative to workspace)"
199 },
200 "patch": {
201 "type": "string",
202 "description": "Unified diff patch content. Pass exactly one of `patch` or `replace`."
203 },
204 "replace": {
205 "type": "array",
206 "description": "Full file replacements (path + content); use instead of `patch`.",
207 "items": {
208 "type": "object",
209 "properties": {
210 "path": { "type": "string" },
211 "content": { "type": "string" }
212 },
213 "required": ["path", "content"]
214 }
215 },
216 "fuzz": {
217 "type": "integer",
218 "description": "Maximum fuzz factor for fuzzy matching (default: 3)"
219 },
220 "create_if_missing": {
221 "type": "boolean",
222 "description": "Create the file if it doesn't exist (for new file patches)"
223 },
224 "expected_hash": {
225 "type": "string",
226 "description": format!(
227 "{EXPECTED_HASH_DESCRIPTION} Verifies the patch target — the `path` argument when given, otherwise the first file the patch touches; other files in a multi-file patch are not hash-checked."
228 )
229 }
230 }
231 })
232 }
233
234 fn capabilities(&self) -> Vec<ToolCapability> {
235 vec![
236 ToolCapability::WritesFiles,
237 ToolCapability::Sandboxable,
238 ToolCapability::RequiresApproval,
239 ]
240 }
241
242 fn approval_requirement(&self) -> ApprovalRequirement {
243 ApprovalRequirement::Suggest
244 }
245
246 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
247 let mut input = input;
248 apply_param_aliases(&mut input, PATH_ALIASES, "File patch")?;
249 PATCH_PARAMS.reject_unknown(&input)?;
250 let input = input;
251
252 let fuzz = optional_u64(&input, "fuzz", DEFAULT_FUZZ as u64)?.min(MAX_FUZZ as u64);
253 let fuzz = usize::try_from(fuzz).unwrap_or(DEFAULT_FUZZ);
254 let normalized = normalize_apply_patch_input(&input)?;
255 let create_if_missing = optional_bool(&input, "create_if_missing", false)?;
256 let preflight = preflight_apply_patch_plan(&input, normalized)?;
257 verify_patch_expected_hash(&input, &preflight.summary, context).await?;
258
259 if let NormalizedApplyPatchInput::Replacement {
260 entries,
261 source_field,
262 } = normalized
263 {
264 let entries = entries.to_vec();
265 let build_context = context.clone();
266 let (mut pending, stats) = patch_blocking(move || {
267 build_pending_writes_from_replace(&entries, source_field, &build_context)
268 })
269 .await?;
270 normalize_pending_rust(&mut pending).await;
271 let pending = apply_pending_writes_blocking(pending).await?;
272 for entry in pending.iter().filter(|p| p.content.is_some()) {
273 context.note_file_read(&entry.path);
274 }
275 let result = PatchResult {
276 success: true,
277 files_applied: stats.stats.files_applied,
278 files_total: stats.stats.files_total,
279 hunks_applied: stats.stats.hunks_applied,
280 hunks_total: stats.stats.hunks_total,
281 fuzz_used: stats.stats.fuzz_used,
282 hunks_with_fuzz: stats.stats.hunks_with_fuzz,
283 hunks_relocated: stats.stats.hunks_relocated,
284 touched_files: stats.touched_files.clone(),
285 file_summaries: stats.file_summaries.clone(),
286 message: build_summary_message(&stats),
287 };
288 let tool_result = ToolResult::json(&result)
289 .map_err(|e| ToolError::execution_failed(e.to_string()))?
290 .with_metadata(apply_patch_result_metadata(
291 &preflight.summary,
292 &pending,
293 &stats,
294 ));
295 return Ok(tool_result);
296 }
297
298 let file_patches = match preflight.kind {
299 ApplyPatchPreflightKind::Replace => {
300 unreachable!("replace input returned before patch execution")
301 }
302 ApplyPatchPreflightKind::PathOverride {
303 path,
304 hunks,
305 creates_new_file,
306 } => vec![FilePatch {
307 path,
308 hunks,
309 delete_after: false,
310 create_if_missing,
311 creates_new_file,
312 }],
313 ApplyPatchPreflightKind::FilePatches(file_patches) => file_patches,
314 };
315
316 let build_context = context.clone();
317 let (mut pending, mut stats) = patch_blocking(move || {
318 build_pending_writes_from_patches(file_patches, &build_context, fuzz)
319 })
320 .await?;
321 stats.header_path_mismatch = preflight.summary.header_path_mismatch.clone();
322 normalize_pending_rust(&mut pending).await;
323 let pending = apply_pending_writes_blocking(pending).await?;
324 for entry in pending.iter().filter(|p| p.content.is_some()) {
325 context.note_file_read(&entry.path);
326 }
327 let result = PatchResult {
328 success: true,
329 files_applied: stats.stats.files_applied,
330 files_total: stats.stats.files_total,
331 hunks_applied: stats.stats.hunks_applied,
332 hunks_total: stats.stats.hunks_total,
333 fuzz_used: stats.stats.fuzz_used,
334 hunks_with_fuzz: stats.stats.hunks_with_fuzz,
335 hunks_relocated: stats.stats.hunks_relocated,
336 touched_files: stats.touched_files.clone(),
337 file_summaries: stats.file_summaries.clone(),
338 message: build_summary_message(&stats),
339 };
340 let tool_result = ToolResult::json(&result)
341 .map_err(|e| ToolError::execution_failed(e.to_string()))?
342 .with_metadata(apply_patch_result_metadata(
343 &preflight.summary,
344 &pending,
345 &stats,
346 ));
347 Ok(tool_result)
348 }
349 }
350
351 /// Enforce the optional `expected_hash` precondition for a patch (#3979).
352 ///
353 /// **This is a whole-patch precondition on a single target file, not a per-file
354 /// guard.** A unified diff carries no place to attach a hash per file section,
355 /// and `File action="patch"` flattens its arguments into one object, so there
356 /// is no clean parameter shape for a hash-per-path map without inventing a
357 /// syntax the model has never seen. The guarded file is therefore the patch's
358 /// target: the explicit `path` argument when one is given, otherwise the first
359 /// file the patch touches. A multi-file patch still verifies only that one
360 /// file; for the rest, the existing hunk-context matching remains the check
361 /// that a stale patch fails on.
362 ///
363 /// Runs before any pending write is built or applied, so a mismatch leaves
364 /// every file in the patch untouched.
365 async fn verify_patch_expected_hash(
366 input: &Value,
367 summary: &ApplyPatchPreflight,
368 context: &ToolContext,
369 ) -> Result<(), ToolError> {
370 let Some(expected) = optional_str(input, "expected_hash")? else {
371 return Ok(());
372 };
373
374 let Some(target) = summary
375 .path_override
376 .as_deref()
377 .or_else(|| summary.touched_files.first().map(String::as_str))
378 else {
379 return Err(ToolError::execution_failed(
380 "File `patch` refused: expected_hash was supplied but the patch names no target file to verify it against, so nothing was written.".to_string(),
381 ));
382 };
383
384 let plan =
385 crate::tools::file::resolve_read_open_plan(context, target, "apply_patch", false, false)
386 .await?;
387 let target_owned = target.to_string();
388 let Some(current) = patch_blocking(move || -> Result<Option<Vec<u8>>, ToolError> {
389 use std::io::Read as _;
390 let Some((mut file, _fd_path)) =
391 crate::tools::file::open_verified_read_handle(&plan, true, true, false)?
392 else {
393 return Ok(None);
394 };
395 let mut bytes = Vec::new();
396 file.read_to_end(&mut bytes).map_err(|e| {
397 ToolError::execution_failed(format!(
398 "File `patch` refused: could not read {target_owned} to verify expected_hash ({e}); nothing was written."
399 ))
400 })?;
401 Ok(Some(bytes))
402 })
403 .await?
404 else {
405 return Err(ToolError::execution_failed(format!(
406 "File `patch` refused: expected_hash was supplied but {target} does not exist, so there is no snapshot to verify and nothing was written. Recovery: drop `expected_hash` when creating files."
407 )));
408 };
409 let actual = content_hash(&current);
410 if actual == expected {
411 return Ok(());
412 }
413 Err(ToolError::execution_failed(format!(
414 "File `patch` refused: {target} changed since it was read. \
415 expected_hash was {expected} but the file is now {actual}, so nothing was written. \
416 Recovery: call read with path=\"{target}\" to get the current contents \
417 and its content_hash, then rebuild the patch against them."
418 )))
419 }
420
421 fn apply_patch_result_metadata(
422 preflight: &ApplyPatchPreflight,
423 pending: &[PendingWrite],
424 stats: &PatchStatsExt,
425 ) -> Value {
426 let mut metadata =
427 serde_json::to_value(preflight).expect("ApplyPatchPreflight should serialize");
428 if let Some(object) = metadata.as_object_mut() {
429 object.insert("event".to_string(), json!("apply_patch.preflight"));
430 object.insert(
431 "mutation".to_string(),
432 build_mutation_metadata(pending, &stats.file_summaries),
433 );
434 }
435 metadata
436 }
437
438 /// Preserve the exact applied before/after diff independently from approval
439 /// presentation. The TUI consumes this success-only metadata for its calm
440 /// File receipt; the normal model-facing result remains compact JSON.
441 fn build_mutation_metadata(pending: &[PendingWrite], summaries: &[FileSummary]) -> Value {
442 let mut matched = HashSet::new();
443 let mut renames = Vec::new();
444
445 for (delete_index, (deleted, delete_summary)) in pending.iter().zip(summaries).enumerate() {
446 if !delete_summary.deleted || matched.contains(&delete_index) {
447 continue;
448 }
449 let Some(old_content) = deleted.original.as_deref() else {
450 continue;
451 };
452 let Some((create_index, (created, create_summary))) = pending
453 .iter()
454 .zip(summaries)
455 .enumerate()
456 .find(|(index, (created, summary))| {
457 !matched.contains(index)
458 && summary.created
459 && created.content.as_deref() == Some(old_content)
460 })
461 else {
462 continue;
463 };
464 matched.insert(delete_index);
465 matched.insert(create_index);
466 // The destination's bytes are the ones this call wrote, so a rename
467 // carries the same size/sha256 facts as a created or updated file.
468 let mut rename = json!({
469 "from": delete_summary.path,
470 "to": create_summary.path,
471 });
472 if let Some(content) = created.content.as_deref() {
473 rename["size"] = json!(content.len());
474 rename["sha256"] = json!(codewhale_runtime::hashing::sha256_hex(content.as_bytes()));
475 }
476 renames.push(rename);
477 }
478
479 let mut files = Vec::new();
480 for (index, summary) in summaries.iter().enumerate() {
481 if matched.contains(&index) {
482 continue;
483 }
484 let outcome = if summary.created {
485 "created"
486 } else if summary.deleted {
487 "deleted"
488 } else {
489 "updated"
490 };
491 // Deleted entries carry neither size nor sha256: no bytes were written.
492 let written = pending
493 .get(index)
494 .and_then(|write| write.content.as_deref())
495 .filter(|_| !summary.deleted)
496 .map(str::as_bytes);
497 files.push(crate::tools::file::mutation_file_entry(
498 &summary.path,
499 outcome,
500 written,
501 ));
502 }
503
504 let mut diff_parts = Vec::new();
505 for rename in &renames {
506 let from = rename["from"].as_str().unwrap_or("<file>");
507 let to = rename["to"].as_str().unwrap_or("<file>");
508 diff_parts.push(format!(
509 "diff --git a/{from} b/{to}\nsimilarity index 100%\nrename from {from}\nrename to {to}\n"
510 ));
511 }
512 for (index, (write, summary)) in pending.iter().zip(summaries).enumerate() {
513 if matched.contains(&index) {
514 continue;
515 }
516 let old = write.original.as_deref().unwrap_or("");
517 let new = write.content.as_deref().unwrap_or("");
518 let diff = make_unified_diff(&summary.path, old, new);
519 if !diff.is_empty() {
520 diff_parts.push(format!(
521 "diff --git a/{path} b/{path}\n{diff}",
522 path = summary.path
523 ));
524 }
525 }
526
527 json!({
528 "diff": diff_parts.join("\n"),
529 "files": files,
530 "renames": renames,
531 })
532 }
533
534 fn build_summary_message(stats: &PatchStatsExt) -> String {
535 let mut parts = Vec::new();
536 if stats.stats.hunks_total > 0 {
537 parts.push(format!(
538 "Applied {}/{} hunks across {} file(s).",
539 stats.stats.hunks_applied, stats.stats.hunks_total, stats.stats.files_applied
540 ));
541 } else {
542 parts.push(format!(
543 "Applied {} file change(s).",
544 stats.stats.files_applied
545 ));
546 }
547
548 if !stats.touched_files.is_empty() {
549 parts.push(format!(
550 "Files: {}.",
551 format_file_list(&stats.touched_files)
552 ));
553 }
554
555 if stats.stats.fuzz_used > 0 {
556 parts.push(format!(
557 "Fuzz used on {} hunk(s) (total fuzz: {}).",
558 stats.stats.hunks_with_fuzz, stats.stats.fuzz_used
559 ));
560 }
561
562 if stats.stats.hunks_relocated > 0 {
563 parts.push(format!(
564 "{} hunk(s) applied with stale line numbers (auto-relocated to unique context).",
565 stats.stats.hunks_relocated
566 ));
567 }
568
569 if let Some(note) = stats.header_path_mismatch.as_deref() {
570 parts.push(note.to_string());
571 }
572
573 parts.join(" ")
574 }
575
576 fn build_pending_writes_from_replace(
577 changes: &[Value],
578 source_field: &str,
579 context: &ToolContext,
580 ) -> Result<(Vec<PendingWrite>, PatchStatsExt), ToolError> {
581 let mut pending = Vec::new();
582 let mut stats = PatchStatsExt::default();
583 for change in changes {
584 let path = change
585 .get("path")
586 .and_then(Value::as_str)
587 .ok_or_else(|| ToolError::missing_field(format!("{source_field}[].path")))?;
588 let content = change
589 .get("content")
590 .and_then(Value::as_str)
591 .ok_or_else(|| ToolError::missing_field(format!("{source_field}[].content")))?;
592
593 let plan =
594 crate::tools::file::resolve_write_preread_plan_sync(context, path, "apply_patch")?;
595 let resolved = plan.file_path.clone();
596 let original = read_optional_verified_file_content(&plan, Some((context, path)))?;
597 let created = original.is_none();
598
599 pending.push(PendingWrite {
600 path: resolved,
601 content: Some(content.to_string()),
602 original,
603 });
604
605 stats.stats.files_total += 1;
606 stats.stats.files_applied += 1;
607 push_unique(&mut stats.touched_files, path.to_string());
608 stats.file_summaries.push(FileSummary {
609 path: path.to_string(),
610 hunks: 0,
611 hunks_applied: 0,
612 fuzz_used: 0,
613 hunks_with_fuzz: 0,
614 hunks_relocated: 0,
615 created,
616 deleted: false,
617 });
618 }
619
620 Ok((pending, stats))
621 }
622
623 fn build_pending_writes_from_patches(
624 file_patches: Vec<FilePatch>,
625 context: &ToolContext,
626 fuzz: usize,
627 ) -> Result<(Vec<PendingWrite>, PatchStatsExt), ToolError> {
628 let mut pending: Vec<PendingWrite> = Vec::new();
629 // Where each file's write already sits in `pending`: a second section for
630 // the same file applies on top of the first instead of re-reading the
631 // disk and silently dropping the earlier hunks (B7).
632 let mut pending_index: std::collections::HashMap<PathBuf, usize> =
633 std::collections::HashMap::new();
634 let mut stats = PatchStatsExt::default();
635 stats.stats.files_total = file_patches.len();
636
637 for file_patch in file_patches {
638 if file_patch.hunks.is_empty() {
639 return Err(ToolError::invalid_input(format!(
640 "Patch section for `{}` has no hunks (`@@ ... @@`).",
641 file_patch.path
642 )));
643 }
644
645 let plan = if file_patch.create_if_missing || file_patch.creates_new_file {
646 crate::tools::file::resolve_write_preread_plan_sync(
647 context,
648 &file_patch.path,
649 "apply_patch",
650 )?
651 } else {
652 crate::tools::file::resolve_read_open_plan_sync(
653 context,
654 &file_patch.path,
655 "apply_patch",
656 false,
657 )?
658 };
659 let resolved = plan.file_path.clone();
660 if let Some(&index) = pending_index.get(&resolved) {
661 let Some(current) = pending[index].content.clone() else {
662 return Err(ToolError::invalid_input(format!(
663 "Patch has a section for `{}` after a section that deletes it; merge them into one section.",
664 file_patch.path
665 )));
666 };
667 if file_patch.creates_new_file && !current.is_empty() {
668 return Err(file_already_exists_error(&file_patch.path, &resolved));
669 }
670 let mut lines: Vec<String> = current.lines().map(String::from).collect();
671 let apply_stats =
672 apply_hunks_to_lines(&mut lines, &file_patch.hunks, fuzz, &file_patch.path)?;
673 if file_patch.delete_after {
674 ensure_delete_consumes_file(&lines, &file_patch.path)?;
675 }
676 stats.stats.hunks_applied += apply_stats.hunks_applied;
677 stats.stats.hunks_total += file_patch.hunks.len();
678 stats.stats.fuzz_used += apply_stats.fuzz_used;
679 stats.stats.hunks_with_fuzz += apply_stats.hunks_with_fuzz;
680 stats.stats.hunks_relocated += apply_stats.hunks_relocated;
681 if let Some(summary) = stats
682 .file_summaries
683 .iter_mut()
684 .rev()
685 .find(|summary| summary.path == file_patch.path)
686 {
687 summary.hunks += file_patch.hunks.len();
688 summary.hunks_applied += apply_stats.hunks_applied;
689 summary.fuzz_used += apply_stats.fuzz_used;
690 summary.hunks_with_fuzz += apply_stats.hunks_with_fuzz;
691 summary.hunks_relocated += apply_stats.hunks_relocated;
692 summary.deleted |= file_patch.delete_after;
693 summary.created &= !file_patch.delete_after;
694 }
695 pending[index].content = (!file_patch.delete_after)
696 .then(|| reassemble_preserving_newlines(&lines, &current));
697 // One file, however many sections: count it once.
698 stats.stats.files_total = stats.stats.files_total.saturating_sub(1);
699 continue;
700 }
701 let original = read_optional_verified_file_content(&plan, None)?;
702
703 if original.is_none() && !file_patch.create_if_missing {
704 return Err(ToolError::execution_failed(format!(
705 "File `{}` does not exist at `{}`. Set create_if_missing=true for new files or include headers for file creation.",
706 file_patch.path,
707 resolved.display(),
708 )));
709 }
710
711 if file_patch.delete_after && original.is_none() {
712 return Err(ToolError::execution_failed(format!(
713 "File `{}` does not exist at `{}` to delete.",
714 file_patch.path,
715 resolved.display(),
716 )));
717 }
718
719 // A `--- /dev/null` section has no old lines to anchor on, so on an
720 // existing file it would splice the "new" content onto the top of
721 // the old one and report success. `git apply` refuses this too.
722 if file_patch.creates_new_file && original.as_deref().is_some_and(|c| !c.is_empty()) {
723 return Err(file_already_exists_error(&file_patch.path, &resolved));
724 }
725
726 let base_content = original.clone().unwrap_or_default();
727 let mut lines: Vec<String> = if base_content.is_empty() {
728 Vec::new()
729 } else {
730 base_content.lines().map(String::from).collect()
731 };
732
733 let apply_stats =
734 apply_hunks_to_lines(&mut lines, &file_patch.hunks, fuzz, &file_patch.path)?;
735 if file_patch.delete_after {
736 ensure_delete_consumes_file(&lines, &file_patch.path)?;
737 }
738 stats.stats.hunks_applied += apply_stats.hunks_applied;
739 stats.stats.hunks_total += file_patch.hunks.len();
740 stats.stats.fuzz_used += apply_stats.fuzz_used;
741 stats.stats.hunks_with_fuzz += apply_stats.hunks_with_fuzz;
742 stats.stats.hunks_relocated += apply_stats.hunks_relocated;
743 stats.stats.files_applied += 1;
744 push_unique(&mut stats.touched_files, file_patch.path.clone());
745 stats.file_summaries.push(FileSummary {
746 path: file_patch.path.clone(),
747 hunks: file_patch.hunks.len(),
748 hunks_applied: apply_stats.hunks_applied,
749 fuzz_used: apply_stats.fuzz_used,
750 hunks_with_fuzz: apply_stats.hunks_with_fuzz,
751 hunks_relocated: apply_stats.hunks_relocated,
752 created: original.is_none() && !file_patch.delete_after,
753 deleted: file_patch.delete_after,
754 });
755
756 pending_index.insert(resolved.clone(), pending.len());
757 if file_patch.delete_after {
758 pending.push(PendingWrite {
759 path: resolved,
760 content: None,
761 original,
762 });
763 } else {
764 let new_content = reassemble_preserving_newlines(&lines, &base_content);
765 pending.push(PendingWrite {
766 path: resolved,
767 content: Some(new_content),
768 original,
769 });
770 }
771 }
772
773 Ok((pending, stats))
774 }
775
776 fn file_already_exists_error(label: &str, resolved: &Path) -> ToolError {
777 ToolError::execution_failed(format!(
778 "Patch creates `{label}` (`--- /dev/null`), but it already exists at `{}`. Nothing was changed. To change the existing file, send a patch with context lines from its current contents; to replace it wholesale, use a write/replace action.",
779 resolved.display(),
780 ))
781 }
782
783 /// A `+++ /dev/null` section deletes the file, so its hunks must remove every
784 /// line. Deleting after a partial match would silently drop the rest.
785 fn ensure_delete_consumes_file(remaining: &[String], label: &str) -> Result<(), ToolError> {
786 if remaining.is_empty() {
787 return Ok(());
788 }
789 Err(ToolError::execution_failed(format!(
790 "Patch deletes `{label}` (`+++ /dev/null`), but its hunks leave {} line(s) of the file unaccounted for. Nothing was changed. Include every line of the file as `-` lines to delete it, or send a patch with a real `+++` path to edit it.",
791 remaining.len(),
792 )))
793 }
794
795 /// Normalize the Rust files a patch rewrites (#6205), before the write and
796 /// before the result's diff is built, so the rendered diff and the bytes on
797 /// disk are the same text and the model's next anchor matches reality.
798 async fn normalize_pending_rust(pending: &mut [PendingWrite]) {
799 for entry in pending.iter_mut() {
800 let (Some(content), Some(original)) = (entry.content.as_ref(), entry.original.as_ref())
801 else {
802 continue;
803 };
804 if let Some(normalized) = normalize_edit(&entry.path, original, content).await {
805 entry.content = Some(normalized);
806 }
807 }
808 }
809
810 /// Run the patch's synchronous file work (reads, the syntax gate, writes and
811 /// rollback) on the blocking pool rather than an async worker (#6559 D01-06).
812 async fn patch_blocking<T: Send + 'static>(
813 work: impl FnOnce() -> Result<T, ToolError> + Send + 'static,
814 ) -> Result<T, ToolError> {
815 tokio::task::spawn_blocking(work)
816 .await
817 .map_err(|error| ToolError::execution_failed(format!("patch task failed: {error}")))?
818 }
819
820 /// [`apply_pending_writes`] on the blocking pool, handing `pending` back for
821 /// the result's diagnostics and metadata.
822 async fn apply_pending_writes_blocking(
823 pending: Vec<PendingWrite>,
824 ) -> Result<Vec<PendingWrite>, ToolError> {
825 patch_blocking(move || apply_pending_writes(&pending).map(|()| pending)).await
826 }
827
828 fn apply_pending_writes(pending: &[PendingWrite]) -> Result<(), ToolError> {
829 // Syntax gate (#6204) ahead of the first write, not per file: a patch is
830 // transactional, so one unparseable result must leave every file in the
831 // patch untouched rather than half-applied and rolled back.
832 for entry in pending {
833 if let Some(content) = entry.content.as_ref() {
834 let display = entry.path.display().to_string();
835 guard_edit(&entry.path, &display, entry.original.as_deref(), content)?;
836 }
837 }
838
839 let mut applied = Vec::new();
840
841 for entry in pending {
842 let result = if let Some(content) = entry.content.as_ref() {
843 let parent_result = if let Some(parent) = entry.path.parent() {
844 fs::create_dir_all(parent).map_err(|e| {
845 ToolError::execution_failed(format!(
846 "Failed to create directory {}: {}",
847 parent.display(),
848 e
849 ))
850 })
851 } else {
852 Ok(())
853 };
854
855 parent_result.and_then(|()| {
856 codewhale_util::utils::write_atomic_workspace(&entry.path, content.as_bytes())
857 .map_err(|e| {
858 ToolError::execution_failed(format!(
859 "Failed to write {}: {}",
860 entry.path.display(),
861 e
862 ))
863 })
864 })
865 } else if entry.path.exists() {
866 fs::remove_file(&entry.path).map_err(|e| {
867 ToolError::execution_failed(format!(
868 "Failed to delete {}: {}",
869 entry.path.display(),
870 e
871 ))
872 })
873 } else {
874 Ok(())
875 };
876
877 if let Err(err) = result {
878 let failures = rollback_pending_writes(&applied);
879 if failures.is_empty() {
880 return Err(err);
881 }
882 // A failed restore leaves the patch partly applied; say which
883 // files still hold it rather than implying nothing changed.
884 return Err(ToolError::execution_failed(format!(
885 "{err}. Rolling back the files already written also failed, so the patch is \
886 partly applied: {}",
887 failures.join("; ")
888 )));
889 }
890
891 applied.push(entry.clone());
892 }
893
894 Ok(())
895 }
896
897 /// Restore every already-applied entry, newest first. Returns one line per
898 /// entry that could not be restored (#6559 D01-06: these were discarded).
899 fn rollback_pending_writes(applied: &[PendingWrite]) -> Vec<String> {
900 let mut failures = Vec::new();
901 for entry in applied.iter().rev() {
902 let restored = match entry.original.as_ref() {
903 Some(content) => {
904 codewhale_util::utils::write_atomic_workspace(&entry.path, content.as_bytes())
905 }
906 None => match fs::remove_file(&entry.path) {
907 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
908 other => other,
909 },
910 };
911 if let Err(error) = restored {
912 failures.push(format!("{} ({error})", entry.path.display()));
913 }
914 }
915 failures
916 }
917
918 fn read_optional_verified_file_content(
919 plan: &crate::tools::file::ReadOpenPlan,
920 require_fresh: Option<(&ToolContext, &str)>,
921 ) -> Result<Option<String>, ToolError> {
922 use std::io::Read as _;
923
924 let Some((mut file, _fd_path)) =
925 crate::tools::file::open_verified_read_handle(plan, true, true, false)?
926 else {
927 return Ok(None);
928 };
929 if let Some((context, raw_path)) = require_fresh {
930 context.require_fresh_read_before_write(&plan.file_path, raw_path)?;
931 }
932 let mut bytes = Vec::new();
933 file.read_to_end(&mut bytes).map_err(|e| {
934 ToolError::execution_failed(format!(
935 "Failed to read {}: {}",
936 plan.file_path.display(),
937 e
938 ))
939 })?;
940 let content = String::from_utf8(bytes).map_err(|e| {
941 ToolError::execution_failed(format!(
942 "Failed to read {}: {}",
943 plan.file_path.display(),
944 e
945 ))
946 })?;
947 Ok(Some(content))
948 }
949
950 fn preview_expected_lines(hunk: &Hunk, limit: usize) -> Vec<String> {
951 let mut preview = Vec::new();
952 for line in hunk.lines.iter().filter_map(|line| match line {
953 HunkLine::Context(s) => Some((" ", s)),
954 HunkLine::Remove(s) => Some(("-", s)),
955 HunkLine::Add(_) => None,
956 }) {
957 if preview.len() >= limit {
958 break;
959 }
960 preview.push(format!(" {}{}", line.0, line.1));
961 }
962 if preview.is_empty() {
963 preview.push(" <no context lines in hunk>".to_string());
964 }
965 preview
966 }
967
968 fn snippet_around(lines: &[String], line_1_based: usize, radius: usize) -> Vec<String> {
969 if lines.is_empty() {
970 return vec![" <empty file>".to_string()];
971 }
972
973 let center = line_1_based
974 .saturating_sub(1)
975 .min(lines.len().saturating_sub(1));
976 let start = center.saturating_sub(radius);
977 let end = (center + radius).min(lines.len().saturating_sub(1));
978
979 lines[start..=end]
980 .iter()
981 .enumerate()
982 .map(|(idx, line)| {
983 let line_no = start + idx + 1;
984 format!(" {line_no:>4}: {line}")
985 })
986 .collect()
987 }
988
989 fn format_hunk_no_match_error(
990 lines: &[String],
991 hunk: &Hunk,
992 err: &ApplyHunkError,
993 max_fuzz: usize,
994 ) -> String {
995 match err {
996 ApplyHunkError::NoMatch {
997 expected_line,
998 adjusted_line,
999 offset,
1000 } => {
1001 let expected_preview = preview_expected_lines(hunk, HUNK_PREVIEW_LINES).join("\n");
1002 let file_preview = snippet_around(lines, *adjusted_line, SNIPPET_RADIUS).join("\n");
1003 format!(
1004 "could not find matching context near line {expected_line} (searched around line {adjusted_line} with offset {offset:+} and fuzz up to {max_fuzz}). Expected context preview:\n{expected_preview}\nFile snippet near line {adjusted_line}:\n{file_preview}\nHints: the line numbers may be stale after earlier edits — call File with action=\"read\" to re-check the current contents, ensure the patch matches the file, increase `fuzz`, or regenerate the patch."
1005 )
1006 }
1007 ApplyHunkError::ContextAmbiguous {
1008 expected_line,
1009 candidate_lines,
1010 } => {
1011 let candidates = candidate_lines
1012 .iter()
1013 .map(|line| line.to_string())
1014 .collect::<Vec<_>>()
1015 .join(", ");
1016 format!(
1017 "could not find matching context near line {expected_line}: the hunk's context appears at multiple locations (lines {candidates}), and the line numbers may be stale after earlier edits, so it is not safe to relocate automatically. Hints: call File with action=\"read\" to inspect the candidate locations above, then regenerate the patch with more surrounding context lines that uniquely identify the target block."
1018 )
1019 }
1020 }
1021 }
1022
1023 fn apply_hunks_to_lines(
1024 lines: &mut Vec<String>,
1025 hunks: &[Hunk],
1026 fuzz: usize,
1027 file_label: &str,
1028 ) -> Result<HunkApplyStats, ToolError> {
1029 let mut stats = HunkApplyStats::default();
1030 let mut cumulative_offset: isize = 0;
1031
1032 for (idx, hunk) in hunks.iter().enumerate() {
1033 match apply_hunk(lines, hunk, fuzz, &mut cumulative_offset) {
1034 Ok(outcome) => {
1035 stats.hunks_applied += 1;
1036 if outcome.fuzz_used > 0 {
1037 stats.fuzz_used += outcome.fuzz_used;
1038 stats.hunks_with_fuzz += 1;
1039 }
1040 if outcome.relocated {
1041 stats.hunks_relocated += 1;
1042 }
1043 }
1044 Err(e) => {
1045 let detail = format_hunk_no_match_error(lines, hunk, &e, fuzz);
1046 return Err(ToolError::execution_failed(format!(
1047 "Failed to apply hunk {}/{} for `{}`: {}",
1048 idx + 1,
1049 hunks.len(),
1050 file_label,
1051 detail
1052 )));
1053 }
1054 }
1055 }
1056
1057 Ok(stats)
1058 }
1059
1060 /// Apply a hunk to the file content with fuzzy matching
1061 fn apply_hunk(
1062 lines: &mut Vec<String>,
1063 hunk: &Hunk,
1064 max_fuzz: usize,
1065 cumulative_offset: &mut isize,
1066 ) -> Result<HunkApplyOutcome, ApplyHunkError> {
1067 // Build expected old lines from hunk
1068 let old_lines: Vec<&str> = hunk
1069 .lines
1070 .iter()
1071 .filter_map(|line| match line {
1072 HunkLine::Context(s) | HunkLine::Remove(s) => Some(s.as_str()),
1073 HunkLine::Add(_) => None,
1074 })
1075 .collect();
1076
1077 // Build new lines from hunk
1078 let new_lines: Vec<String> = hunk
1079 .lines
1080 .iter()
1081 .filter_map(|line| match line {
1082 HunkLine::Context(s) | HunkLine::Add(s) => Some(s.clone()),
1083 HunkLine::Remove(_) => None,
1084 })
1085 .collect();
1086
1087 // Try to find the location with fuzzy matching
1088 // Apply cumulative offset from previous hunks, clamping to valid range.
1089 // A pure insertion (`@@ -N,0 +M,K @@`, as `git diff -U0` emits) names
1090 // the line it follows, so it goes *after* line N, not before it. Only a
1091 // header that says `,0` qualifies: an omitted or nonzero old count keeps
1092 // the "before line N" anchor. `new_start` settles the common hand-written
1093 // `@@ -N,0 +N,K @@` ("new text starts at line N"): when it points at
1094 // line N itself rather than after it, the text goes before line N.
1095 let pure_insertion = hunk.old_count == 0 && old_lines.is_empty();
1096 let starts_at_named_line = hunk.new_start > 0
1097 && cumulative_offset
1098 .checked_neg()
1099 .and_then(|back| (hunk.new_start - 1).checked_add_signed(back))
1100 == Some(hunk.old_start.saturating_sub(1));
1101 let base_idx = if pure_insertion && !starts_at_named_line {
1102 hunk.old_start
1103 } else {
1104 hunk.old_start.saturating_sub(1)
1105 };
1106 // Use checked_add_signed to safely handle negative offsets without
1107 // risking isize overflow on adversarial input.
1108 let start_idx = base_idx
1109 .checked_add_signed(*cumulative_offset)
1110 .unwrap_or(0)
1111 .min(lines.len());
1112
1113 for fuzz in 0..=max_fuzz {
1114 // Try at exact position first, then nearby
1115 let search_range = if fuzz == 0 {
1116 vec![start_idx]
1117 } else {
1118 let min = start_idx.saturating_sub(fuzz);
1119 let max = (start_idx + fuzz).min(lines.len());
1120 (min..=max).collect()
1121 };
1122
1123 for pos in search_range {
1124 if matches_at_position(lines, &old_lines, pos) {
1125 // Apply the hunk
1126 let end_pos = pos + old_lines.len();
1127 lines.splice(pos..end_pos, new_lines.clone());
1128
1129 // Update cumulative offset: new lines added minus old lines removed
1130 let delta = new_lines.len() as isize - old_lines.len() as isize;
1131 *cumulative_offset += delta;
1132
1133 return Ok(HunkApplyOutcome {
1134 fuzz_used: fuzz,
1135 relocated: false,
1136 });
1137 }
1138 }
1139 }
1140
1141 // Special case: adding to empty file or new hunk at end
1142 if old_lines.is_empty() && (lines.is_empty() || start_idx >= lines.len()) {
1143 let delta = new_lines.len() as isize;
1144 lines.extend(new_lines);
1145 *cumulative_offset += delta;
1146 return Ok(HunkApplyOutcome {
1147 fuzz_used: 0,
1148 relocated: false,
1149 });
1150 }
1151
1152 // #5003 — positional search failed. The line numbers are probably stale
1153 // because an earlier edit (this patch or a previous one) shifted the file
1154 // and the model regenerated the patch from outdated read_file output.
1155 // If the hunk carries enough anchor lines, look for a unique whole-file
1156 // content match and relocate there; anything that matched within `fuzz`
1157 // of `start_idx` was already tried above, so any unique match found here
1158 // is genuinely relocated. Ambiguous matches are refused (applying to the
1159 // wrong copy of a repeated block would corrupt the file).
1160 let anchor_matches: Vec<usize> = if old_lines.len() >= MIN_ANCHOR_LINES {
1161 (0..=lines.len().saturating_sub(old_lines.len()))
1162 .filter(|&pos| matches_at_position(lines, &old_lines, pos))
1163 .collect()
1164 } else {
1165 Vec::new()
1166 };
1167 match anchor_matches.as_slice() {
1168 [pos] => {
1169 let end_pos = pos + old_lines.len();
1170 lines.splice(*pos..end_pos, new_lines.clone());
1171 let delta = new_lines.len() as isize - old_lines.len() as isize;
1172 *cumulative_offset += delta;
1173 Ok(HunkApplyOutcome {
1174 fuzz_used: 0,
1175 relocated: true,
1176 })
1177 }
1178 [] => Err(ApplyHunkError::NoMatch {
1179 expected_line: hunk.old_start,
1180 adjusted_line: start_idx + 1, // Convert back to 1-indexed
1181 offset: *cumulative_offset,
1182 }),
1183 multiple => Err(ApplyHunkError::ContextAmbiguous {
1184 expected_line: hunk.old_start,
1185 candidate_lines: multiple.iter().map(|&p| p + 1).collect(),
1186 }),
1187 }
1188 }
1189
1190 /// Check if `old_lines` match at the given position
1191 fn matches_at_position(lines: &[String], old_lines: &[&str], pos: usize) -> bool {
1192 if pos + old_lines.len() > lines.len() {
1193 return false;
1194 }
1195
1196 for (i, old_line) in old_lines.iter().enumerate() {
1197 // Normalize whitespace for comparison
1198 let file_line = lines[pos + i].trim_end();
1199 let expected = old_line.trim_end();
1200 if file_line != expected {
1201 return false;
1202 }
1203 }
1204
1205 true
1206 }
1207
1208 // === Unit Tests ===
1209
1210 #[cfg(test)]
1211 mod tests {
1212 use super::*;
1213 use codewhale_tools::patch_preflight::{
1214 parse_range, parse_unified_diff, preflight_apply_patch,
1215 };
1216 use tempfile::tempdir;
1217
1218 /// #6559 D01-06: a rollback that cannot restore a file used to be
1219 /// discarded, so the error read as if nothing had changed. Deleting `x`
1220 /// and creating `x/y.txt` leaves a directory at `x`; when the third write
1221 /// fails, restoring the file `x` over that directory fails too.
1222 #[test]
1223 fn failed_rollback_is_reported_as_a_partly_applied_patch() {
1224 let tmp = tempdir().expect("tempdir");
1225 let root = tmp.path();
1226 fs::write(root.join("x"), "original\n").expect("seed x");
1227 fs::write(root.join("blocker"), "a file, not a directory\n").expect("seed blocker");
1228 let pending = vec![
1229 PendingWrite {
1230 path: root.join("x"),
1231 content: None,
1232 original: Some("original\n".to_string()),
1233 },
1234 PendingWrite {
1235 path: root.join("x").join("y.txt"),
1236 content: Some("new\n".to_string()),
1237 original: None,
1238 },
1239 PendingWrite {
1240 path: root.join("blocker").join("z.txt"),
1241 content: Some("never written\n".to_string()),
1242 original: None,
1243 },
1244 ];
1245
1246 let message = apply_pending_writes(&pending)
1247 .expect_err("the third write cannot create its directory")
1248 .to_string();
1249
1250 assert!(message.contains("partly applied"), "{message}");
1251 assert!(
1252 message.contains(&root.join("x").display().to_string()),
1253 "{message}"
1254 );
1255 }
1256
1257 /// The receipt entry a created/updated file must carry: its size and
1258 /// SHA-256 are those of the bytes now on disk.
1259 fn on_disk_receipt(root: &std::path::Path, path: &str, outcome: &str) -> Value {
1260 let bytes = fs::read(root.join(path)).expect("receipt target exists");
1261 json!({
1262 "path": path,
1263 "outcome": outcome,
1264 "size": bytes.len(),
1265 "sha256": codewhale_runtime::hashing::sha256_hex(&bytes),
1266 })
1267 }
1268
1269 fn parse_patch_result(result: ToolResult) -> PatchResult {
1270 serde_json::from_str(&result.content).expect("patch result json")
1271 }
1272
1273 #[test]
1274 fn test_parse_range() {
1275 assert_eq!(parse_range("10,5").unwrap(), (10, 5));
1276 assert_eq!(parse_range("10").unwrap(), (10, 1));
1277 assert_eq!(parse_range("1,0").unwrap(), (1, 0));
1278 }
1279
1280 #[test]
1281 fn test_parse_unified_diff() {
1282 let patch = r"--- a/test.txt
1283 +++ b/test.txt
1284 @@ -1,3 +1,3 @@
1285 line1
1286 -line2
1287 +modified line2
1288 line3
1289 ";
1290
1291 let hunks = parse_unified_diff(patch).unwrap();
1292 assert_eq!(hunks.len(), 1);
1293 assert_eq!(hunks[0].old_start, 1);
1294 assert_eq!(hunks[0].old_count, 3);
1295 assert_eq!(hunks[0].new_start, 1);
1296 assert_eq!(hunks[0].new_count, 3);
1297 }
1298
1299 #[test]
1300 fn parse_unified_diff_keeps_lines_past_an_undercounted_header() {
1301 let patch = "--- a/t\n+++ b/t\n@@ -1,1 +1,1 @@\n-a\n+b\n c\n d\n+e\n";
1302 let hunks = parse_unified_diff(patch).unwrap();
1303 assert_eq!(hunks[0].lines.len(), 5);
1304
1305 let huge = format!("--- a/t\n+++ b/t\n@@ -1,{} +1,1 @@\n-a\n+b\n", usize::MAX);
1306 assert_eq!(parse_unified_diff(&huge).unwrap()[0].lines.len(), 2);
1307 }
1308
1309 /// #6205 — a patch that lands unformatted Rust in an already-clean file is
1310 /// normalized before the write, and the rendered diff shows the normalized
1311 /// text, so the model's next patch context matches the bytes on disk.
1312 #[tokio::test]
1313 async fn patch_normalizes_rust_in_an_already_clean_file() {
1314 let tmp = tempdir().expect("tempdir");
1315 let ctx = ToolContext::new(tmp.path().to_path_buf());
1316 let file = tmp.path().join("clean.rs");
1317 fs::write(&file, "fn main() {\n let x = 1;\n}\n").expect("write");
1318
1319 let patch = "--- a/clean.rs\n+++ b/clean.rs\n@@ -1,3 +1,4 @@\n fn main() {\n let x = 1;\n+ let y=2;\n }\n";
1320 let result = ApplyPatchTool
1321 .execute(json!({"path": "clean.rs", "patch": patch}), &ctx)
1322 .await
1323 .expect("execute");
1324
1325 assert_eq!(
1326 fs::read_to_string(&file).expect("read"),
1327 "fn main() {\n let x = 1;\n let y = 2;\n}\n"
1328 );
1329 let diff = result.metadata.as_ref().expect("metadata")["mutation"]["diff"]
1330 .as_str()
1331 .expect("diff")
1332 .to_string();
1333 assert!(diff.contains("+ let y = 2;"), "{diff}");
1334 assert!(!diff.contains("let y=2;"), "{diff}");
1335 }
1336
1337 /// #6204 — a patch whose result does not parse is refused before any file
1338 /// is written, so a multi-file patch cannot land half-applied.
1339 #[tokio::test]
1340 async fn patch_refuses_a_hunk_that_breaks_rust_syntax() {
1341 let tmp = tempdir().expect("tempdir");
1342 let ctx = ToolContext::new(tmp.path().to_path_buf());
1343 let file = tmp.path().join("main.rs");
1344 let original = "fn main() {\n println!(\"hi\");\n}\n";
1345 fs::write(&file, original).expect("write");
1346
1347 let patch = "--- a/main.rs\n+++ b/main.rs\n@@ -1,3 +1,2 @@\n fn main() {\n println!(\"hi\");\n-}\n";
1348 let error = ApplyPatchTool
1349 .execute(json!({"path": "main.rs", "patch": patch}), &ctx)
1350 .await
1351 .expect_err("a patch that breaks Rust syntax must be refused");
1352
1353 let message = error.to_string();
1354 assert!(message.contains("Rust syntax error at line"), "{message}");
1355 assert_eq!(
1356 fs::read_to_string(&file).expect("read"),
1357 original,
1358 "a refused patch must leave the file untouched"
1359 );
1360 }
1361
1362 #[test]
1363 fn input_schema_exposes_replace_without_top_level_combinators() {
1364 let schema = ApplyPatchTool.input_schema();
1365
1366 assert_eq!(schema["properties"]["replace"]["type"], "array");
1367 assert!(schema["properties"].get("changes").is_none());
1368 assert!(schema.get("oneOf").is_none(), "{schema}");
1369 }
1370
1371 #[test]
1372 fn test_preflight_apply_patch_with_path_override() {
1373 let patch = r"@@ -1,2 +1,2 @@
1374 old
1375 -value
1376 +new-value
1377 ";
1378
1379 let preflight = preflight_apply_patch(&json!({
1380 "path": "src/lib.rs",
1381 "patch": patch
1382 }))
1383 .expect("preflight");
1384
1385 assert_eq!(preflight.touched_files, vec!["src/lib.rs"]);
1386 assert_eq!(preflight.files_total, 1);
1387 assert_eq!(preflight.hunks_total, 1);
1388 assert_eq!(preflight.path_override.as_deref(), Some("src/lib.rs"));
1389 }
1390
1391 #[test]
1392 fn test_preflight_apply_patch_multi_file_create_and_delete() {
1393 let patch = r"diff --git a/new.rs b/new.rs
1394 --- /dev/null
1395 +++ b/new.rs
1396 @@ -0,0 +1 @@
1397 +fn added() {}
1398 diff --git a/old.rs b/old.rs
1399 --- a/old.rs
1400 +++ /dev/null
1401 @@ -1 +0,0 @@
1402 -fn old() {}
1403 ";
1404
1405 let preflight = preflight_apply_patch(&json!({ "patch": patch })).expect("preflight");
1406
1407 assert_eq!(preflight.touched_files, vec!["new.rs", "old.rs"]);
1408 assert_eq!(preflight.files_total, 2);
1409 assert_eq!(preflight.hunks_total, 2);
1410 assert_eq!(preflight.creates, vec!["new.rs"]);
1411 assert_eq!(preflight.deletes, vec!["old.rs"]);
1412 }
1413
1414 #[test]
1415 fn test_preflight_apply_patch_timestamp_headers_strip_metadata() {
1416 let patch = "diff --git a/src/lib.rs b/src/lib.rs\n\
1417 --- a/src/lib.rs\t2026-06-26 10:00:00 +0000\n\
1418 +++ b/src/lib.rs\t2026-06-26 10:01:00 +0000\n\
1419 @@ -1,1 +1,1 @@\n\
1420 -old\n\
1421 +new\n";
1422
1423 let preflight = preflight_apply_patch(&json!({ "patch": patch })).expect("preflight");
1424
1425 assert_eq!(preflight.touched_files, vec!["src/lib.rs"]);
1426 assert_eq!(preflight.files_total, 1);
1427 assert_eq!(preflight.hunks_total, 1);
1428 }
1429
1430 #[test]
1431 fn test_preflight_apply_patch_ignores_forged_headers_inside_hunk_shape() {
1432 let patch = r"--- a/src/lib.rs
1433 +++ b/src/lib.rs
1434 @@ -1,3 +1,3 @@
1435 line1
1436 --- a/forged.rs
1437 +++ b/forged.rs
1438 line3
1439 ";
1440
1441 let preflight = preflight_apply_patch(&json!({
1442 "path": "src/lib.rs",
1443 "patch": patch
1444 }))
1445 .expect("preflight");
1446
1447 assert_eq!(preflight.touched_files, vec!["src/lib.rs"]);
1448 assert_eq!(preflight.header_path_mismatch, None);
1449 }
1450
1451 #[test]
1452 fn test_preflight_apply_patch_replace_list() {
1453 let canonical = preflight_apply_patch(&json!({
1454 "replace": [
1455 { "path": "one.txt", "content": "one" },
1456 { "path": "two.txt", "content": "two" }
1457 ]
1458 }))
1459 .expect("preflight");
1460
1461 let legacy = preflight_apply_patch(&json!({
1462 "changes": [
1463 { "path": "one.txt", "content": "one" },
1464 { "path": "two.txt", "content": "two" }
1465 ]
1466 }))
1467 .expect("legacy preflight");
1468
1469 assert_eq!(canonical.touched_files, vec!["one.txt", "two.txt"]);
1470 assert_eq!(canonical.files_total, 2);
1471 assert_eq!(canonical.hunks_total, 0);
1472 assert_eq!(legacy, canonical);
1473 }
1474
1475 #[test]
1476 fn test_preflight_replace_files_total_counts_entries() {
1477 let preflight = preflight_apply_patch(&json!({
1478 "replace": [
1479 { "path": "same.txt", "content": "one" },
1480 { "path": "same.txt", "content": "two" }
1481 ]
1482 }))
1483 .expect("preflight");
1484
1485 assert_eq!(preflight.touched_files, vec!["same.txt"]);
1486 assert_eq!(preflight.files_total, 2);
1487 }
1488
1489 #[test]
1490 fn test_preflight_patch_files_total_counts_sections() {
1491 let patch = r"diff --git a/same.txt b/same.txt
1492 --- a/same.txt
1493 +++ b/same.txt
1494 @@ -1,1 +1,1 @@
1495 -one
1496 +two
1497 diff --git a/same.txt b/same.txt
1498 --- a/same.txt
1499 +++ b/same.txt
1500 @@ -2,1 +2,1 @@
1501 -three
1502 +four
1503 ";
1504
1505 let preflight = preflight_apply_patch(&json!({ "patch": patch })).expect("preflight");
1506
1507 assert_eq!(preflight.touched_files, vec!["same.txt"]);
1508 assert_eq!(preflight.files_total, 2);
1509 assert_eq!(preflight.hunks_total, 2);
1510 }
1511
1512 #[test]
1513 fn test_apply_hunk_simple() {
1514 let mut lines = vec![
1515 "line1".to_string(),
1516 "line2".to_string(),
1517 "line3".to_string(),
1518 ];
1519
1520 let hunk = Hunk {
1521 old_start: 1,
1522 old_count: 3,
1523 new_start: 1,
1524 new_count: 3,
1525 lines: vec![
1526 HunkLine::Context("line1".to_string()),
1527 HunkLine::Remove("line2".to_string()),
1528 HunkLine::Add("modified".to_string()),
1529 HunkLine::Context("line3".to_string()),
1530 ],
1531 };
1532
1533 let mut offset: isize = 0;
1534 let outcome = apply_hunk(&mut lines, &hunk, 0, &mut offset).unwrap();
1535 assert_eq!(outcome.fuzz_used, 0);
1536 assert!(!outcome.relocated);
1537 assert_eq!(lines, vec!["line1", "modified", "line3"]);
1538 }
1539
1540 #[test]
1541 fn test_apply_hunk_with_fuzz() {
1542 let mut lines = vec![
1543 "line0".to_string(),
1544 "line1".to_string(),
1545 "line2".to_string(),
1546 "line3".to_string(),
1547 ];
1548
1549 // Hunk expects to start at line 1, but content is at line 2
1550 let hunk = Hunk {
1551 old_start: 1, // Wrong position
1552 old_count: 2,
1553 new_start: 1,
1554 new_count: 2,
1555 lines: vec![
1556 HunkLine::Remove("line1".to_string()),
1557 HunkLine::Add("modified".to_string()),
1558 HunkLine::Context("line2".to_string()),
1559 ],
1560 };
1561
1562 let mut offset: isize = 0;
1563 let outcome = apply_hunk(&mut lines, &hunk, 3, &mut offset).unwrap();
1564 assert!(outcome.fuzz_used > 0);
1565 assert!(!outcome.relocated);
1566 assert_eq!(lines, vec!["line0", "modified", "line2", "line3"]);
1567 }
1568
1569 #[test]
1570 fn test_apply_hunk_no_match_returns_error() {
1571 let mut lines = vec!["line1".to_string(), "line2".to_string()];
1572 let hunk = Hunk {
1573 old_start: 5,
1574 old_count: 1,
1575 new_start: 5,
1576 new_count: 1,
1577 lines: vec![
1578 HunkLine::Context("missing".to_string()),
1579 HunkLine::Add("new".to_string()),
1580 ],
1581 };
1582
1583 let mut offset: isize = 0;
1584 let err = apply_hunk(&mut lines, &hunk, 0, &mut offset).unwrap_err();
1585 assert!(matches!(
1586 err,
1587 ApplyHunkError::NoMatch {
1588 expected_line: 5,
1589 ..
1590 }
1591 ));
1592 }
1593
1594 #[tokio::test]
1595 async fn test_apply_patch_tool() {
1596 let tmp = tempdir().expect("tempdir");
1597 let ctx = ToolContext::new(tmp.path().to_path_buf());
1598
1599 // Create a test file
1600 fs::write(tmp.path().join("test.txt"), "line1\nline2\nline3\n").expect("write");
1601
1602 let patch = r"--- a/test.txt
1603 +++ b/test.txt
1604 @@ -1,3 +1,3 @@
1605 line1
1606 -line2
1607 +modified
1608 line3
1609 ";
1610
1611 let tool = ApplyPatchTool;
1612 let result = tool
1613 .execute(json!({"path": "test.txt", "patch": patch}), &ctx)
1614 .await
1615 .expect("execute");
1616
1617 assert!(result.success);
1618 assert_eq!(
1619 result.metadata.as_ref().unwrap()["event"],
1620 "apply_patch.preflight"
1621 );
1622 assert_eq!(
1623 result.metadata.as_ref().unwrap()["touched_files"],
1624 json!(["test.txt"])
1625 );
1626 assert!(
1627 result
1628 .metadata
1629 .as_ref()
1630 .unwrap()
1631 .get("header_path_mismatch")
1632 .is_none()
1633 );
1634 assert!(
1635 result
1636 .metadata
1637 .as_ref()
1638 .unwrap()
1639 .get("path_override")
1640 .is_some()
1641 );
1642 let mutation = &result.metadata.as_ref().unwrap()["mutation"];
1643 assert_eq!(
1644 mutation["files"],
1645 json!([on_disk_receipt(tmp.path(), "test.txt", "updated")])
1646 );
1647 assert!(
1648 mutation["diff"]
1649 .as_str()
1650 .is_some_and(|diff| diff.contains("-line2") && diff.contains("+modified")),
1651 "{mutation}"
1652 );
1653 let patch_result = parse_patch_result(result);
1654 assert_eq!(patch_result.touched_files, vec!["test.txt"]);
1655 assert_eq!(patch_result.hunks_applied, 1);
1656
1657 // Verify the patch was applied
1658 let content = fs::read_to_string(tmp.path().join("test.txt")).expect("read");
1659 assert!(content.contains("modified"));
1660 assert!(!content.contains("line2"));
1661 // Regression: the file's trailing newline must survive the patch.
1662 assert!(content.ends_with('\n'), "trailing newline was dropped");
1663 }
1664
1665 #[test]
1666 fn reassemble_preserving_newlines_keeps_style() {
1667 let lines = vec!["a".to_string(), "b".to_string()];
1668 // LF with trailing newline.
1669 assert_eq!(reassemble_preserving_newlines(&lines, "x\ny\n"), "a\nb\n");
1670 // LF without trailing newline.
1671 assert_eq!(reassemble_preserving_newlines(&lines, "x\ny"), "a\nb");
1672 // CRLF is preserved (endings and trailing).
1673 assert_eq!(
1674 reassemble_preserving_newlines(&lines, "x\r\ny\r\n"),
1675 "a\r\nb\r\n"
1676 );
1677 // New/empty file gets a conventional trailing newline.
1678 assert_eq!(reassemble_preserving_newlines(&lines, ""), "a\nb\n");
1679 // Empty result stays empty.
1680 assert_eq!(reassemble_preserving_newlines(&[], "x\n"), "");
1681 }
1682
1683 #[tokio::test]
1684 async fn apply_patch_preserves_crlf_line_endings() {
1685 let tmp = tempdir().expect("tempdir");
1686 let ctx = ToolContext::new(tmp.path().to_path_buf());
1687 fs::write(tmp.path().join("crlf.txt"), "line1\r\nline2\r\nline3\r\n").expect("write");
1688 let patch =
1689 "--- a/crlf.txt\n+++ b/crlf.txt\n@@ -1,3 +1,3 @@\n line1\n-line2\n+modified\n line3\n";
1690 let result = ApplyPatchTool
1691 .execute(json!({"path": "crlf.txt", "patch": patch}), &ctx)
1692 .await
1693 .expect("execute");
1694 assert!(result.success);
1695 let content = fs::read_to_string(tmp.path().join("crlf.txt")).expect("read");
1696 assert!(content.contains("modified"));
1697 // Regression: a CRLF file must not be flipped to LF.
1698 assert!(
1699 content.contains("\r\n"),
1700 "CRLF was flipped to LF: {content:?}"
1701 );
1702 assert!(!content.contains("\n\n"), "spurious bare LF introduced");
1703 assert!(content.ends_with("\r\n"), "trailing CRLF dropped");
1704 }
1705
1706 #[tokio::test]
1707 async fn test_apply_patch_add_lines() {
1708 let tmp = tempdir().expect("tempdir");
1709 let ctx = ToolContext::new(tmp.path().to_path_buf());
1710
1711 fs::write(tmp.path().join("test.txt"), "line1\nline3\n").expect("write");
1712
1713 let patch = r"@@ -1,2 +1,3 @@
1714 line1
1715 +line2
1716 line3
1717 ";
1718
1719 let tool = ApplyPatchTool;
1720 let result = tool
1721 .execute(json!({"path": "test.txt", "patch": patch}), &ctx)
1722 .await
1723 .expect("execute");
1724
1725 assert!(result.success);
1726 let mutation = &result.metadata.as_ref().expect("metadata")["mutation"];
1727 assert_eq!(
1728 mutation["files"],
1729 json!([on_disk_receipt(tmp.path(), "test.txt", "updated")])
1730 );
1731 assert!(
1732 mutation["diff"]
1733 .as_str()
1734 .is_some_and(|diff| diff.contains("+line2")),
1735 "{mutation}"
1736 );
1737 let patch_result = parse_patch_result(result);
1738 assert_eq!(patch_result.touched_files, vec!["test.txt"]);
1739
1740 let content = fs::read_to_string(tmp.path().join("test.txt")).expect("read");
1741 assert!(content.contains("line2"));
1742 }
1743
1744 #[tokio::test]
1745 async fn test_apply_patch_create_new_file() {
1746 let tmp = tempdir().expect("tempdir");
1747 let ctx = ToolContext::new(tmp.path().to_path_buf());
1748
1749 let patch = r"@@ -0,0 +1,3 @@
1750 +line1
1751 +line2
1752 +line3
1753 ";
1754
1755 let tool = ApplyPatchTool;
1756 let result = tool
1757 .execute(
1758 json!({"path": "new_file.txt", "patch": patch, "create_if_missing": true}),
1759 &ctx,
1760 )
1761 .await
1762 .expect("execute");
1763
1764 assert!(result.success);
1765 let mutation = &result.metadata.as_ref().expect("metadata")["mutation"];
1766 assert_eq!(
1767 mutation["files"],
1768 json!([on_disk_receipt(tmp.path(), "new_file.txt", "created")])
1769 );
1770 assert!(
1771 mutation["diff"]
1772 .as_str()
1773 .is_some_and(|diff| diff.contains("+line1")),
1774 "{mutation}"
1775 );
1776 let patch_result = parse_patch_result(result);
1777 assert_eq!(patch_result.touched_files, vec!["new_file.txt"]);
1778 assert!(patch_result.file_summaries.first().unwrap().created);
1779 assert!(tmp.path().join("new_file.txt").exists());
1780 }
1781
1782 #[tokio::test]
1783 async fn test_apply_patch_replace_list() {
1784 let tmp = tempdir().expect("tempdir");
1785 let ctx = ToolContext::new(tmp.path().to_path_buf());
1786
1787 fs::write(tmp.path().join("one.txt"), "old\n").expect("write");
1788 ctx.note_file_read(&ctx.resolve_path("one.txt").expect("resolve"));
1789
1790 let tool = ApplyPatchTool;
1791 let result = tool
1792 .execute(
1793 json!({
1794 "replace": [
1795 { "path": "one.txt", "content": "new\n" },
1796 { "path": "two.txt", "content": "second\n" }
1797 ]
1798 }),
1799 &ctx,
1800 )
1801 .await
1802 .expect("execute");
1803
1804 assert!(result.success);
1805 let metadata = result.metadata.as_ref().expect("metadata");
1806 assert_eq!(metadata["event"], "apply_patch.preflight");
1807 assert_eq!(metadata["touched_files"], json!(["one.txt", "two.txt"]));
1808 assert_eq!(metadata["files_total"], 2);
1809 assert_eq!(metadata["hunks_total"], 0);
1810 assert!(metadata.get("path_override").is_none());
1811 assert_eq!(
1812 metadata["mutation"]["files"],
1813 json!([
1814 on_disk_receipt(tmp.path(), "one.txt", "updated"),
1815 on_disk_receipt(tmp.path(), "two.txt", "created")
1816 ])
1817 );
1818 let mutation_diff = metadata["mutation"]["diff"]
1819 .as_str()
1820 .expect("mutation diff");
1821 assert!(mutation_diff.contains("diff --git a/one.txt b/one.txt"));
1822 assert!(mutation_diff.contains("diff --git a/two.txt b/two.txt"));
1823 assert!(mutation_diff.contains("--- a/one.txt"), "{mutation_diff}");
1824 assert!(mutation_diff.contains("+++ b/two.txt"), "{mutation_diff}");
1825 let patch_result = parse_patch_result(result);
1826 let mut touched = patch_result.touched_files.clone();
1827 touched.sort();
1828 assert_eq!(touched, vec!["one.txt", "two.txt"]);
1829 assert_eq!(patch_result.hunks_total, 0);
1830 assert_eq!(
1831 fs::read_to_string(tmp.path().join("one.txt")).unwrap(),
1832 "new\n"
1833 );
1834 assert_eq!(
1835 fs::read_to_string(tmp.path().join("two.txt")).unwrap(),
1836 "second\n"
1837 );
1838 }
1839
1840 #[tokio::test]
1841 async fn test_apply_patch_legacy_changes_list() {
1842 let tmp = tempdir().expect("tempdir");
1843 let ctx = ToolContext::new(tmp.path().to_path_buf());
1844 fs::write(tmp.path().join("legacy.txt"), "old\n").expect("write");
1845 ctx.note_file_read(&ctx.resolve_path("legacy.txt").expect("resolve"));
1846
1847 let result = ApplyPatchTool
1848 .execute(
1849 json!({
1850 "changes": [
1851 { "path": "legacy.txt", "content": "new\n" }
1852 ]
1853 }),
1854 &ctx,
1855 )
1856 .await
1857 .expect("legacy changes alias should execute");
1858
1859 assert!(result.success);
1860 assert_eq!(
1861 fs::read_to_string(tmp.path().join("legacy.txt")).unwrap(),
1862 "new\n"
1863 );
1864 }
1865
1866 #[tokio::test]
1867 async fn apply_patch_rejects_every_mixed_mode_before_writing() {
1868 let tmp = tempdir().expect("tempdir");
1869 let ctx = ToolContext::new(tmp.path().to_path_buf());
1870 fs::write(tmp.path().join("guard.txt"), "old\n").expect("write");
1871 let patch = "--- a/guard.txt\n+++ b/guard.txt\n@@ -1 +1 @@\n-old\n+patched\n";
1872 let replacement = json!([{
1873 "path": "guard.txt",
1874 "content": "replaced\n"
1875 }]);
1876 let cases = [
1877 (
1878 ["patch", "replace"],
1879 json!({"patch": patch, "replace": replacement.clone()}),
1880 ),
1881 (
1882 ["patch", "changes"],
1883 json!({"patch": patch, "changes": replacement.clone()}),
1884 ),
1885 (
1886 ["replace", "changes"],
1887 json!({
1888 "replace": replacement.clone(),
1889 "changes": replacement.clone()
1890 }),
1891 ),
1892 ];
1893
1894 for (fields, input) in cases {
1895 let err = ApplyPatchTool
1896 .execute(input, &ctx)
1897 .await
1898 .expect_err("mixed modes must be rejected");
1899 let ToolError::InvalidInput { message } = err else {
1900 panic!("mixed modes should be invalid input, got: {err}");
1901 };
1902 assert!(message.contains("simultaneously"), "{message}");
1903 for field in fields {
1904 assert!(message.contains(field), "{message}");
1905 }
1906 assert_eq!(
1907 fs::read_to_string(tmp.path().join("guard.txt")).unwrap(),
1908 "old\n",
1909 "mixed modes must be rejected before the first write"
1910 );
1911 }
1912 }
1913
1914 #[tokio::test]
1915 async fn test_apply_patch_replace_list_rolls_back_on_write_failure() {
1916 let tmp = tempdir().expect("tempdir");
1917 let ctx = ToolContext::new(tmp.path().to_path_buf());
1918
1919 fs::write(tmp.path().join("one.txt"), "old\n").expect("write");
1920 ctx.note_file_read(&ctx.resolve_path("one.txt").expect("resolve"));
1921 fs::write(tmp.path().join("blocked"), "not a dir\n").expect("write blocker");
1922
1923 let tool = ApplyPatchTool;
1924 let err = tool
1925 .execute(
1926 json!({
1927 "replace": [
1928 { "path": "one.txt", "content": "new\n" },
1929 { "path": "blocked/two.txt", "content": "second\n" }
1930 ]
1931 }),
1932 &ctx,
1933 )
1934 .await
1935 .expect_err("second write should fail");
1936
1937 let message = err.to_string();
1938 assert!(message.contains("blocked"), "{message}");
1939 assert_eq!(
1940 fs::read_to_string(tmp.path().join("one.txt")).unwrap(),
1941 "old\n"
1942 );
1943 assert!(!tmp.path().join("blocked").join("two.txt").exists());
1944 }
1945
1946 #[tokio::test]
1947 async fn test_apply_patch_multi_file_diff() {
1948 let tmp = tempdir().expect("tempdir");
1949 let ctx = ToolContext::new(tmp.path().to_path_buf());
1950
1951 fs::write(tmp.path().join("a.txt"), "line1\nline2\n").expect("write");
1952 fs::write(tmp.path().join("b.txt"), "alpha\nbeta\n").expect("write");
1953
1954 let patch = r"diff --git a/a.txt b/a.txt
1955 --- a/a.txt
1956 +++ b/a.txt
1957 @@ -1,2 +1,2 @@
1958 line1
1959 -line2
1960 +line2-mod
1961 diff --git a/b.txt b/b.txt
1962 --- a/b.txt
1963 +++ b/b.txt
1964 @@ -1,2 +1,3 @@
1965 alpha
1966 +beta2
1967 beta
1968 ";
1969
1970 let tool = ApplyPatchTool;
1971 let result = tool
1972 .execute(json!({"patch": patch}), &ctx)
1973 .await
1974 .expect("execute");
1975
1976 assert!(result.success);
1977 let metadata = result.metadata.as_ref().expect("metadata");
1978 assert_eq!(metadata["event"], "apply_patch.preflight");
1979 assert_eq!(metadata["touched_files"], json!(["a.txt", "b.txt"]));
1980 assert_eq!(metadata["files_total"], 2);
1981 assert_eq!(metadata["hunks_total"], 2);
1982 assert!(metadata.get("path_override").is_none());
1983 let patch_result = parse_patch_result(result);
1984 let mut touched = patch_result.touched_files.clone();
1985 touched.sort();
1986 assert_eq!(touched, vec!["a.txt", "b.txt"]);
1987 assert_eq!(patch_result.files_applied, 2);
1988 let a = fs::read_to_string(tmp.path().join("a.txt")).unwrap();
1989 let b = fs::read_to_string(tmp.path().join("b.txt")).unwrap();
1990 assert!(a.contains("line2-mod"));
1991 assert!(b.contains("beta2"));
1992 }
1993
1994 #[tokio::test]
1995 async fn mutation_receipt_covers_delete_rename_and_multifile_outcomes() {
1996 let tmp = tempdir().expect("tempdir");
1997 let ctx = ToolContext::new(tmp.path().to_path_buf());
1998 fs::write(tmp.path().join("old.txt"), "same\n").expect("old");
1999 fs::write(tmp.path().join("update.txt"), "before\n").expect("update");
2000 fs::write(tmp.path().join("delete.txt"), "gone\n").expect("delete");
2001
2002 let patch = r"diff --git a/old.txt b/old.txt
2003 --- a/old.txt
2004 +++ /dev/null
2005 @@ -1 +0,0 @@
2006 -same
2007 diff --git a/new.txt b/new.txt
2008 --- /dev/null
2009 +++ b/new.txt
2010 @@ -0,0 +1 @@
2011 +same
2012 diff --git a/update.txt b/update.txt
2013 --- a/update.txt
2014 +++ b/update.txt
2015 @@ -1 +1 @@
2016 -before
2017 +after
2018 diff --git a/create.txt b/create.txt
2019 --- /dev/null
2020 +++ b/create.txt
2021 @@ -0,0 +1 @@
2022 +fresh
2023 diff --git a/delete.txt b/delete.txt
2024 --- a/delete.txt
2025 +++ /dev/null
2026 @@ -1 +0,0 @@
2027 -gone
2028 ";
2029
2030 let result = ApplyPatchTool
2031 .execute(json!({"patch": patch}), &ctx)
2032 .await
2033 .expect("execute");
2034 let mutation = &result.metadata.as_ref().expect("metadata")["mutation"];
2035 assert_eq!(
2036 mutation["files"],
2037 json!([
2038 on_disk_receipt(tmp.path(), "update.txt", "updated"),
2039 on_disk_receipt(tmp.path(), "create.txt", "created"),
2040 // A deleted entry carries neither size nor sha256.
2041 { "path": "delete.txt", "outcome": "deleted" }
2042 ])
2043 );
2044 // The rename carries the destination's written bytes.
2045 let renamed = fs::read(tmp.path().join("new.txt")).expect("renamed bytes");
2046 assert_eq!(
2047 mutation["renames"],
2048 json!([{
2049 "from": "old.txt",
2050 "to": "new.txt",
2051 "size": renamed.len(),
2052 "sha256": codewhale_runtime::hashing::sha256_hex(&renamed),
2053 }])
2054 );
2055 let exact = mutation["diff"].as_str().expect("exact mutation diff");
2056 assert!(exact.contains("rename from old.txt"), "{exact}");
2057 assert!(exact.contains("rename to new.txt"), "{exact}");
2058 assert!(exact.contains("--- a/update.txt"), "{exact}");
2059 assert!(exact.contains("+++ b/create.txt"), "{exact}");
2060 assert!(exact.contains("--- a/delete.txt"), "{exact}");
2061
2062 assert!(!tmp.path().join("old.txt").exists());
2063 assert_eq!(
2064 fs::read_to_string(tmp.path().join("new.txt")).expect("renamed target"),
2065 "same\n"
2066 );
2067 assert_eq!(
2068 fs::read_to_string(tmp.path().join("update.txt")).expect("updated"),
2069 "after\n"
2070 );
2071 assert!(tmp.path().join("create.txt").exists());
2072 assert!(!tmp.path().join("delete.txt").exists());
2073 }
2074
2075 #[tokio::test]
2076 async fn test_apply_patch_requires_headers_without_path() {
2077 let tmp = tempdir().expect("tempdir");
2078 let ctx = ToolContext::new(tmp.path().to_path_buf());
2079 let tool = ApplyPatchTool;
2080
2081 let patch = r"@@ -1,1 +1,1 @@
2082 -old
2083 +new
2084 ";
2085
2086 let err = tool
2087 .execute(json!({"patch": patch}), &ctx)
2088 .await
2089 .unwrap_err();
2090 match err {
2091 ToolError::InvalidInput { message } => {
2092 assert!(message.contains("no file headers"));
2093 assert!(message.contains("Provide `path`"));
2094 }
2095 other => panic!("expected invalid input, got: {other}"),
2096 }
2097 }
2098
2099 #[tokio::test]
2100 async fn test_path_override_rejects_multi_file_diff() {
2101 let tmp = tempdir().expect("tempdir");
2102 let ctx = ToolContext::new(tmp.path().to_path_buf());
2103 let tool = ApplyPatchTool;
2104
2105 let patch = r"diff --git a/a.txt b/a.txt
2106 --- a/a.txt
2107 +++ b/a.txt
2108 @@ -1,1 +1,1 @@
2109 -one
2110 +one-mod
2111 diff --git a/b.txt b/b.txt
2112 --- a/b.txt
2113 +++ b/b.txt
2114 @@ -1,1 +1,1 @@
2115 -two
2116 +two-mod
2117 ";
2118
2119 let err = tool
2120 .execute(json!({"path": "a.txt", "patch": patch}), &ctx)
2121 .await
2122 .unwrap_err();
2123 match err {
2124 ToolError::InvalidInput { message } => {
2125 assert!(message.contains("multiple files"));
2126 assert!(message.contains("a.txt"));
2127 assert!(message.contains("b.txt"));
2128 }
2129 other => panic!("expected invalid input, got: {other}"),
2130 }
2131 }
2132
2133 #[tokio::test]
2134 async fn test_apply_patch_summary_reports_fuzz() {
2135 let tmp = tempdir().expect("tempdir");
2136 let ctx = ToolContext::new(tmp.path().to_path_buf());
2137 let tool = ApplyPatchTool;
2138
2139 fs::write(tmp.path().join("test.txt"), "line0\nline1\nline2\nline3\n").expect("write");
2140
2141 let patch = r"@@ -1,2 +1,2 @@
2142 -line1
2143 +modified
2144 line2
2145 ";
2146
2147 let result = tool
2148 .execute(json!({"path": "test.txt", "patch": patch, "fuzz": 3}), &ctx)
2149 .await
2150 .expect("execute");
2151 assert!(result.success);
2152 let patch_result = parse_patch_result(result);
2153 assert_eq!(patch_result.hunks_with_fuzz, 1);
2154 assert!(patch_result.fuzz_used > 0);
2155 assert!(patch_result.message.contains("Fuzz used"));
2156 let summary = patch_result.file_summaries.first().unwrap();
2157 assert_eq!(summary.hunks_with_fuzz, 1);
2158 }
2159
2160 #[tokio::test]
2161 async fn test_path_override_header_mismatch_note() {
2162 let tmp = tempdir().expect("tempdir");
2163 let ctx = ToolContext::new(tmp.path().to_path_buf());
2164 let tool = ApplyPatchTool;
2165
2166 fs::write(tmp.path().join("override.txt"), "old\n").expect("write");
2167
2168 let patch = r"--- a/other.txt
2169 +++ b/other.txt
2170 @@ -1,1 +1,1 @@
2171 -old
2172 +new
2173 ";
2174
2175 let result = tool
2176 .execute(json!({"path": "override.txt", "patch": patch}), &ctx)
2177 .await
2178 .expect("execute");
2179 let metadata = result.metadata.as_ref().expect("metadata");
2180 assert!(
2181 metadata["header_path_mismatch"]
2182 .as_str()
2183 .unwrap()
2184 .contains("headers reference `other.txt`")
2185 );
2186 let patch_result = parse_patch_result(result);
2187 assert!(
2188 patch_result
2189 .message
2190 .contains("headers reference `other.txt`")
2191 );
2192 assert!(
2193 patch_result
2194 .message
2195 .contains("path` overrides to `override.txt`")
2196 );
2197 }
2198
2199 #[test]
2200 fn test_apply_patch_tool_properties() {
2201 let tool = ApplyPatchTool;
2202 assert_eq!(tool.name(), "apply_patch");
2203 assert!(!tool.is_read_only());
2204 assert!(tool.is_sandboxable());
2205 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Suggest);
2206 }
2207
2208 #[test]
2209 fn test_multi_hunk_offset_tracking() {
2210 // File with 6 lines
2211 let mut lines: Vec<String> = vec![
2212 "line1".to_string(),
2213 "line2".to_string(),
2214 "line3".to_string(),
2215 "line4".to_string(),
2216 "line5".to_string(),
2217 "line6".to_string(),
2218 ];
2219
2220 // Hunk 1: Add 2 lines after line1 (offset becomes +2)
2221 let hunk1 = Hunk {
2222 old_start: 1,
2223 old_count: 2,
2224 new_start: 1,
2225 new_count: 4,
2226 lines: vec![
2227 HunkLine::Context("line1".to_string()),
2228 HunkLine::Add("new_a".to_string()),
2229 HunkLine::Add("new_b".to_string()),
2230 HunkLine::Context("line2".to_string()),
2231 ],
2232 };
2233
2234 // Hunk 2: Modify line5 (originally at position 5, now at position 7 due to +2 offset)
2235 let hunk2 = Hunk {
2236 old_start: 5, // Original position in the diff
2237 old_count: 1,
2238 new_start: 7,
2239 new_count: 1,
2240 lines: vec![
2241 HunkLine::Remove("line5".to_string()),
2242 HunkLine::Add("modified5".to_string()),
2243 ],
2244 };
2245
2246 let mut offset: isize = 0;
2247
2248 // Apply first hunk
2249 let outcome1 = apply_hunk(&mut lines, &hunk1, 3, &mut offset).unwrap();
2250 assert_eq!(outcome1.fuzz_used, 0);
2251 assert!(!outcome1.relocated);
2252 assert_eq!(offset, 2); // Added 2 lines (4 new - 2 old)
2253 assert_eq!(
2254 lines,
2255 vec![
2256 "line1", "new_a", "new_b", "line2", "line3", "line4", "line5", "line6"
2257 ]
2258 );
2259
2260 // Apply second hunk - this would fail without offset tracking!
2261 let outcome2 = apply_hunk(&mut lines, &hunk2, 3, &mut offset).unwrap();
2262 assert_eq!(outcome2.fuzz_used, 0);
2263 assert!(!outcome2.relocated);
2264 assert!(lines.contains(&"modified5".to_string()));
2265 assert!(!lines.contains(&"line5".to_string()));
2266 }
2267
2268 #[test]
2269 fn test_apply_hunk_relocates_to_unique_context_match() {
2270 // #5003 - stale line numbers (hunk says line 1, content is at line 20).
2271 let mut lines: Vec<String> = (0..25).map(|i| format!("line{i}")).collect();
2272 let hunk = Hunk {
2273 old_start: 1, // stale line number
2274 old_count: 5,
2275 new_start: 1,
2276 new_count: 5,
2277 lines: vec![
2278 HunkLine::Context("line19".to_string()),
2279 HunkLine::Context("line20".to_string()),
2280 HunkLine::Remove("line21".to_string()),
2281 HunkLine::Add("line21-modified".to_string()),
2282 HunkLine::Context("line22".to_string()),
2283 HunkLine::Context("line23".to_string()),
2284 ],
2285 };
2286
2287 let mut offset: isize = 0;
2288 let outcome = apply_hunk(&mut lines, &hunk, 1, &mut offset).unwrap();
2289 assert!(
2290 outcome.relocated,
2291 "expected relocation for stale line numbers"
2292 );
2293 assert_eq!(outcome.fuzz_used, 0);
2294 assert_eq!(lines[21], "line21-modified");
2295 assert!(!lines.contains(&"line21".to_string()));
2296 }
2297
2298 #[test]
2299 fn test_apply_hunk_ambiguous_context_reports_candidates() {
2300 // Two identical block-a..d blocks: anchor is not unique -> ContextAmbiguous.
2301 let mut lines: Vec<String> = [
2302 "header0", "header1", "header2", "block-a", "block-b", "block-c", "block-d", "middle",
2303 "block-a", "block-b", "block-c", "block-d", "footer",
2304 ]
2305 .iter()
2306 .map(|s| s.to_string())
2307 .collect();
2308
2309 let hunk = Hunk {
2310 old_start: 1,
2311 old_count: 4,
2312 new_start: 1,
2313 new_count: 4,
2314 lines: vec![
2315 HunkLine::Remove("block-a".to_string()),
2316 HunkLine::Remove("block-b".to_string()),
2317 HunkLine::Remove("block-c".to_string()),
2318 HunkLine::Remove("block-d".to_string()),
2319 HunkLine::Add("block-a-modified".to_string()),
2320 HunkLine::Add("block-b".to_string()),
2321 HunkLine::Add("block-c".to_string()),
2322 HunkLine::Add("block-d".to_string()),
2323 ],
2324 };
2325
2326 let mut offset: isize = 0;
2327 let err = apply_hunk(&mut lines, &hunk, 1, &mut offset).unwrap_err();
2328 match err {
2329 ApplyHunkError::ContextAmbiguous {
2330 expected_line,
2331 candidate_lines,
2332 } => {
2333 assert_eq!(expected_line, 1);
2334 // The two duplicate blocks start at 1-based lines 4 and 9.
2335 assert_eq!(candidate_lines, vec![4, 9]);
2336 }
2337 other => panic!("expected ContextAmbiguous, got: {other:?}"),
2338 }
2339 }
2340
2341 #[test]
2342 fn test_apply_hunk_short_anchor_not_relocated() {
2343 // Anchor too short (1 line < MIN_ANCHOR_LINES): keep NoMatch behavior.
2344 let mut lines: Vec<String> = ["zero", "one", "two", "three", "four"]
2345 .iter()
2346 .map(|s| s.to_string())
2347 .collect();
2348 let hunk = Hunk {
2349 old_start: 1,
2350 old_count: 1,
2351 new_start: 1,
2352 new_count: 1,
2353 lines: vec![
2354 HunkLine::Remove("four".to_string()),
2355 HunkLine::Add("four-modified".to_string()),
2356 ],
2357 };
2358
2359 let mut offset: isize = 0;
2360 let err = apply_hunk(&mut lines, &hunk, 1, &mut offset).unwrap_err();
2361 assert!(
2362 matches!(err, ApplyHunkError::NoMatch { .. }),
2363 "short anchors must not be relocated"
2364 );
2365 }
2366
2367 #[tokio::test]
2368 async fn test_apply_patch_relocates_stale_line_numbers() {
2369 // #5003 - integration: hunk claims line 1 but content is at line 21.
2370 let tmp = tempdir().expect("tempdir");
2371 let ctx = ToolContext::new(tmp.path().to_path_buf());
2372 let tool = ApplyPatchTool;
2373
2374 let content = (0..30)
2375 .map(|i| format!("line{i}"))
2376 .collect::<Vec<_>>()
2377 .join("\n")
2378 + "\n";
2379 fs::write(tmp.path().join("stale.txt"), &content).expect("write");
2380
2381 let patch = r"@@ -1,5 +1,5 @@
2382 line19
2383 line20
2384 -line21
2385 +line21-modified
2386 line22
2387 line23
2388 ";
2389
2390 let result = tool
2391 .execute(
2392 json!({"path": "stale.txt", "patch": patch, "fuzz": 1}),
2393 &ctx,
2394 )
2395 .await
2396 .expect("execute");
2397 assert!(result.success);
2398 let patch_result = parse_patch_result(result);
2399 assert_eq!(patch_result.hunks_relocated, 1);
2400 assert!(
2401 patch_result.message.contains("stale line numbers"),
2402 "message: {}",
2403 patch_result.message
2404 );
2405 let summary = patch_result.file_summaries.first().unwrap();
2406 assert_eq!(summary.hunks_relocated, 1);
2407
2408 let edited = fs::read_to_string(tmp.path().join("stale.txt")).expect("read");
2409 assert!(edited.contains("line21-modified"));
2410 assert!(!edited.contains("\nline21\n"));
2411 }
2412
2413 #[tokio::test]
2414 async fn test_apply_patch_ambiguous_context_reports_candidates() {
2415 // #5003 - integration: duplicate context blocks, ambiguous relocation.
2416 let tmp = tempdir().expect("tempdir");
2417 let ctx = ToolContext::new(tmp.path().to_path_buf());
2418 let tool = ApplyPatchTool;
2419
2420 let content = "header0\nheader1\nheader2\nblock-a\nblock-b\nblock-c\nblock-d\nmiddle\nblock-a\nblock-b\nblock-c\nblock-d\nfooter\n";
2421 fs::write(tmp.path().join("dup.txt"), content).expect("write");
2422
2423 let patch = r"@@ -1,4 +1,4 @@
2424 -block-a
2425 -block-b
2426 -block-c
2427 -block-d
2428 +block-a-modified
2429 +block-b
2430 +block-c
2431 +block-d
2432 ";
2433
2434 let err = tool
2435 .execute(json!({"path": "dup.txt", "patch": patch, "fuzz": 1}), &ctx)
2436 .await
2437 .unwrap_err();
2438 let message = err.to_string();
2439 assert!(
2440 message.contains("multiple locations"),
2441 "expected ambiguity error, got: {message}"
2442 );
2443 // The two duplicate blocks start at 1-based lines 4 and 9.
2444 assert!(
2445 message.contains("lines 4, 9"),
2446 "expected candidate lines, got: {message}"
2447 );
2448 let unchanged = fs::read_to_string(tmp.path().join("dup.txt")).expect("read");
2449 assert_eq!(
2450 unchanged, content,
2451 "ambiguous hunk must not modify the file"
2452 );
2453 }
2454 #[tokio::test]
2455 async fn test_apply_patch_relocates_after_crlf_chinese_edit_shift() {
2456 // #5003 - issue scenario: a C-style file with CRLF line endings and
2457 // Chinese comments. A first edit shifts line numbers; a second patch
2458 // still uses stale line numbers but its context is unique in the
2459 // file, so apply_patch relocates instead of failing.
2460 let tmp = tempdir().expect("tempdir");
2461 let ctx = ToolContext::new(tmp.path().to_path_buf());
2462 let tool = ApplyPatchTool;
2463
2464 let mut lines = vec!["/* 扭矩控制模块 */".to_string()];
2465 for i in 0..60 {
2466 lines.push(format!("int cfg_{i} = {i}; // 配置项 {i}"));
2467 }
2468 let content = lines.join("\r\n") + "\r\n";
2469 fs::write(tmp.path().join("app_foc.c"), &content).expect("write");
2470
2471 // First edit: insert 8 lines right after cfg_9 (old line 11). This
2472 // shifts every later line number by +8.
2473 let patch1 = r"@@ -11,1 +11,9 @@
2474 int cfg_9 = 9; // 配置项 9
2475 +int new_a = 100; // 新增配置 A
2476 +int new_b = 101; // 新增配置 B
2477 +int new_c = 102; // 新增配置 C
2478 +int new_d = 103; // 新增配置 D
2479 +int new_e = 104; // 新增配置 E
2480 +int new_f = 105; // 新增配置 F
2481 +int new_g = 106; // 新增配置 G
2482 +int new_h = 107; // 新增配置 H
2483 ";
2484 let r1 = tool
2485 .execute(
2486 json!({"path": "app_foc.c", "patch": patch1, "fuzz": 0}),
2487 &ctx,
2488 )
2489 .await
2490 .expect("first patch");
2491 assert!(r1.success, "first patch should apply: {}", r1.content);
2492
2493 // Second edit: claims line 31 (stale - cfg_21 now), but the replaced
2494 // block cfg_30..cfg_34 actually lives at lines 40-44. Positional
2495 // search with fuzz=1 fails; the unique whole-file anchor relocates.
2496 let patch2 = r"@@ -31,5 +31,5 @@
2497 int cfg_30 = 30; // 配置项 30
2498 int cfg_31 = 31; // 配置项 31
2499 -int cfg_32 = 32; // 配置项 32
2500 +int cfg_32 = 3200; // 配置项 32 已修改
2501 int cfg_33 = 33; // 配置项 33
2502 int cfg_34 = 34; // 配置项 34
2503 ";
2504 let r2 = tool
2505 .execute(
2506 json!({"path": "app_foc.c", "patch": patch2, "fuzz": 1}),
2507 &ctx,
2508 )
2509 .await
2510 .expect("second patch");
2511 assert!(r2.success, "second patch should relocate: {}", r2.content);
2512 let pr2 = parse_patch_result(r2);
2513 assert_eq!(pr2.hunks_relocated, 1, "second patch must be relocated");
2514
2515 let edited = fs::read_to_string(tmp.path().join("app_foc.c")).expect("read");
2516 assert!(
2517 edited.contains("int cfg_32 = 3200;"),
2518 "replacement must land"
2519 );
2520 assert!(
2521 edited.contains("int cfg_33 = 33;"),
2522 "context after the edit must stay intact"
2523 );
2524 assert!(
2525 edited.contains("int new_h = 107;"),
2526 "first edit must survive"
2527 );
2528 }
2529
2530 // === Content-hash patch guard (#3979) ===
2531 //
2532 // The guard is a whole-patch precondition on the patch target, not a
2533 // per-file check — see `verify_patch_expected_hash`. These pin that it
2534 // fires before anything is written.
2535
2536 const GUARD_PATCH: &str = "--- a/test.txt
2537 +++ b/test.txt
2538 @@ -1,3 +1,3 @@
2539 line1
2540 -line2
2541 +modified
2542 line3
2543 ";
2544
2545 #[tokio::test]
2546 async fn patch_with_matching_expected_hash_proceeds() {
2547 let tmp = tempdir().expect("tempdir");
2548 let ctx = ToolContext::new(tmp.path().to_path_buf());
2549 let body = "line1\nline2\nline3\n";
2550 fs::write(tmp.path().join("test.txt"), body).expect("write");
2551
2552 ApplyPatchTool
2553 .execute(
2554 json!({
2555 "path": "test.txt",
2556 "patch": GUARD_PATCH,
2557 "expected_hash": content_hash(body.as_bytes()),
2558 }),
2559 &ctx,
2560 )
2561 .await
2562 .expect("matching hash must not block the patch");
2563
2564 let updated = fs::read_to_string(tmp.path().join("test.txt")).expect("read");
2565 assert!(updated.contains("modified"), "{updated}");
2566 }
2567
2568 #[tokio::test]
2569 async fn patch_with_stale_expected_hash_rejects_without_writing() {
2570 let tmp = tempdir().expect("tempdir");
2571 let ctx = ToolContext::new(tmp.path().to_path_buf());
2572 let body = "line1\nline2\nline3\n";
2573 fs::write(tmp.path().join("test.txt"), body).expect("write");
2574
2575 let err = ApplyPatchTool
2576 .execute(
2577 json!({
2578 "path": "test.txt",
2579 "patch": GUARD_PATCH,
2580 "expected_hash": content_hash(b"a different file entirely\n"),
2581 }),
2582 &ctx,
2583 )
2584 .await
2585 .expect_err("stale hash must reject");
2586
2587 let message = err.to_string();
2588 assert!(message.contains("changed since it was read"), "{message}");
2589 assert!(message.contains("nothing was written"), "{message}");
2590 assert_eq!(
2591 fs::read_to_string(tmp.path().join("test.txt")).expect("read"),
2592 body,
2593 "a rejected patch must not modify the file"
2594 );
2595 }
2596
2597 #[tokio::test]
2598 async fn patch_without_expected_hash_is_unchanged() {
2599 let tmp = tempdir().expect("tempdir");
2600 let ctx = ToolContext::new(tmp.path().to_path_buf());
2601 fs::write(tmp.path().join("test.txt"), "line1\nline2\nline3\n").expect("write");
2602
2603 ApplyPatchTool
2604 .execute(json!({ "path": "test.txt", "patch": GUARD_PATCH }), &ctx)
2605 .await
2606 .expect("absent expected_hash keeps the pre-#3979 behavior");
2607
2608 let updated = fs::read_to_string(tmp.path().join("test.txt")).expect("read");
2609 assert!(updated.contains("modified"), "{updated}");
2610 }
2611
2612 #[tokio::test]
2613 async fn multi_file_patch_guards_the_first_file_and_writes_nothing_on_mismatch() {
2614 let tmp = tempdir().expect("tempdir");
2615 let ctx = ToolContext::new(tmp.path().to_path_buf());
2616 fs::write(tmp.path().join("one.txt"), "one\n").expect("write");
2617 fs::write(tmp.path().join("two.txt"), "two\n").expect("write");
2618
2619 let patch = "diff --git a/one.txt b/one.txt
2620 --- a/one.txt
2621 +++ b/one.txt
2622 @@ -1 +1 @@
2623 -one
2624 +ONE
2625 diff --git a/two.txt b/two.txt
2626 --- a/two.txt
2627 +++ b/two.txt
2628 @@ -1 +1 @@
2629 -two
2630 +TWO
2631 ";
2632
2633 let err = ApplyPatchTool
2634 .execute(
2635 json!({
2636 "patch": patch,
2637 "expected_hash": content_hash(b"stale\n"),
2638 }),
2639 &ctx,
2640 )
2641 .await
2642 .expect_err("stale hash on the first file must reject the whole patch");
2643 assert!(err.to_string().contains("one.txt"), "{err}");
2644
2645 // Transactional: the unguarded second file must not have been
2646 // written either.
2647 assert_eq!(
2648 fs::read_to_string(tmp.path().join("one.txt")).unwrap(),
2649 "one\n"
2650 );
2651 assert_eq!(
2652 fs::read_to_string(tmp.path().join("two.txt")).unwrap(),
2653 "two\n"
2654 );
2655 }
2656
2657 #[tokio::test]
2658 async fn patch_expected_hash_on_a_missing_target_fails_closed() {
2659 let tmp = tempdir().expect("tempdir");
2660 let ctx = ToolContext::new(tmp.path().to_path_buf());
2661
2662 let err = ApplyPatchTool
2663 .execute(
2664 json!({
2665 "path": "absent.txt",
2666 "patch": GUARD_PATCH,
2667 "create_if_missing": true,
2668 "expected_hash": content_hash(b"anything"),
2669 }),
2670 &ctx,
2671 )
2672 .await
2673 .expect_err("guarded patch of a missing file must fail closed");
2674
2675 assert!(err.to_string().contains("does not exist"), "{err}");
2676 assert!(!tmp.path().join("absent.txt").exists());
2677 }
2678
2679 /// B7: two sections for the same file both land; the second applies on
2680 /// top of the first instead of re-reading the disk and dropping it.
2681 #[tokio::test]
2682 async fn two_sections_for_one_file_apply_both() {
2683 let tmp = tempdir().expect("tempdir");
2684 let ctx = ToolContext::new(tmp.path().to_path_buf());
2685 fs::write(tmp.path().join("f.txt"), "a1\na2\na3\nmid\nb1\nb2\nb3\n").expect("write");
2686 let patch = r"--- a/f.txt
2687 +++ b/f.txt
2688 @@ -1,3 +1,3 @@
2689 a1
2690 -a2
2691 +A2
2692 a3
2693 --- a/f.txt
2694 +++ b/f.txt
2695 @@ -5,3 +5,3 @@
2696 b1
2697 -b2
2698 +B2
2699 b3
2700 ";
2701 let result = ApplyPatchTool
2702 .execute(json!({"patch": patch}), &ctx)
2703 .await
2704 .expect("execute");
2705 assert!(result.success, "{}", result.content);
2706 assert_eq!(
2707 fs::read_to_string(tmp.path().join("f.txt")).expect("read"),
2708 "a1\nA2\na3\nmid\nb1\nB2\nb3\n"
2709 );
2710 let summary = parse_patch_result(result);
2711 assert_eq!(summary.files_total, 1, "one file, two sections");
2712 assert_eq!(summary.files_applied, 1);
2713 assert_eq!(summary.hunks_applied, 2);
2714 }
2715
2716 #[tokio::test]
2717 async fn creation_patch_on_an_existing_file_is_refused() {
2718 let tmp = tempdir().expect("tempdir");
2719 let ctx = ToolContext::new(tmp.path().to_path_buf());
2720 fs::write(tmp.path().join("foo.rs"), "fn keep() {}\n").expect("write");
2721 let patch = "--- /dev/null\n+++ b/foo.rs\n@@ -0,0 +1,2 @@\n+fn a() {}\n+fn b() {}\n";
2722
2723 let err = ApplyPatchTool
2724 .execute(json!({"patch": patch}), &ctx)
2725 .await
2726 .expect_err("a /dev/null creation must not land on an existing file");
2727
2728 assert!(err.to_string().contains("already exists"), "{err}");
2729 assert_eq!(
2730 fs::read_to_string(tmp.path().join("foo.rs")).expect("read"),
2731 "fn keep() {}\n"
2732 );
2733 }
2734
2735 #[tokio::test]
2736 async fn pure_insertion_hunk_lands_after_the_named_line() {
2737 let tmp = tempdir().expect("tempdir");
2738 let ctx = ToolContext::new(tmp.path().to_path_buf());
2739 fs::write(tmp.path().join("f.txt"), "l1\nl2\nl3\nl4\n").expect("write");
2740 // `git diff -U0` form: insert after line 3.
2741 let patch = "@@ -3,0 +4,1 @@\n+inserted\n";
2742
2743 ApplyPatchTool
2744 .execute(json!({"path": "f.txt", "patch": patch}), &ctx)
2745 .await
2746 .expect("execute");
2747
2748 assert_eq!(
2749 fs::read_to_string(tmp.path().join("f.txt")).expect("read"),
2750 "l1\nl2\nl3\ninserted\nl4\n"
2751 );
2752 }
2753
2754 #[tokio::test]
2755 async fn delete_section_covering_part_of_a_file_is_refused() {
2756 let tmp = tempdir().expect("tempdir");
2757 let ctx = ToolContext::new(tmp.path().to_path_buf());
2758 let original = "1\n2\n3\n4\n5\n";
2759 fs::write(tmp.path().join("big.txt"), original).expect("write");
2760 let patch = "--- a/big.txt\n+++ /dev/null\n@@ -1,3 +0,0 @@\n-1\n-2\n-3\n";
2761
2762 let err = ApplyPatchTool
2763 .execute(json!({"patch": patch}), &ctx)
2764 .await
2765 .expect_err("a partial delete must not remove the file");
2766
2767 assert!(err.to_string().contains("2 line(s)"), "{err}");
2768 assert_eq!(
2769 fs::read_to_string(tmp.path().join("big.txt")).expect("still there"),
2770 original
2771 );
2772 }
2773
2774 #[tokio::test]
2775 async fn creation_patch_with_a_path_override_on_an_existing_file_is_refused() {
2776 let tmp = tempdir().expect("tempdir");
2777 let ctx = ToolContext::new(tmp.path().to_path_buf());
2778 fs::write(tmp.path().join("foo.rs"), "fn keep() {}\n").expect("write");
2779 let patch = "--- /dev/null\n+++ b/foo.rs\n@@ -0,0 +1,2 @@\n+fn a() {}\n+fn b() {}\n";
2780
2781 let err = ApplyPatchTool
2782 .execute(json!({"path": "foo.rs", "patch": patch}), &ctx)
2783 .await
2784 .expect_err("`path` must not turn a /dev/null creation into a prepend");
2785
2786 assert!(err.to_string().contains("already exists"), "{err}");
2787 assert_eq!(
2788 fs::read_to_string(tmp.path().join("foo.rs")).expect("read"),
2789 "fn keep() {}\n"
2790 );
2791 }
2792
2793 #[tokio::test]
2794 async fn creation_section_after_an_edit_of_the_same_file_is_refused() {
2795 let tmp = tempdir().expect("tempdir");
2796 let ctx = ToolContext::new(tmp.path().to_path_buf());
2797 fs::write(tmp.path().join("foo.txt"), "a\nb\n").expect("write");
2798 let patch = "--- a/foo.txt\n+++ b/foo.txt\n@@ -1,2 +1,2 @@\n a\n-b\n+c\n\
2799 --- /dev/null\n+++ b/foo.txt\n@@ -0,0 +1,1 @@\n+new\n";
2800
2801 let err = ApplyPatchTool
2802 .execute(json!({"patch": patch}), &ctx)
2803 .await
2804 .expect_err("a second, creating section must not prepend to the edited file");
2805
2806 assert!(err.to_string().contains("already exists"), "{err}");
2807 assert_eq!(
2808 fs::read_to_string(tmp.path().join("foo.txt")).expect("read"),
2809 "a\nb\n"
2810 );
2811 }
2812
2813 #[tokio::test]
2814 async fn insertion_hunks_without_a_zero_old_count_keep_the_before_anchor() {
2815 let tmp = tempdir().expect("tempdir");
2816 let ctx = ToolContext::new(tmp.path().to_path_buf());
2817 for (patch, expected) in [
2818 // Omitted old count (defaults to 1): before line 2, as before.
2819 ("@@ -2 +2,1 @@\n+x\n", "l1\nx\nl2\nl3\n"),
2820 // Hand-written "new text starts at line 1": at the top.
2821 ("@@ -1,0 +1,1 @@\n+x\n", "x\nl1\nl2\nl3\n"),
2822 // `git diff -U0` form: after line 1.
2823 ("@@ -1,0 +2,1 @@\n+x\n", "l1\nx\nl2\nl3\n"),
2824 ] {
2825 fs::write(tmp.path().join("f.txt"), "l1\nl2\nl3\n").expect("write");
2826 ApplyPatchTool
2827 .execute(json!({"path": "f.txt", "patch": patch}), &ctx)
2828 .await
2829 .expect("execute");
2830 assert_eq!(
2831 fs::read_to_string(tmp.path().join("f.txt")).expect("read"),
2832 expected,
2833 "{patch:?}"
2834 );
2835 }
2836 }
2837
2838 #[allow(clippy::await_holding_lock)]
2839 #[tokio::test]
2840 async fn apply_patch_refuses_credential_and_denied_targets_in_expected_hash_and_hunks() {
2841 let _env_lock = crate::test_support::lock_test_env();
2842 let tmp = tempdir().expect("tempdir");
2843 let ws_canon = tmp.path().canonicalize().expect("canon ws");
2844 let cw_home = ws_canon.join("cw-home");
2845 fs::create_dir_all(&cw_home).expect("mkdir cw-home");
2846 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
2847 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
2848 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
2849
2850 let config_file = cw_home.join("config.toml");
2851 let config_original = "api_key = \"sk-secret\"\n";
2852 fs::write(&config_file, config_original).expect("write config");
2853 let env_file = ws_canon.join(".env");
2854 let env_original = "SECRET=topsecret\n";
2855 fs::write(&env_file, env_original).expect("write .env");
2856
2857 let trusted_ctx = ToolContext::new(&ws_canon).with_trust_mode(true);
2858 trusted_ctx.note_file_read(&config_file);
2859 trusted_ctx.note_file_read(&env_file);
2860
2861 let patch = "@@ -1 +1 @@\n-old\n+new\n";
2862 for target in [
2863 config_file.to_string_lossy().to_string(),
2864 ".env".to_string(),
2865 ] {
2866 let hash_err = ApplyPatchTool
2867 .execute(
2868 json!({"path": &target, "patch": patch, "expected_hash": "deadbeef"}),
2869 &trusted_ctx,
2870 )
2871 .await
2872 .expect_err("expected_hash must refuse protected target before hashing");
2873 assert!(
2874 matches!(hash_err, ToolError::PermissionDenied { .. }),
2875 "{target}: {hash_err:?}"
2876 );
2877
2878 let diff_err = ApplyPatchTool
2879 .execute(json!({"path": &target, "patch": patch}), &trusted_ctx)
2880 .await
2881 .expect_err("unified diff must refuse protected target");
2882 assert!(
2883 matches!(diff_err, ToolError::PermissionDenied { .. }),
2884 "{target}: {diff_err:?}"
2885 );
2886
2887 let replace_err = ApplyPatchTool
2888 .execute(
2889 json!({"replace": [{"path": &target, "content": "overwritten\n"}]}),
2890 &trusted_ctx,
2891 )
2892 .await
2893 .expect_err("replace mode must refuse protected target");
2894 assert!(
2895 matches!(replace_err, ToolError::PermissionDenied { .. }),
2896 "{target}: {replace_err:?}"
2897 );
2898 }
2899
2900 assert_eq!(
2901 fs::read_to_string(&config_file).expect("read config"),
2902 config_original
2903 );
2904 assert_eq!(
2905 fs::read_to_string(&env_file).expect("read .env"),
2906 env_original
2907 );
2908
2909 let normal = ws_canon.join("normal.txt");
2910 fs::write(&normal, "before\n").expect("write normal");
2911 trusted_ctx.note_file_read(&normal);
2912 ApplyPatchTool
2913 .execute(
2914 json!({"path": "normal.txt", "patch": "@@ -1 +1 @@\n-before\n+after\n"}),
2915 &trusted_ctx,
2916 )
2917 .await
2918 .expect("normal patch in trust mode succeeds");
2919 assert_eq!(fs::read_to_string(&normal).expect("read normal"), "after\n");
2920 }
2921
2922 #[allow(clippy::await_holding_lock)]
2923 #[tokio::test]
2924 async fn apply_patch_allows_brand_new_dotenv_and_refuses_missing_credentials() {
2925 let _env_lock = crate::test_support::lock_test_env();
2926 let tmp = tempdir().expect("tempdir");
2927 let ws_canon = tmp.path().canonicalize().expect("canon ws");
2928 let cw_home = ws_canon.join("cw-home");
2929 fs::create_dir_all(&cw_home).expect("mkdir cw-home");
2930 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &cw_home);
2931 let _config_path = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
2932 let _legacy_config_path = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
2933
2934 let missing_config = cw_home.join("config.toml");
2935 let trusted_ctx = ToolContext::new(&ws_canon).with_trust_mode(true);
2936
2937 let cred_replace_err = ApplyPatchTool
2938 .execute(
2939 json!({
2940 "replace": [{
2941 "path": missing_config.to_string_lossy(),
2942 "content": "hijack = true\n"
2943 }]
2944 }),
2945 &trusted_ctx,
2946 )
2947 .await
2948 .expect_err("replace must refuse missing CODEWHALE_HOME/config.toml");
2949 assert!(
2950 matches!(cred_replace_err, ToolError::PermissionDenied { .. }),
2951 "{cred_replace_err:?}"
2952 );
2953
2954 let cred_create_err = ApplyPatchTool
2955 .execute(
2956 json!({
2957 "path": missing_config.to_string_lossy(),
2958 "patch": "@@ -0,0 +1 @@\n+hijack = true\n",
2959 "create_if_missing": true
2960 }),
2961 &trusted_ctx,
2962 )
2963 .await
2964 .expect_err("create_if_missing patch must refuse missing CODEWHALE_HOME/config.toml");
2965 assert!(
2966 matches!(cred_create_err, ToolError::PermissionDenied { .. }),
2967 "{cred_create_err:?}"
2968 );
2969 assert!(!missing_config.exists());
2970
2971 let missing_env_diff_err = ApplyPatchTool
2972 .execute(
2973 json!({"path": ".env", "patch": "@@ -1 +1 @@\n-old\n+new\n"}),
2974 &trusted_ctx,
2975 )
2976 .await
2977 .expect_err("non-creating patch on missing .env must fail with PermissionDenied");
2978 assert!(
2979 matches!(missing_env_diff_err, ToolError::PermissionDenied { .. }),
2980 "{missing_env_diff_err:?}"
2981 );
2982
2983 let missing_env_hash_err = ApplyPatchTool
2984 .execute(
2985 json!({
2986 "path": ".env",
2987 "patch": "@@ -0,0 +1 @@\n+A=1\n",
2988 "create_if_missing": true,
2989 "expected_hash": "sha256:deadbeef"
2990 }),
2991 &trusted_ctx,
2992 )
2993 .await
2994 .expect_err("expected_hash on missing .env must fail with PermissionDenied");
2995 assert!(
2996 matches!(missing_env_hash_err, ToolError::PermissionDenied { .. }),
2997 "{missing_env_hash_err:?}"
2998 );
2999
3000 let ws_replace = tempdir().expect("ws_replace");
3001 let ctx_replace = ToolContext::new(ws_replace.path()).with_trust_mode(true);
3002 ApplyPatchTool
3003 .execute(
3004 json!({"replace": [{"path": ".env", "content": "A=1\n"}]}),
3005 &ctx_replace,
3006 )
3007 .await
3008 .expect("replace creates brand-new .env");
3009 assert_eq!(
3010 fs::read_to_string(ws_replace.path().join(".env")).expect("read .env"),
3011 "A=1\n"
3012 );
3013 let overwrite_replace_err = ApplyPatchTool
3014 .execute(
3015 json!({"replace": [{"path": ".env", "content": "A=2\n"}]}),
3016 &ctx_replace,
3017 )
3018 .await
3019 .expect_err("replace must refuse existing .env");
3020 assert!(
3021 matches!(overwrite_replace_err, ToolError::PermissionDenied { .. }),
3022 "{overwrite_replace_err:?}"
3023 );
3024 assert_eq!(
3025 fs::read_to_string(ws_replace.path().join(".env")).expect("unchanged .env"),
3026 "A=1\n"
3027 );
3028
3029 let ws_create = tempdir().expect("ws_create");
3030 let ctx_create = ToolContext::new(ws_create.path()).with_trust_mode(true);
3031 ApplyPatchTool
3032 .execute(
3033 json!({
3034 "path": ".env",
3035 "patch": "@@ -0,0 +1 @@\n+B=1\n",
3036 "create_if_missing": true
3037 }),
3038 &ctx_create,
3039 )
3040 .await
3041 .expect("create_if_missing patch creates brand-new .env");
3042 assert_eq!(
3043 fs::read_to_string(ws_create.path().join(".env")).expect("read .env"),
3044 "B=1\n"
3045 );
3046
3047 let ws_devnull = tempdir().expect("ws_devnull");
3048 let ctx_devnull = ToolContext::new(ws_devnull.path()).with_trust_mode(true);
3049 ApplyPatchTool
3050 .execute(
3051 json!({
3052 "patch": "--- /dev/null\n+++ b/.env\n@@ -0,0 +1 @@\n+C=1\n"
3053 }),
3054 &ctx_devnull,
3055 )
3056 .await
3057 .expect("/dev/null creation patch creates brand-new .env");
3058 assert_eq!(
3059 fs::read_to_string(ws_devnull.path().join(".env")).expect("read .env"),
3060 "C=1\n"
3061 );
3062 }
3063 }
3064
3064 lines RUST