1use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5
6use crate::server::tool_trait::{
7 McpTool, ToolContext, ToolOutput, get_bool, get_int, get_str, require_resolved_path,
8 tool_execution_error,
9};
10use lean_ctx::tool_defs::tool_def;
11
12pub struct CtxPatchTool;
13
14pub(crate) fn host_draws_diffs(ctx: &ToolContext) -> bool {
18 static MOD_PRESENT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
19 let claude = ctx
20 .client_name
21 .as_ref()
22 .and_then(|name| {
23 name.try_read()
24 .ok()
25 .map(|n| n.to_ascii_lowercase().contains("claude"))
26 })
27 .unwrap_or(false);
28 claude
29 && *MOD_PRESENT.get_or_init(|| {
30 std::env::var_os("CLAUDE_CONFIG_DIR")
31 .map(std::path::PathBuf::from)
32 .or_else(|| dirs::home_dir().map(|home| home.join(".claude")))
33 .is_some_and(|dir| {
34 !lean_ctx_hooks::hooks::agents::claude_mod::cached_versions(&dir).is_empty()
35 })
36 })
37}
38
39impl McpTool for CtxPatchTool {
40 fn name(&self) -> &'static str {
41 "ctx_patch"
42 }
43
44 fn tool_def(&self) -> Tool {
51 tool_def(
52 "ctx_patch",
53 "Safe file edit; relative paths as in ctx_read. replace_unique(path,old_text,new_text): \
54 exact unique replacement, needs no anchors. Line ops take line+hash from \
55 ctx_read(mode=\"anchored:N-M\"); CONFLICT means re-read. ops[] batch \
56 (cross-file, incl. replace_unique/replace_symbol); create and replace_all only \
57 as top-level calls. A 0-byte file: create, or replace_unique with old_text=\"\".",
58 json!({
59 "type": "object",
60 "properties": {
61 "path": { "type": "string" },
62 "op": { "type": "string", "enum": ["set_line", "replace_lines", "insert_after", "delete", "replace_unique", "replace_symbol", "create", "replace_all"] },
63 "line": { "type": "integer" },
64 "hash": { "type": "string" },
65 "start_line": { "type": "integer" },
66 "start_hash": { "type": "string" },
67 "end_line": { "type": "integer" },
68 "end_hash": { "type": "string" },
69 "new_text": { "type": "string" },
70 "old_text": { "type": "string" },
71 "name": { "type": "string" },
72 "find": { "type": "string" },
73 "replace": { "type": "string" },
74 "dry_run": { "type": "boolean" },
75 "ops": { "type": "array", "items": { "type": "object" } }
76 },
77 "allOf": [
85 { "if": { "properties": { "op": { "const": "set_line" } }, "required": ["op"] },
86 "then": { "required": ["op", "line", "hash", "new_text"] } },
87 { "if": { "properties": { "op": { "const": "replace_lines" } }, "required": ["op"] },
88 "then": { "required": ["op", "start_line", "start_hash", "end_line", "end_hash", "new_text"] } },
89 { "if": { "properties": { "op": { "const": "replace_unique" } }, "required": ["op"] },
90 "then": { "required": ["op", "old_text", "new_text"] } },
91 { "if": { "properties": { "op": { "const": "replace_symbol" } }, "required": ["op"] },
92 "then": { "required": ["op", "new_text"] } },
93 { "if": { "properties": { "op": { "const": "create" } }, "required": ["op"] },
94 "then": { "required": ["op", "new_text"] } },
95 { "if": { "properties": { "op": { "const": "replace_all" } }, "required": ["op"] },
96 "then": { "required": ["op", "find", "replace"] } }
97 ]
98 }),
99 )
100 }
101
102 fn handle(
103 &self,
104 args: &Map<String, Value>,
105 ctx: &ToolContext,
106 ) -> Result<ToolOutput, ErrorData> {
107 let moved_base = names_relative_path(args)
112 .then(|| crate::tools::path_base::active_base(ctx))
113 .flatten();
114 let substituted = moved_base
118 .as_ref()
119 .filter(|_| !args.contains_key("ops"))
120 .zip(get_str(args, "path"))
121 .zip(ctx.resolved_path("path"))
122 .and_then(|((base, raw), resolved)| {
123 crate::tools::path_base::doubled_path_fallback(ctx, base, &raw, resolved)
124 .filter(|found| ctx.ensure_writable(found).is_ok())
125 .map(|found| (resolved.to_string(), found))
126 });
127 let swapped;
128 let ctx = match &substituted {
129 Some((_, found)) => {
130 let mut sub = ctx.clone();
131 sub.resolved_paths.insert("path".to_string(), found.clone());
132 swapped = sub;
133 &swapped
134 }
135 None => ctx,
136 };
137 let before = substituted
141 .as_ref()
142 .filter(|_| !get_bool(args, "dry_run").unwrap_or(false))
143 .map(|(_, found)| std::fs::read(found).ok());
144
145 let result = crate::tools::claims_gate::scoped(ctx, || handle_patch(args, ctx));
148 match result {
149 Ok(mut output) => {
150 let written = substituted
151 .as_ref()
152 .zip(before)
153 .filter(|((_, found), before)| std::fs::read(found).ok() != *before)
154 .map(|((requested, found), _)| {
155 crate::tools::path_base::substitution_note(requested, found, "patched")
156 });
157 let notes: Vec<String> = written
158 .into_iter()
159 .chain(
160 moved_base
161 .as_ref()
162 .and_then(crate::tools::path_base::ActiveBase::note_once),
163 )
164 .collect();
165 if !notes.is_empty() {
166 output.text = format!(
167 "{}\n{}",
168 output.text.trim_end_matches('\n'),
169 notes.join("\n")
170 );
171 }
172 Ok(output)
173 }
174 Err(mut error) => {
176 if let Some(base) = &moved_base {
177 base.mark_noted();
178 error.message = format!("{}\n{}", error.message, base.note()).into();
179 }
180 Err(error)
181 }
182 }
183 }
184}
185
186fn names_relative_path(args: &Map<String, Value>) -> bool {
189 let relative = |v: Option<&Value>| {
190 v.and_then(Value::as_str)
191 .is_some_and(crate::tools::path_base::is_relative)
192 };
193 relative(args.get("path"))
194 || args
195 .get("ops")
196 .and_then(Value::as_array)
197 .is_some_and(|ops| ops.iter().any(|op| relative(op.get("path"))))
198}
199
200fn handle_patch(args: &Map<String, Value>, ctx: &ToolContext) -> Result<ToolOutput, ErrorData> {
201 let inferred = infer_replace_unique(args);
202 let args = inferred.as_ref().unwrap_or(args);
203
204 if crate::tools::ctx_patch::is_replace_symbol(args) {
207 return delegate_replace_symbol(args, ctx);
208 }
209
210 if get_str(args, "op").as_deref() == Some("replace_unique") {
211 return delegate_replace_unique(args, ctx);
212 }
213
214 if get_str(args, "op").as_deref() == Some("replace_all") {
216 return handle_replace_all(args, ctx);
217 }
218
219 if let Some(arr) = args.get("ops").and_then(Value::as_array) {
223 for (i, v) in arr.iter().enumerate() {
225 if let Some(kind) = is_unbatchable_op(v) {
226 return Err(ErrorData::invalid_params(
227 format!(
228 "ops[{i}]: {kind} cannot be batched in ops[] \
229 — send it as a separate top-level ctx_patch call"
230 ),
231 None,
232 ));
233 }
234 }
235 if arr.iter().any(|v| delegated_op_kind(v).is_some()) {
236 return handle_mixed_batch(args, arr, ctx);
237 }
238 }
239
240 handle_anchored(args, ctx)
241}
242
243fn handle_anchored(args: &Map<String, Value>, ctx: &ToolContext) -> Result<ToolOutput, ErrorData> {
247 if get_bool(args, "dry_run").unwrap_or(false) {
248 let path = get_str(args, "path").unwrap_or_default();
249 return Ok(ToolOutput::simple(format!(
250 "DRY RUN: ctx_patch would apply anchor-based ops to {path}"
251 )));
252 }
253
254 let expected_blake3 =
257 get_str(args, "expected_blake3").or_else(|| get_str(args, "expected_md5"));
258 let backup = get_bool(args, "backup").unwrap_or(false);
259 let backup_path = get_str(args, "backup_path")
260 .map(|p| ctx.resolved_paths.get("backup_path").cloned().unwrap_or(p))
261 .map(|p| lean_ctx::core::workspace_authority::confine(&p, &ctx.project_root, true))
262 .transpose()
263 .map_err(|error| ErrorData::invalid_params(error, None))?;
264 let evidence = get_bool(args, "evidence").unwrap_or(false);
266 let diff_max_lines = get_int(args, "diff_max_lines")
267 .and_then(|v| usize::try_from(v.max(0)).ok())
268 .unwrap_or(200);
269 let allow_lossy_utf8 = get_bool(args, "allow_lossy_utf8").unwrap_or(false);
270 let validate_syntax = get_bool(args, "validate_syntax").unwrap_or(true);
271
272 let groups = plan_groups(args, ctx)?;
276 validate_cross_file_options(args, groups.len())?;
277 let output_path = (groups.len() == 1).then(|| groups[0].0.clone());
278 let label_parts = groups.len() > 1;
281 let diff_artifact = host_draws_diffs(ctx);
282
283 let mut texts = Vec::with_capacity(groups.len());
284 for (path, ops) in groups {
285 let patch_params = crate::tools::ctx_patch::PatchParams {
286 path: path.clone(),
287 ops,
288 expected_blake3: expected_blake3.clone(),
289 backup,
290 backup_path: backup_path.clone(),
291 evidence,
292 diff_artifact,
293 diff_max_lines,
294 allow_lossy_utf8,
295 validate_syntax,
296 };
297 let output =
298 apply_one(ctx, &patch_params).map_err(|error| with_prior_edits(error, &texts))?;
299 texts.push(if label_parts {
300 format!("[{}]\n{output}", receipt_label(&path, &ctx.project_root))
301 } else {
302 output
303 });
304 }
305
306 Ok(ToolOutput {
307 text: texts.join("\n\n"),
308 original_tokens: 0,
309 saved_tokens: 0,
310 mode: None,
311 path: output_path,
312 changed: false,
313 shell_outcome: None,
314 content_blocks: None,
315 })
316}
317
318fn infer_replace_unique(args: &Map<String, Value>) -> Option<Map<String, Value>> {
328 fn is_text_replacement(obj: &Map<String, Value>) -> bool {
329 let text = |keys: [&str; 2]| keys.iter().find_map(|key| obj.get(*key)?.as_str());
330 !obj.contains_key("op")
331 && text(["old_text", "old_string"]).is_some_and(|old| !old.is_empty())
332 && text(["new_text", "new_string"]).is_some()
333 }
334 fn alias(obj: &mut Map<String, Value>, key: &str, aliases: &[&str]) -> bool {
336 if obj.contains_key(key) {
337 return false;
338 }
339 let Some(value) = aliases
340 .iter()
341 .find_map(|alias| obj.get(*alias).filter(|v| v.is_string()).cloned())
342 else {
343 return false;
344 };
345 obj.insert(key.to_string(), value);
346 true
347 }
348 fn repair(obj: &mut Map<String, Value>) -> bool {
349 let mut changed = false;
350 if is_text_replacement(obj) {
351 obj.insert("op".into(), json!("replace_unique"));
352 changed = true;
353 }
354 match obj.get("op").and_then(Value::as_str) {
355 Some("replace_unique") => {
356 changed |= alias(obj, "old_text", &["old_string", "find"]);
357 changed |= alias(obj, "new_text", &["new_string", "replace"]);
358 }
359 Some("create") => changed |= alias(obj, "new_text", &["new_string", "content"]),
360 Some("set_line" | "replace_lines" | "insert_after") => {
361 changed |= alias(obj, "new_text", &["new_string"]);
362 }
363 _ => {}
364 }
365 changed
366 }
367 let mut out = args.clone();
368 let mut repaired = false;
369 if let Some(Value::String(encoded)) = out.get("ops")
370 && let Ok(Value::Array(ops)) = serde_json::from_str::<Value>(encoded)
371 {
372 out.insert("ops".into(), Value::Array(ops));
373 repaired = true;
374 }
375 if !out.contains_key("ops") {
376 repaired |= repair(&mut out);
377 }
378 if let Some(Value::Array(ops)) = out.get_mut("ops") {
379 for op in ops.iter_mut().filter_map(Value::as_object_mut) {
380 repaired |= repair(op);
381 }
382 }
383 repaired.then_some(out)
384}
385
386fn delegated_op_kind(v: &Value) -> Option<&str> {
389 v.get("op")
390 .and_then(Value::as_str)
391 .filter(|k| matches!(*k, "replace_unique" | "replace_symbol"))
392}
393
394fn is_unbatchable_op(v: &Value) -> Option<&str> {
402 v.get("op")
403 .and_then(Value::as_str)
404 .filter(|k| matches!(*k, "replace_all" | "create"))
405}
406
407fn handle_mixed_batch(
408 args: &Map<String, Value>,
409 arr: &[Value],
410 ctx: &ToolContext,
411) -> Result<ToolOutput, ErrorData> {
412 for (i, v) in arr.iter().enumerate() {
414 if !v.is_object() {
415 return Err(ErrorData::invalid_params(
416 format!("ops[{i}] must be an object"),
417 None,
418 ));
419 }
420 if let Some(kind) = is_unbatchable_op(v) {
421 return Err(ErrorData::invalid_params(
422 format!(
423 "ops[{i}]: {kind} cannot be batched in ops[] \
424 — send it as a separate top-level ctx_patch call"
425 ),
426 None,
427 ));
428 }
429 }
430
431 let top_path = get_str(args, "path");
434 let mut targets = std::collections::BTreeSet::new();
435 let mut unknown_target = false;
436 for v in arr {
437 match v
438 .get("path")
439 .and_then(Value::as_str)
440 .or(top_path.as_deref())
441 {
442 Some(p) => {
443 targets.insert(p);
444 }
445 None => unknown_target = true,
446 }
447 }
448 let label_parts = unknown_target || targets.len() > 1;
449
450 let mut texts: Vec<String> = Vec::new();
451 let mut run: Vec<Value> = Vec::new();
452 for (i, v) in arr.iter().enumerate() {
453 let obj = v.as_object().ok_or_else(|| {
454 ErrorData::invalid_params(format!("ops[{i}] must be an object"), None)
455 })?;
456 let Some(kind) = delegated_op_kind(v) else {
457 run.push(v.clone());
458 continue;
459 };
460 flush_anchored_run(args, ctx, &mut run, &mut texts)?;
461
462 let (sub_args, sub_ctx) = delegated_op_call(args, obj, ctx, i, kind)
463 .map_err(|error| with_prior_edits(error, &texts))?;
464 let out = if kind == "replace_unique" {
465 delegate_replace_unique(&sub_args, &sub_ctx)
466 } else {
467 delegate_replace_symbol(&sub_args, &sub_ctx)
468 }
469 .map_err(|mut e| {
470 e.message = format!("ops[{i}] ({kind}): {}", e.message).into();
471 with_prior_edits(e, &texts)
472 })?;
473 if label_parts {
474 let label = sub_ctx.resolved_path("path").map_or_else(
475 || kind.to_string(),
476 |resolved| receipt_label(resolved, &ctx.project_root),
477 );
478 texts.push(format!("[{label}]\n{}", out.text));
479 } else {
480 texts.push(out.text);
481 }
482 }
483 flush_anchored_run(args, ctx, &mut run, &mut texts)?;
484
485 Ok(ToolOutput::simple(texts.join("\n\n")))
486}
487
488fn receipt_label(resolved: &str, project_root: &str) -> String {
494 let display = lean_ctx::core::protocol::display_path(resolved);
495 let canonical_root = std::fs::canonicalize(project_root).ok().map(|p| {
496 lean_ctx::core::pathutil::strip_verbatim(p)
497 .to_string_lossy()
498 .into_owned()
499 });
500 for root in std::iter::once(project_root.to_string()).chain(canonical_root) {
501 let root = lean_ctx::core::protocol::display_path(&root);
502 let root = root.trim_end_matches('/');
503 let (Some(head), Some(rest)) = (display.get(..root.len()), display.get(root.len()..))
504 else {
505 continue;
506 };
507 if root.is_empty() || rest.len() < 2 {
508 continue;
509 }
510 let same_root = if cfg!(windows) {
511 head.eq_ignore_ascii_case(root)
512 } else {
513 head == root
514 };
515 if same_root && let Some(rel) = rest.strip_prefix('/') {
516 return rel.to_string();
517 }
518 }
519 display
520}
521
522fn flush_anchored_run(
524 args: &Map<String, Value>,
525 ctx: &ToolContext,
526 run: &mut Vec<Value>,
527 texts: &mut Vec<String>,
528) -> Result<(), ErrorData> {
529 if run.is_empty() {
530 return Ok(());
531 }
532 let mut sub = args.clone();
533 sub.insert("ops".into(), Value::Array(std::mem::take(run)));
534 texts.push(
535 handle_anchored(&sub, ctx)
536 .map_err(|error| with_prior_edits(error, texts))?
537 .text,
538 );
539 Ok(())
540}
541
542fn with_prior_edits(mut error: ErrorData, texts: &[String]) -> ErrorData {
545 if !texts.is_empty() {
546 error.code = crate::server::tool_trait::TOOL_EXECUTION_ERROR;
547 error.message = format!(
548 "{}\nEarlier ops in this batch were already applied:\n{}",
549 error.message,
550 texts.join("\n\n")
551 )
552 .into();
553 }
554 error
555}
556
557fn delegated_op_call(
562 args: &Map<String, Value>,
563 op: &Map<String, Value>,
564 ctx: &ToolContext,
565 i: usize,
566 kind: &str,
567) -> Result<(Map<String, Value>, ToolContext), ErrorData> {
568 let mut sub = op.clone();
569 for key in ["path", "dry_run"] {
570 if !sub.contains_key(key)
571 && let Some(v) = args.get(key)
572 {
573 sub.insert(key.to_string(), v.clone());
574 }
575 }
576
577 let mut sub_ctx = ctx.clone();
578 sub_ctx.resolved_paths.remove("path");
579 sub_ctx.path_errors.remove("path");
580 match get_str(&sub, "path") {
581 Some(raw) => {
582 let resolved = resolve_op_path(&sub_ctx, &raw)
583 .map_err(|e| ErrorData::invalid_params(format!("ops[{i}]: path: {e}"), None))?;
584 sub_ctx
585 .ensure_writable(&resolved)
586 .map_err(|e| ErrorData::invalid_params(format!("ops[{i}]: {e}"), None))?;
587 sub_ctx.resolved_paths.insert("path".to_string(), resolved);
588 }
589 None if kind == "replace_unique" => {
592 return Err(ErrorData::invalid_params(
593 format!("ops[{i}] needs its own 'path' (no top-level 'path' to fall back to)"),
594 None,
595 ));
596 }
597 None => {}
598 }
599 Ok((sub, sub_ctx))
600}
601
602fn delegate_replace_unique(
606 args: &Map<String, Value>,
607 ctx: &ToolContext,
608) -> Result<ToolOutput, ErrorData> {
609 let edit_args =
610 build_unique_edit_args(args).map_err(|message| ErrorData::invalid_params(message, None))?;
611
612 if get_str(&edit_args, "old_string").is_some_and(|old| old.is_empty()) {
617 let path = require_resolved_path(ctx, args, "path")?;
618 if let Some(message) = empty_old_text_refusal(std::path::Path::new(&path)) {
619 return Err(ErrorData::invalid_params(message, None));
620 }
621 }
622
623 if get_bool(args, "dry_run").unwrap_or(false) {
624 let old_text = get_str(args, "old_text")
625 .or_else(|| get_str(args, "old_string"))
626 .unwrap_or_default();
627 let new_text = get_str(args, "new_text")
628 .or_else(|| get_str(args, "new_string"))
629 .unwrap_or_default();
630 let path = get_str(args, "path").unwrap_or_default();
631 return Ok(ToolOutput::simple(format!(
632 "DRY RUN: replace_unique would replace {old_text:?} with {new_text:?} in {path}"
633 )));
634 }
635
636 crate::tools::registered::ctx_edit::handle_edit(&edit_args, ctx, host_draws_diffs(ctx))
637}
638
639fn empty_old_text_refusal(path: &std::path::Path) -> Option<String> {
643 let shown = path.display();
644 match std::fs::symlink_metadata(path) {
645 Ok(meta) if meta.file_type().is_file() && meta.len() == 0 => None,
646 Ok(meta) if meta.file_type().is_file() => Some(format!(
647 "replace_unique with empty old_text only fills an existing empty (0-byte) file; \
648 {shown} has content. Quote unique text from it as old_text, or use anchored ops \
649 (ctx_read mode=\"anchored\" → insert_after/set_line/replace_lines)"
650 )),
651 Ok(_) => Some(format!(
652 "replace_unique with empty old_text only fills an existing empty regular file; \
653 {shown} is not one (symlink or directory)"
654 )),
655 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some(format!(
656 "replace_unique with empty old_text only fills an existing empty file; \
657 {shown} does not exist — use op=create to write a new file"
658 )),
659 Err(error) => Some(format!("cannot inspect {shown}: {error}")),
660 }
661}
662
663fn build_unique_edit_args(args: &Map<String, Value>) -> Result<Map<String, Value>, String> {
664 let old_text = get_str(args, "old_text")
667 .or_else(|| get_str(args, "old_string"))
668 .ok_or_else(|| {
669 "replace_unique requires old_text (old_string also accepted); an empty \
670 old_text fills an existing empty file"
671 .to_string()
672 })?;
673 let new_text = get_str(args, "new_text")
674 .or_else(|| get_str(args, "new_string"))
675 .ok_or_else(|| "replace_unique requires new_text (new_string also accepted)".to_string())?;
676
677 let mut edit_args = args.clone();
678 edit_args.insert("old_string".into(), Value::String(old_text));
679 edit_args.insert("new_string".into(), Value::String(new_text));
680 edit_args.insert("replace_all".into(), Value::Bool(false));
681 edit_args.remove("old_text");
682 edit_args.remove("op");
683 edit_args.remove("create");
686 Ok(edit_args)
687}
688
689fn validate_cross_file_options(
693 args: &Map<String, Value>,
694 file_count: usize,
695) -> Result<(), ErrorData> {
696 if file_count <= 1 {
697 return Ok(());
698 }
699 for key in ["expected_blake3", "expected_md5", "backup_path"] {
700 if args.contains_key(key) {
701 return Err(ErrorData::invalid_params(
702 format!("cross-file ctx_patch batches do not support top-level '{key}'"),
703 None,
704 ));
705 }
706 }
707 Ok(())
708}
709
710fn plan_groups(
715 args: &Map<String, Value>,
716 ctx: &ToolContext,
717) -> Result<Vec<(String, Vec<crate::tools::ctx_patch::AnchorOp>)>, ErrorData> {
718 let Some(ops_val) = args.get("ops") else {
719 let path = require_resolved_path(ctx, args, "path")?;
720 let ops = crate::tools::ctx_patch::parse_ops(args)
721 .map_err(|e| ErrorData::invalid_params(e, None))?;
722 return Ok(vec![(path, ops)]);
723 };
724
725 let arr = ops_val
726 .as_array()
727 .ok_or_else(|| ErrorData::invalid_params("ops must be an array of edit objects", None))?;
728 let grouped = group_ops_by_path(arr, get_str(args, "path").as_deref())
729 .map_err(|e| ErrorData::invalid_params(e, None))?;
730
731 let mut groups = Vec::with_capacity(grouped.len());
732 for (raw_path, op_objs) in grouped {
733 let resolved = resolve_op_path(ctx, &raw_path)
734 .map_err(|e| ErrorData::invalid_params(format!("path: {e}"), None))?;
735 ctx.ensure_writable(&resolved)
736 .map_err(|e| ErrorData::invalid_params(e, None))?;
737 let sub = Map::from_iter([("ops".to_string(), Value::Array(op_objs))]);
738 let ops = crate::tools::ctx_patch::parse_ops(&sub)
739 .map_err(|e| ErrorData::invalid_params(e, None))?;
740 groups.push((resolved, ops));
741 }
742 Ok(groups)
743}
744
745fn resolve_op_path(ctx: &ToolContext, raw: &str) -> Result<String, String> {
748 let base = crate::tools::path_base::is_relative(raw)
749 .then(|| crate::tools::path_base::active_base(ctx))
750 .flatten();
751 crate::tools::path_base::resolve_against_base(ctx, base.as_ref(), raw)
752}
753
754fn group_ops_by_path(
758 ops: &[Value],
759 top_path: Option<&str>,
760) -> Result<Vec<(String, Vec<Value>)>, String> {
761 if ops.is_empty() {
762 return Err("ops[] is empty — provide at least one edit".to_string());
763 }
764 let mut order: Vec<String> = Vec::new();
765 let mut by_path: std::collections::HashMap<String, Vec<Value>> =
766 std::collections::HashMap::new();
767 for (i, op) in ops.iter().enumerate() {
768 let obj = op
769 .as_object()
770 .ok_or_else(|| format!("ops[{i}] must be an object"))?;
771 let raw = obj
772 .get("path")
773 .and_then(Value::as_str)
774 .map(str::to_string)
775 .or_else(|| top_path.map(str::to_string))
776 .ok_or_else(|| {
777 format!("ops[{i}] needs its own 'path' (no top-level 'path' to fall back to)")
778 })?;
779 if !by_path.contains_key(&raw) {
780 order.push(raw.clone());
781 }
782 by_path.entry(raw).or_default().push(op.clone());
783 }
784 Ok(order
785 .into_iter()
786 .map(|p| {
787 let ops = by_path.remove(&p).unwrap_or_default();
788 (p, ops)
789 })
790 .collect())
791}
792
793fn apply_one(
798 ctx: &ToolContext,
799 params: &crate::tools::ctx_patch::PatchParams,
800) -> Result<String, ErrorData> {
801 let path = params.path.clone();
802 {
803 let cache_lock = ctx
804 .cache
805 .as_ref()
806 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
807
808 let file_lock = lean_ctx::core::path_locks::per_file_lock(&path);
813 let _file_guard = {
814 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
815 loop {
816 if let Ok(guard) = file_lock.try_lock() {
817 break guard;
818 }
819 if std::time::Instant::now() >= deadline {
820 return Err(ErrorData::internal_error(
821 format!(
822 "per-file edit lock contention for {path} — another edit to the same file is in progress, retry in a moment"
823 ),
824 None,
825 ));
826 }
827 std::thread::sleep(std::time::Duration::from_millis(20));
828 }
829 };
830
831 let last_mode = match crate::server::bounded_lock::read(cache_lock, "ctx_patch cache read")
832 {
833 Some(cache) => cache
834 .get(&path)
835 .map(|e| e.last_mode.clone())
836 .unwrap_or_default(),
837 None => String::new(),
838 };
839
840 let before = std::fs::read(&path).unwrap_or_default();
842 let (output, effect) = crate::tools::ctx_patch::run_io(params, &last_mode);
843 let written = matches!(effect, crate::tools::ctx_edit::CacheEffect::Invalidate);
844
845 if written {
846 let after = std::fs::read(&path).unwrap_or_default();
847 super::ctx_edit::observe_mcp_edit(ctx, &path, "ctx_patch", &before, &after);
848 }
849
850 crate::tools::ctx_patch::record_outcome(params, &last_mode, &output, &effect);
851
852 if !matches!(effect, crate::tools::ctx_edit::CacheEffect::None) {
853 crate::tools::ctx_read::dedup_hook::on_write(&path);
854 match crate::server::bounded_lock::write(cache_lock, "ctx_patch cache write") {
855 Some(mut cache) => {
856 crate::tools::ctx_edit::apply_cache_effect(&mut cache, &path, effect);
857 }
858 None => {
859 tracing::warn!(
860 "ctx_patch: cache write-lock timeout applying effect for {path}"
861 );
862 }
863 }
864 }
865
866 if !written {
867 return Err(tool_execution_error(output));
868 }
869
870 if let Some(session_lock) = ctx.session.as_ref() {
871 if let Some(mut session) =
872 crate::server::bounded_lock::write(session_lock, "ctx_patch session write")
873 {
874 session.mark_modified(&path);
875 }
876 }
877
878 Ok(output)
879 }
880}
881
882fn delegate_replace_symbol(
887 args: &Map<String, Value>,
888 ctx: &ToolContext,
889) -> Result<ToolOutput, ErrorData> {
890 let refactor_args = crate::tools::ctx_patch::build_refactor_args(args)
891 .map_err(|e| ErrorData::invalid_params(e, None))?;
892
893 if get_bool(args, "dry_run").unwrap_or(false) {
894 let name = get_str(args, "name").unwrap_or_default();
895 let path = get_str(args, "path").unwrap_or_default();
896 return Ok(ToolOutput::simple(format!(
897 "DRY RUN: replace_symbol would rewrite symbol {name:?} in {path}"
898 )));
899 }
900
901 let has_path = args.get("path").and_then(Value::as_str).is_some();
905 let abs_path = if has_path {
906 require_resolved_path(ctx, args, "path")?
907 } else {
908 String::new()
909 };
910
911 let args_value = Value::Object(refactor_args);
912 let result = crate::tools::ctx_refactor::handle(&args_value, &ctx.project_root, &abs_path);
913 let changed = !result.starts_with("ERROR") && !result.starts_with("CONFLICT");
914 if !changed {
915 return Err(tool_execution_error(result));
916 }
917
918 Ok(ToolOutput {
919 text: result,
920 original_tokens: 0,
921 saved_tokens: 0,
922 mode: Some("replace_symbol".to_string()),
923 path: get_str(args, "path"),
924 changed,
925 shell_outcome: None,
926 content_blocks: None,
927 })
928}
929
930fn resolve_find_replace(args: &Map<String, Value>) -> Result<(String, String), String> {
942 let find = aliased(args, "find", &["old_string", "old_text"])?
943 .filter(|s| !s.is_empty())
944 .ok_or("replace_all requires non-empty 'find' (old_string also accepted)")?;
945 let replace = aliased(args, "replace", &["new_string", "new_text"])?.ok_or(
946 "replace_all requires 'replace' (the replacement text, new_string also accepted); \
947 pass replace=\"\" explicitly to delete every match",
948 )?;
949 Ok((find, replace))
950}
951
952fn aliased(
955 args: &Map<String, Value>,
956 key: &str,
957 aliases: &[&str],
958) -> Result<Option<String>, String> {
959 let mut found: Option<(&str, &str)> = None;
960 for name in std::iter::once(key).chain(aliases.iter().copied()) {
961 let Some(value) = args.get(name).and_then(Value::as_str) else {
962 continue;
963 };
964 match found {
965 Some((first, seen)) if seen != value => {
966 return Err(format!(
967 "'{first}' and '{name}' name the same field with different values — pass only one"
968 ));
969 }
970 Some(_) => {}
971 None => found = Some((name, value)),
972 }
973 }
974 Ok(found.map(|(_, value)| value.to_string()))
975}
976
977fn replace_all_plan(
994 path: &str,
995 root: &str,
996 find: &str,
997) -> Result<(crate::tools::edit_io::FilePreimage, usize), String> {
998 use crate::tools::admitted_sources::SourceRead;
999 let cap = lean_ctx::core::limits::max_read_bytes();
1000 let original = crate::tools::edit_io::read_preimage(std::path::Path::new(path), cap, false)?;
1001 let mut remaining = cap;
1002 let admitted =
1003 match crate::tools::admitted_sources::read(path, root, "ctx_patch", &mut remaining) {
1004 SourceRead::Admitted(read) => read.content,
1005 SourceRead::Withheld(reason) | SourceRead::Unavailable(reason) => {
1006 return Err(format!("cannot read {path}: {reason}"));
1007 }
1008 };
1009 let count = admitted.matches(find).count();
1010 if count != original.text.matches(find).count() {
1011 return Err(format!(
1012 "replace_all refused for {path}: the pattern overlaps content the context gateway \
1013 masks; nothing was changed"
1014 ));
1015 }
1016 Ok((original, count))
1017}
1018
1019fn replace_all_write(
1023 path: &str,
1024 pre: &crate::tools::edit_io::FilePreimage,
1025 new_content: &str,
1026) -> Result<(), String> {
1027 let path = std::path::Path::new(path);
1028 crate::tools::claims_gate::before_write(path, Some(&pre.text), new_content)?;
1029 crate::tools::edit_io::ensure_preimage_still_matches(
1030 path,
1031 &pre.fp,
1032 lean_ctx::core::limits::max_read_bytes(),
1033 )?;
1034 crate::tools::edit_io::write_atomic_bytes_with_permissions(
1035 path,
1036 new_content.as_bytes(),
1037 Some(&pre.permissions),
1038 )
1039}
1040
1041fn handle_replace_all(
1043 args: &Map<String, Value>,
1044 ctx: &ToolContext,
1045) -> Result<ToolOutput, ErrorData> {
1046 let path = require_resolved_path(ctx, args, "path")?;
1047 let (find, replace) =
1048 resolve_find_replace(args).map_err(|e| ErrorData::invalid_params(e, None))?;
1049 let dry_run = get_bool(args, "dry_run").unwrap_or(false);
1050
1051 let file_lock = lean_ctx::core::path_locks::per_file_lock(&path);
1054 let _guard = file_lock
1055 .lock()
1056 .map_err(|_| ErrorData::internal_error(format!("lock contention for {path}"), None))?;
1057
1058 let root = crate::tools::admitted_sources::root_in_context(&path, ctx);
1059 let (pre, count) = replace_all_plan(&path, &root, &find).map_err(tool_execution_error)?;
1060 if count == 0 {
1061 return Ok(ToolOutput::simple(format!(
1062 "No matches for {find:?} in {path}"
1063 )));
1064 }
1065
1066 if dry_run {
1067 return Ok(ToolOutput::simple(format!(
1068 "DRY RUN: {count} occurrence(s) of {find:?} would be replaced with {replace:?} in {path}"
1069 )));
1070 }
1071
1072 let new_content = pre.text.replace(find.as_str(), &replace);
1073 replace_all_write(&path, &pre, &new_content).map_err(tool_execution_error)?;
1074 super::ctx_edit::observe_mcp_edit(ctx, &path, "ctx_patch", &pre.bytes, new_content.as_bytes());
1075
1076 crate::tools::ctx_read::dedup_hook::on_write(&path);
1077 if let Some(cache) = ctx.cache.as_ref() {
1078 if let Some(mut c) =
1079 crate::server::bounded_lock::write(cache, "ctx_patch replace_all cache invalidate")
1080 {
1081 c.invalidate(&path);
1082 }
1083 }
1084 if let Some(session_lock) = ctx.session.as_ref() {
1085 if let Some(mut session) =
1086 crate::server::bounded_lock::write(session_lock, "ctx_patch replace_all session")
1087 {
1088 session.mark_modified(&path);
1089 }
1090 }
1091
1092 Ok(ToolOutput::simple(format!(
1093 "Replaced {count} occurrence(s) of {find:?} with {replace:?} in {path}"
1094 )))
1095}
1096
1097#[cfg(test)]
1098mod replace_all_tests {
1099 use super::*;
1100 use serde_json::json;
1101
1102 fn obj(v: Value) -> Map<String, Value> {
1103 match v {
1104 Value::Object(m) => m,
1105 _ => panic!("expected object"),
1106 }
1107 }
1108
1109 #[test]
1110 fn resolves_find_and_replace() {
1111 let (f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": "b"}))).unwrap();
1112 assert_eq!((f.as_str(), r.as_str()), ("a", "b"));
1113 }
1114
1115 #[test]
1116 fn explicit_empty_replace_is_a_deletion() {
1117 let (_f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": ""}))).unwrap();
1118 assert_eq!(r, "");
1119 }
1120
1121 #[test]
1122 fn missing_replace_is_rejected_not_silent_delete() {
1123 let err = resolve_find_replace(&obj(json!({"find": "a"}))).unwrap_err();
1124 assert!(err.contains("requires 'replace'"), "got: {err}");
1125 }
1126
1127 #[test]
1128 fn other_ops_names_are_aliases() {
1129 for (old, new) in [("old_string", "new_string"), ("old_text", "new_text")] {
1130 let (f, r) = resolve_find_replace(&obj(json!({old: "a", new: "b"}))).unwrap();
1131 assert_eq!((f.as_str(), r.as_str()), ("a", "b"), "{old}/{new}");
1132 }
1133 }
1134
1135 #[test]
1136 fn alias_never_turns_a_missing_replacement_into_a_delete() {
1137 let err = resolve_find_replace(&obj(json!({"old_string": "a"}))).unwrap_err();
1138 assert!(err.contains("requires 'replace'"), "got: {err}");
1139 }
1140
1141 #[test]
1142 fn conflicting_spellings_are_rejected() {
1143 let err = resolve_find_replace(&obj(
1144 json!({"find": "a", "old_string": "x", "replace": "b"}),
1145 ))
1146 .unwrap_err();
1147 assert!(
1148 err.contains("find") && err.contains("old_string"),
1149 "got: {err}"
1150 );
1151 let same = resolve_find_replace(&obj(
1152 json!({"find": "a", "old_string": "a", "replace": "b"}),
1153 ));
1154 assert!(same.is_ok(), "identical spellings agree");
1155 }
1156
1157 #[test]
1158 fn empty_find_is_rejected() {
1159 let err = resolve_find_replace(&obj(json!({"find": "", "replace": "b"}))).unwrap_err();
1160 assert!(err.contains("find"), "got: {err}");
1161 }
1162
1163 #[test]
1169 fn the_reported_count_comes_from_the_admitted_text_and_the_original_is_what_is_written() {
1170 use lean_ctx::core::policy::runtime::TestPolicyOverride;
1171 let _data = lean_ctx::core::data_dir::isolated_data_dir();
1172 let policy = lean_ctx::core::policy::load(
1173 "name = \"ctx-patch-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
1174 [redaction]\ncustomer = \"CUS-[0-9]{4}\"\n\
1175 [filters]\nclassification = \"block\"\nblocked_labels = [\"CONFIDENTIAL\"]\n",
1176 )
1177 .unwrap();
1178 let project = tempfile::tempdir().unwrap();
1179 let root = project.path().to_string_lossy().into_owned();
1180 let file = |name: &str, content: &str| {
1181 let path = project.path().join(name);
1182 std::fs::write(&path, content).unwrap();
1183 path.to_string_lossy().into_owned()
1184 };
1185 let original = "let owner = \"CUS-1234\";\nlet mode = old_mode();\nold_mode();\n";
1186 let orders = file("orders.rs", original);
1187 let plan = file("plan.rs", "CONFIDENTIAL\nold_mode();\n");
1188 let planned = |path: &str, find: &str| {
1189 replace_all_plan(path, &root, find).map(|(pre, count)| (pre.text, count))
1190 };
1191 {
1192 let _community = TestPolicyOverride::set(None);
1194 assert_eq!(planned(&orders, "old_mode"), Ok((original.to_string(), 2)));
1195 }
1196 let _policy = TestPolicyOverride::set(Some(policy));
1197 assert_eq!(planned(&orders, "old_mode"), Ok((original.to_string(), 2)));
1199 let refused = replace_all_plan(&orders, &root, "CUS-1234").unwrap_err();
1201 assert!(refused.contains("refused"), "{refused}");
1202 assert!(!refused.contains("1 occurrence"), "{refused}");
1203 let withheld = replace_all_plan(&plan, &root, "old_mode").unwrap_err();
1205 assert!(withheld.contains("withheld"), "{withheld}");
1206 assert!(replace_all_plan(&orders, "", "old_mode").is_err());
1208 }
1209
1210 #[test]
1214 fn replace_all_uses_the_edit_boundary() {
1215 let _data = lean_ctx::core::data_dir::isolated_data_dir();
1216 let project = tempfile::tempdir().unwrap();
1217 let root = project.path().to_string_lossy().into_owned();
1218 let target = project.path().join("a.rs");
1219 std::fs::write(&target, "old();\nold();\n").unwrap();
1220 let target_str = target.to_string_lossy().into_owned();
1221
1222 #[cfg(unix)]
1223 {
1224 let link = project.path().join("link.rs");
1225 std::os::unix::fs::symlink(&target, &link).unwrap();
1226 let err = replace_all_plan(&link.to_string_lossy(), &root, "old").unwrap_err();
1227 assert!(err.contains("symlink"), "{err}");
1228 }
1229
1230 let (pre, count) = replace_all_plan(&target_str, &root, "old").unwrap();
1231 assert_eq!(count, 2);
1232 std::fs::write(&target, "old();\nnewer();\n").unwrap();
1234 let new_content = pre.text.replace("old", "new");
1235 let err = replace_all_write(&target_str, &pre, &new_content).unwrap_err();
1236 assert!(err.contains("TOCTOU"), "{err}");
1237 assert_eq!(
1238 std::fs::read_to_string(&target).unwrap(),
1239 "old();\nnewer();\n"
1240 );
1241
1242 let (pre, _) = replace_all_plan(&target_str, &root, "old").unwrap();
1244 let new_content = pre.text.replace("old", "new");
1245 replace_all_write(&target_str, &pre, &new_content).unwrap();
1246 assert_eq!(
1247 std::fs::read_to_string(&target).unwrap(),
1248 "new();\nnewer();\n"
1249 );
1250 }
1251}
1252
1253#[cfg(test)]
1254mod batch_grouping_tests {
1255 use super::*;
1256 use serde_json::json;
1257
1258 #[test]
1261 fn groups_ops_across_files_preserving_order() {
1262 let ops = vec![
1263 json!({"op":"insert_after","path":"a.go","line":1,"hash":"aa","new_text":"x"}),
1264 json!({"op":"insert_after","path":"b.go","line":2,"hash":"bb","new_text":"y"}),
1265 json!({"op":"set_line","path":"a.go","line":3,"hash":"cc","new_text":"z"}),
1266 ];
1267 let g = group_ops_by_path(&ops, None).unwrap();
1268 assert_eq!(g.len(), 2);
1269 assert_eq!(g[0].0, "a.go");
1270 assert_eq!(g[0].1.len(), 2);
1271 assert_eq!(g[1].0, "b.go");
1272 assert_eq!(g[1].1.len(), 1);
1273 }
1274
1275 #[test]
1276 fn ops_without_path_fall_back_to_top_level() {
1277 let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
1278 let g = group_ops_by_path(&ops, Some("top.go")).unwrap();
1279 assert_eq!(g.len(), 1);
1280 assert_eq!(g[0].0, "top.go");
1281 }
1282
1283 #[test]
1284 fn op_without_path_and_no_top_level_is_rejected() {
1285 let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
1286 let err = group_ops_by_path(&ops, None).unwrap_err();
1287 assert!(err.contains("path"), "got: {err}");
1288 }
1289
1290 #[test]
1291 fn empty_ops_rejected() {
1292 let err = group_ops_by_path(&[], None).unwrap_err();
1293 assert!(err.contains("empty"), "got: {err}");
1294 }
1295
1296 #[test]
1297 fn cross_file_rejects_single_value_preimage_and_backup_options() {
1298 for key in ["expected_blake3", "expected_md5", "backup_path"] {
1299 let args = Map::from_iter([(key.to_string(), json!("one-value"))]);
1300 assert!(validate_cross_file_options(&args, 2).is_err());
1301 assert!(validate_cross_file_options(&args, 1).is_ok());
1302 }
1303 }
1304
1305 #[test]
1306 fn replace_unique_maps_to_a_single_safe_ctx_edit_replacement() {
1307 let args = Map::from_iter([
1308 ("path".into(), json!("a.rs")),
1309 ("op".into(), json!("replace_unique")),
1310 ("old_text".into(), json!("old")),
1311 ("new_text".into(), json!("new")),
1312 ]);
1313 let mapped = build_unique_edit_args(&args).expect("valid mapping");
1314 assert_eq!(mapped.get("old_string"), Some(&json!("old")));
1315 assert_eq!(mapped.get("new_string"), Some(&json!("new")));
1316 assert_eq!(mapped.get("replace_all"), Some(&json!(false)));
1317 assert!(!mapped.contains_key("op"));
1318 assert!(!mapped.contains_key("old_text"));
1319 }
1320
1321 #[test]
1322 fn replace_unique_requires_explicit_old_and_new_text() {
1323 assert!(build_unique_edit_args(&Map::new()).is_err());
1324 let only_old = Map::from_iter([("old_text".into(), json!("old"))]);
1325 assert!(build_unique_edit_args(&only_old).is_err());
1326 }
1327
1328 #[test]
1329 fn dry_run_replace_unique_does_not_apply() {
1330 let args = Map::from_iter([
1331 ("path".into(), json!("a.rs")),
1332 ("op".into(), json!("replace_unique")),
1333 ("old_text".into(), json!("old")),
1334 ("new_text".into(), json!("new")),
1335 ("dry_run".into(), json!(true)),
1336 ]);
1337 let edit_args = build_unique_edit_args(&args).expect("validation passes");
1338 assert!(
1339 edit_args.contains_key("old_string"),
1340 "args mapped correctly"
1341 );
1342 assert!(
1343 args.get("dry_run").and_then(Value::as_bool) == Some(true),
1344 "dry_run flag preserved in original args"
1345 );
1346 }
1347
1348 #[test]
1349 fn text_replacement_without_op_is_inferred_as_replace_unique() {
1350 let top = Map::from_iter([
1351 ("path".into(), json!("a.rs")),
1352 ("old_string".into(), json!("old")),
1353 ("new_string".into(), json!("new")),
1354 ]);
1355 let inferred = infer_replace_unique(&top).expect("op inferred");
1356 assert_eq!(inferred.get("op"), Some(&json!("replace_unique")));
1357
1358 let batch = Map::from_iter([(
1359 "ops".into(),
1360 json!([
1361 {"path": "a.rs", "old_text": "a", "new_text": "b"},
1362 {"op": "set_line", "line": 1, "hash": "aa", "new_text": "x"}
1363 ]),
1364 )]);
1365 let inferred = infer_replace_unique(&batch).expect("op inferred in ops[]");
1366 assert_eq!(inferred["ops"][0]["op"], json!("replace_unique"));
1367 assert_eq!(inferred["ops"][1]["op"], json!("set_line"));
1368
1369 for unchanged in [
1371 json!({"op": "set_line", "old_text": "a", "new_text": "b"}),
1372 json!({"old_text": "", "new_text": "b"}),
1373 json!({"old_text": "a"}),
1374 ] {
1375 assert!(infer_replace_unique(unchanged.as_object().unwrap()).is_none());
1376 }
1377
1378 let encoded = json!({"ops": "[{\"op\":\"replace_unique\",\"path\":\"a.rs\",\"old_text\":\"a\",\"new_text\":\"b\"}]"});
1380 let repaired = infer_replace_unique(encoded.as_object().unwrap()).expect("ops decoded");
1381 assert_eq!(repaired["ops"][0]["old_text"], json!("a"));
1382 let create = json!({"op": "create", "path": "n.py", "new_string": "x = 1\n"});
1383 let repaired = infer_replace_unique(create.as_object().unwrap()).expect("create aliased");
1384 assert_eq!(repaired["new_text"], json!("x = 1\n"));
1385 let find_replace =
1386 json!({"op": "replace_unique", "path": "a.rs", "find": "a", "replace": "b"});
1387 let repaired = infer_replace_unique(find_replace.as_object().unwrap()).expect("aliased");
1388 assert_eq!(
1389 (&repaired["old_text"], &repaired["new_text"]),
1390 (&json!("a"), &json!("b"))
1391 );
1392 let replace_all = json!({"op": "replace_all", "path": "a.rs", "find": "a", "replace": "b"});
1394 assert!(infer_replace_unique(replace_all.as_object().unwrap()).is_none());
1395 }
1396
1397 fn empty_old_text_patch(
1400 root: &std::path::Path,
1401 path: &std::path::Path,
1402 ) -> Result<String, ErrorData> {
1403 let resolved = path.to_string_lossy().into_owned();
1404 let ctx = ToolContext {
1405 project_root: root.to_string_lossy().into_owned(),
1406 resolved_paths: std::collections::HashMap::from([("path".into(), resolved.clone())]),
1407 cache: Some(std::sync::Arc::new(tokio::sync::RwLock::new(
1408 lean_ctx::core::cache::SessionCache::new(),
1409 ))),
1410 ..ToolContext::default()
1411 };
1412 let args = json!({
1413 "op": "replace_unique", "path": resolved, "old_text": "", "new_text": "filled\n"
1414 });
1415 tokio::task::block_in_place(|| CtxPatchTool.handle(args.as_object().unwrap(), &ctx))
1416 .map(|out| out.text)
1417 }
1418
1419 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1420 async fn replace_unique_with_empty_old_text_fills_an_empty_file() {
1421 let _iso = lean_ctx::core::data_dir::isolated_data_dir();
1423 let dir = tempfile::tempdir().unwrap();
1424 let file = dir.path().join("empty.txt");
1425 std::fs::write(&file, "").unwrap();
1426 let text = empty_old_text_patch(dir.path(), &file).expect("empty file is filled");
1427 assert!(text.contains("created empty.txt"), "{text}");
1428 assert_eq!(std::fs::read_to_string(&file).unwrap(), "filled\n");
1429 }
1430
1431 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1432 async fn replace_unique_with_empty_old_text_refuses_other_targets() {
1433 let _iso = lean_ctx::core::data_dir::isolated_data_dir();
1434 let dir = tempfile::tempdir().unwrap();
1435
1436 let full = dir.path().join("full.txt");
1437 std::fs::write(&full, "keep\n").unwrap();
1438 let err = empty_old_text_patch(dir.path(), &full).unwrap_err();
1439 assert!(err.message.contains("anchored"), "{}", err.message);
1440 assert_eq!(std::fs::read_to_string(&full).unwrap(), "keep\n");
1441
1442 let missing = dir.path().join("missing.txt");
1443 let err = empty_old_text_patch(dir.path(), &missing).unwrap_err();
1444 assert!(err.message.contains("op=create"), "{}", err.message);
1445 assert!(!missing.exists(), "replace_unique must not create files");
1446
1447 #[cfg(unix)]
1448 {
1449 let target = dir.path().join("target.txt");
1450 std::fs::write(&target, "").unwrap();
1451 let link = dir.path().join("link.txt");
1452 std::os::unix::fs::symlink(&target, &link).unwrap();
1453 let err = empty_old_text_patch(dir.path(), &link).unwrap_err();
1454 assert!(err.message.contains("not one"), "{}", err.message);
1455 assert_eq!(std::fs::read_to_string(&target).unwrap(), "");
1456 }
1457 }
1458
1459 #[test]
1460 fn replace_unique_never_forwards_a_whole_file_create() {
1461 let args = Map::from_iter([
1462 ("old_text".into(), json!("old")),
1463 ("new_text".into(), json!("new")),
1464 ("create".into(), json!(true)),
1465 ]);
1466 let mapped = build_unique_edit_args(&args).expect("valid mapping");
1467 assert!(!mapped.contains_key("create"));
1468 }
1469}