1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{
6 McpTool, ToolContext, ToolOutput, get_bool, get_int, get_str, require_resolved_path,
7 tool_execution_error,
8};
9use crate::tool_defs::tool_def;
10
11pub struct CtxPatchTool;
12
13impl McpTool for CtxPatchTool {
14 fn name(&self) -> &'static str {
15 "ctx_patch"
16 }
17
18 fn tool_def(&self) -> Tool {
25 tool_def(
26 "ctx_patch",
27 "Safe file edit. Anchored ops use line+hash from ctx_read(mode=\"anchored\"); \
28 CONFLICT means re-read. replace_unique(path,old_text,new_text) is a no-read, \
29 exact unique replacement. replace_symbol/create/replace_all supported as \
30 top-level ops. Cross-file ops[] batch (incl. replace_unique) supported; \
31 replace_all and create must be sent as separate top-level calls, not inside ops[].",
32 json!({
33 "type": "object",
34 "properties": {
35 "path": { "type": "string" },
36 "op": { "type": "string", "enum": ["set_line", "replace_lines", "insert_after", "delete", "replace_unique", "replace_symbol", "create", "replace_all"] },
37 "line": { "type": "integer" },
38 "hash": { "type": "string" },
39 "start_line": { "type": "integer" },
40 "start_hash": { "type": "string" },
41 "end_line": { "type": "integer" },
42 "end_hash": { "type": "string" },
43 "new_text": { "type": "string" },
44 "old_text": { "type": "string" },
45 "name": { "type": "string" },
46 "find": { "type": "string" },
47 "replace": { "type": "string" },
48 "dry_run": { "type": "boolean" },
49 "ops": { "type": "array", "items": { "type": "object" } }
50 },
51 "allOf": [
59 { "if": { "properties": { "op": { "const": "set_line" } }, "required": ["op"] },
60 "then": { "required": ["op", "line", "hash", "new_text"] } },
61 { "if": { "properties": { "op": { "const": "replace_lines" } }, "required": ["op"] },
62 "then": { "required": ["op", "start_line", "start_hash", "end_line", "end_hash", "new_text"] } },
63 { "if": { "properties": { "op": { "const": "replace_unique" } }, "required": ["op"] },
64 "then": { "required": ["op", "old_text", "new_text"] } },
65 { "if": { "properties": { "op": { "const": "replace_symbol" } }, "required": ["op"] },
66 "then": { "required": ["op", "new_text"] } },
67 { "if": { "properties": { "op": { "const": "create" } }, "required": ["op"] },
68 "then": { "required": ["op", "new_text"] } },
69 { "if": { "properties": { "op": { "const": "replace_all" } }, "required": ["op"] },
70 "then": { "required": ["op", "find", "replace"] } }
71 ]
72 }),
73 )
74 }
75
76 fn handle(
77 &self,
78 args: &Map<String, Value>,
79 ctx: &ToolContext,
80 ) -> Result<ToolOutput, ErrorData> {
81 let inferred = infer_replace_unique(args);
82 let args = inferred.as_ref().unwrap_or(args);
83
84 if crate::tools::ctx_patch::is_replace_symbol(args) {
87 return delegate_replace_symbol(args, ctx);
88 }
89
90 if get_str(args, "op").as_deref() == Some("replace_unique") {
91 return delegate_replace_unique(args, ctx);
92 }
93
94 if get_str(args, "op").as_deref() == Some("replace_all") {
96 return handle_replace_all(args, ctx);
97 }
98
99 if let Some(arr) = args.get("ops").and_then(Value::as_array) {
103 for (i, v) in arr.iter().enumerate() {
105 if let Some(kind) = is_unbatchable_op(v) {
106 return Err(ErrorData::invalid_params(
107 format!(
108 "ops[{i}]: {kind} cannot be batched in ops[] \
109 — send it as a separate top-level ctx_patch call"
110 ),
111 None,
112 ));
113 }
114 }
115 if arr.iter().any(|v| delegated_op_kind(v).is_some()) {
116 return handle_mixed_batch(args, arr, ctx);
117 }
118 }
119
120 handle_anchored(args, ctx)
121 }
122}
123
124fn handle_anchored(args: &Map<String, Value>, ctx: &ToolContext) -> Result<ToolOutput, ErrorData> {
128 if get_bool(args, "dry_run").unwrap_or(false) {
129 let path = get_str(args, "path").unwrap_or_default();
130 return Ok(ToolOutput::simple(format!(
131 "DRY RUN: ctx_patch would apply anchor-based ops to {path}"
132 )));
133 }
134
135 let expected_blake3 =
138 get_str(args, "expected_blake3").or_else(|| get_str(args, "expected_md5"));
139 let backup = get_bool(args, "backup").unwrap_or(false);
140 let backup_path = get_str(args, "backup_path")
141 .map(|p| ctx.resolved_paths.get("backup_path").cloned().unwrap_or(p));
142 let evidence = get_bool(args, "evidence").unwrap_or(true);
143 let diff_max_lines = get_int(args, "diff_max_lines")
144 .and_then(|v| usize::try_from(v.max(0)).ok())
145 .unwrap_or(200);
146 let allow_lossy_utf8 = get_bool(args, "allow_lossy_utf8").unwrap_or(false);
147 let validate_syntax = get_bool(args, "validate_syntax").unwrap_or(true);
148
149 let groups = plan_groups(args, ctx)?;
153 validate_cross_file_options(args, groups.len())?;
154 let output_path = (groups.len() == 1).then(|| groups[0].0.clone());
155
156 let mut texts = Vec::with_capacity(groups.len());
157 for (path, ops) in groups {
158 let patch_params = crate::tools::ctx_patch::PatchParams {
159 path: path.clone(),
160 ops,
161 expected_blake3: expected_blake3.clone(),
162 backup,
163 backup_path: backup_path.clone(),
164 evidence,
165 diff_max_lines,
166 allow_lossy_utf8,
167 validate_syntax,
168 };
169 let output =
170 apply_one(ctx, &patch_params).map_err(|error| with_prior_edits(error, &texts))?;
171 texts.push(format!("[{path}]\n{output}"));
172 }
173
174 Ok(ToolOutput {
175 text: texts.join("\n\n"),
176 original_tokens: 0,
177 saved_tokens: 0,
178 mode: None,
179 path: output_path,
180 changed: false,
181 shell_outcome: None,
182 content_blocks: None,
183 })
184}
185
186fn infer_replace_unique(args: &Map<String, Value>) -> Option<Map<String, Value>> {
191 fn is_text_replacement(obj: &Map<String, Value>) -> bool {
192 let text = |keys: [&str; 2]| keys.iter().find_map(|key| obj.get(*key)?.as_str());
193 !obj.contains_key("op")
194 && text(["old_text", "old_string"]).is_some_and(|old| !old.is_empty())
195 && text(["new_text", "new_string"]).is_some()
196 }
197 let mut out = args.clone();
198 let mut inferred = false;
199 if !out.contains_key("ops") && is_text_replacement(&out) {
200 out.insert("op".into(), json!("replace_unique"));
201 inferred = true;
202 }
203 if let Some(Value::Array(ops)) = out.get_mut("ops") {
204 for op in ops.iter_mut().filter_map(Value::as_object_mut) {
205 if is_text_replacement(op) {
206 op.insert("op".into(), json!("replace_unique"));
207 inferred = true;
208 }
209 }
210 }
211 inferred.then_some(out)
212}
213
214fn delegated_op_kind(v: &Value) -> Option<&str> {
217 v.get("op")
218 .and_then(Value::as_str)
219 .filter(|k| matches!(*k, "replace_unique" | "replace_symbol"))
220}
221
222fn is_unbatchable_op(v: &Value) -> Option<&str> {
230 v.get("op")
231 .and_then(Value::as_str)
232 .filter(|k| matches!(*k, "replace_all" | "create"))
233}
234
235fn handle_mixed_batch(
236 args: &Map<String, Value>,
237 arr: &[Value],
238 ctx: &ToolContext,
239) -> Result<ToolOutput, ErrorData> {
240 for (i, v) in arr.iter().enumerate() {
242 if !v.is_object() {
243 return Err(ErrorData::invalid_params(
244 format!("ops[{i}] must be an object"),
245 None,
246 ));
247 }
248 if let Some(kind) = is_unbatchable_op(v) {
249 return Err(ErrorData::invalid_params(
250 format!(
251 "ops[{i}]: {kind} cannot be batched in ops[] \
252 — send it as a separate top-level ctx_patch call"
253 ),
254 None,
255 ));
256 }
257 }
258
259 let mut texts: Vec<String> = Vec::new();
260 let mut run: Vec<Value> = Vec::new();
261 for (i, v) in arr.iter().enumerate() {
262 let obj = v.as_object().ok_or_else(|| {
263 ErrorData::invalid_params(format!("ops[{i}] must be an object"), None)
264 })?;
265 let Some(kind) = delegated_op_kind(v) else {
266 run.push(v.clone());
267 continue;
268 };
269 flush_anchored_run(args, ctx, &mut run, &mut texts)?;
270
271 let (sub_args, sub_ctx) = delegated_op_call(args, obj, ctx, i, kind)
272 .map_err(|error| with_prior_edits(error, &texts))?;
273 let out = if kind == "replace_unique" {
274 delegate_replace_unique(&sub_args, &sub_ctx)
275 } else {
276 delegate_replace_symbol(&sub_args, &sub_ctx)
277 }
278 .map_err(|mut e| {
279 e.message = format!("ops[{i}] ({kind}): {}", e.message).into();
280 with_prior_edits(e, &texts)
281 })?;
282 let label = get_str(&sub_args, "path").unwrap_or_else(|| kind.to_string());
283 texts.push(format!("[{label}]\n{}", out.text));
284 }
285 flush_anchored_run(args, ctx, &mut run, &mut texts)?;
286
287 Ok(ToolOutput::simple(texts.join("\n\n")))
288}
289
290fn flush_anchored_run(
292 args: &Map<String, Value>,
293 ctx: &ToolContext,
294 run: &mut Vec<Value>,
295 texts: &mut Vec<String>,
296) -> Result<(), ErrorData> {
297 if run.is_empty() {
298 return Ok(());
299 }
300 let mut sub = args.clone();
301 sub.insert("ops".into(), Value::Array(std::mem::take(run)));
302 texts.push(
303 handle_anchored(&sub, ctx)
304 .map_err(|error| with_prior_edits(error, texts))?
305 .text,
306 );
307 Ok(())
308}
309
310fn with_prior_edits(mut error: ErrorData, texts: &[String]) -> ErrorData {
313 if !texts.is_empty() {
314 error.code = crate::server::tool_trait::TOOL_EXECUTION_ERROR;
315 error.message = format!(
316 "{}\nEarlier ops in this batch were already applied:\n{}",
317 error.message,
318 texts.join("\n\n")
319 )
320 .into();
321 }
322 error
323}
324
325fn delegated_op_call(
330 args: &Map<String, Value>,
331 op: &Map<String, Value>,
332 ctx: &ToolContext,
333 i: usize,
334 kind: &str,
335) -> Result<(Map<String, Value>, ToolContext), ErrorData> {
336 let mut sub = op.clone();
337 for key in ["path", "dry_run"] {
338 if !sub.contains_key(key)
339 && let Some(v) = args.get(key)
340 {
341 sub.insert(key.to_string(), v.clone());
342 }
343 }
344
345 let mut sub_ctx = ctx.clone();
346 sub_ctx.resolved_paths.remove("path");
347 sub_ctx.path_errors.remove("path");
348 match get_str(&sub, "path") {
349 Some(raw) => {
350 let resolved = sub_ctx
351 .resolve_path_sync(&raw)
352 .map_err(|e| ErrorData::invalid_params(format!("ops[{i}]: path: {e}"), None))?;
353 sub_ctx
354 .ensure_writable(&resolved)
355 .map_err(|e| ErrorData::invalid_params(format!("ops[{i}]: {e}"), None))?;
356 sub_ctx.resolved_paths.insert("path".to_string(), resolved);
357 }
358 None if kind == "replace_unique" => {
361 return Err(ErrorData::invalid_params(
362 format!("ops[{i}] needs its own 'path' (no top-level 'path' to fall back to)"),
363 None,
364 ));
365 }
366 None => {}
367 }
368 Ok((sub, sub_ctx))
369}
370
371fn delegate_replace_unique(
375 args: &Map<String, Value>,
376 ctx: &ToolContext,
377) -> Result<ToolOutput, ErrorData> {
378 let edit_args =
379 build_unique_edit_args(args).map_err(|message| ErrorData::invalid_params(message, None))?;
380
381 if get_bool(args, "dry_run").unwrap_or(false) {
382 let old_text = get_str(args, "old_text")
383 .or_else(|| get_str(args, "old_string"))
384 .unwrap_or_default();
385 let new_text = get_str(args, "new_text")
386 .or_else(|| get_str(args, "new_string"))
387 .unwrap_or_default();
388 let path = get_str(args, "path").unwrap_or_default();
389 return Ok(ToolOutput::simple(format!(
390 "DRY RUN: replace_unique would replace {old_text:?} with {new_text:?} in {path}"
391 )));
392 }
393
394 crate::tools::registered::ctx_edit::CtxEditTool.handle(&edit_args, ctx)
395}
396
397fn build_unique_edit_args(args: &Map<String, Value>) -> Result<Map<String, Value>, String> {
398 let old_text = get_str(args, "old_text")
399 .or_else(|| get_str(args, "old_string"))
400 .filter(|text| !text.is_empty())
401 .ok_or_else(|| {
402 "replace_unique requires non-empty old_text (old_string also accepted)".to_string()
403 })?;
404 let new_text = get_str(args, "new_text")
405 .or_else(|| get_str(args, "new_string"))
406 .ok_or_else(|| "replace_unique requires new_text (new_string also accepted)".to_string())?;
407
408 let mut edit_args = args.clone();
409 edit_args.insert("old_string".into(), Value::String(old_text));
410 edit_args.insert("new_string".into(), Value::String(new_text));
411 edit_args.insert("replace_all".into(), Value::Bool(false));
412 edit_args.remove("old_text");
413 edit_args.remove("op");
414 Ok(edit_args)
415}
416
417fn validate_cross_file_options(
421 args: &Map<String, Value>,
422 file_count: usize,
423) -> Result<(), ErrorData> {
424 if file_count <= 1 {
425 return Ok(());
426 }
427 for key in ["expected_blake3", "expected_md5", "backup_path"] {
428 if args.contains_key(key) {
429 return Err(ErrorData::invalid_params(
430 format!("cross-file ctx_patch batches do not support top-level '{key}'"),
431 None,
432 ));
433 }
434 }
435 Ok(())
436}
437
438fn plan_groups(
443 args: &Map<String, Value>,
444 ctx: &ToolContext,
445) -> Result<Vec<(String, Vec<crate::tools::ctx_patch::AnchorOp>)>, ErrorData> {
446 let Some(ops_val) = args.get("ops") else {
447 let path = require_resolved_path(ctx, args, "path")?;
448 let ops = crate::tools::ctx_patch::parse_ops(args)
449 .map_err(|e| ErrorData::invalid_params(e, None))?;
450 return Ok(vec![(path, ops)]);
451 };
452
453 let arr = ops_val
454 .as_array()
455 .ok_or_else(|| ErrorData::invalid_params("ops must be an array of edit objects", None))?;
456 let grouped = group_ops_by_path(arr, get_str(args, "path").as_deref())
457 .map_err(|e| ErrorData::invalid_params(e, None))?;
458
459 let mut groups = Vec::with_capacity(grouped.len());
460 for (raw_path, op_objs) in grouped {
461 let resolved = ctx
462 .resolve_path_sync(&raw_path)
463 .map_err(|e| ErrorData::invalid_params(format!("path: {e}"), None))?;
464 ctx.ensure_writable(&resolved)
465 .map_err(|e| ErrorData::invalid_params(e, None))?;
466 let sub = Map::from_iter([("ops".to_string(), Value::Array(op_objs))]);
467 let ops = crate::tools::ctx_patch::parse_ops(&sub)
468 .map_err(|e| ErrorData::invalid_params(e, None))?;
469 groups.push((resolved, ops));
470 }
471 Ok(groups)
472}
473
474fn group_ops_by_path(
478 ops: &[Value],
479 top_path: Option<&str>,
480) -> Result<Vec<(String, Vec<Value>)>, String> {
481 if ops.is_empty() {
482 return Err("ops[] is empty — provide at least one edit".to_string());
483 }
484 let mut order: Vec<String> = Vec::new();
485 let mut by_path: std::collections::HashMap<String, Vec<Value>> =
486 std::collections::HashMap::new();
487 for (i, op) in ops.iter().enumerate() {
488 let obj = op
489 .as_object()
490 .ok_or_else(|| format!("ops[{i}] must be an object"))?;
491 let raw = obj
492 .get("path")
493 .and_then(Value::as_str)
494 .map(str::to_string)
495 .or_else(|| top_path.map(str::to_string))
496 .ok_or_else(|| {
497 format!("ops[{i}] needs its own 'path' (no top-level 'path' to fall back to)")
498 })?;
499 if !by_path.contains_key(&raw) {
500 order.push(raw.clone());
501 }
502 by_path.entry(raw).or_default().push(op.clone());
503 }
504 Ok(order
505 .into_iter()
506 .map(|p| {
507 let ops = by_path.remove(&p).unwrap_or_default();
508 (p, ops)
509 })
510 .collect())
511}
512
513fn apply_one(
518 ctx: &ToolContext,
519 params: &crate::tools::ctx_patch::PatchParams,
520) -> Result<String, ErrorData> {
521 let path = params.path.clone();
522 {
523 let cache_lock = ctx
524 .cache
525 .as_ref()
526 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
527
528 let file_lock = crate::core::path_locks::per_file_lock(&path);
533 let _file_guard = {
534 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
535 loop {
536 if let Ok(guard) = file_lock.try_lock() {
537 break guard;
538 }
539 if std::time::Instant::now() >= deadline {
540 return Err(ErrorData::internal_error(
541 format!(
542 "per-file edit lock contention for {path} — another edit to the same file is in progress, retry in a moment"
543 ),
544 None,
545 ));
546 }
547 std::thread::sleep(std::time::Duration::from_millis(20));
548 }
549 };
550
551 let last_mode = match crate::server::bounded_lock::read(cache_lock, "ctx_patch cache read")
552 {
553 Some(cache) => cache
554 .get(&path)
555 .map(|e| e.last_mode.clone())
556 .unwrap_or_default(),
557 None => String::new(),
558 };
559
560 let before = std::fs::read(&path).unwrap_or_default();
562 let (output, effect) = crate::tools::ctx_patch::run_io(params, &last_mode);
563 let written = matches!(effect, crate::tools::ctx_edit::CacheEffect::Invalidate);
564
565 if written {
566 let after = std::fs::read(&path).unwrap_or_default();
567 super::ctx_edit::observe_mcp_edit(ctx, &path, "ctx_patch", &before, &after);
568 }
569
570 crate::tools::ctx_patch::record_outcome(params, &last_mode, &output, &effect);
571
572 if !matches!(effect, crate::tools::ctx_edit::CacheEffect::None) {
573 crate::tools::ctx_read::dedup_hook::on_write(&path);
574 match crate::server::bounded_lock::write(cache_lock, "ctx_patch cache write") {
575 Some(mut cache) => {
576 crate::tools::ctx_edit::apply_cache_effect(&mut cache, &path, effect);
577 }
578 None => {
579 tracing::warn!(
580 "ctx_patch: cache write-lock timeout applying effect for {path}"
581 );
582 }
583 }
584 }
585
586 if !written {
587 return Err(tool_execution_error(output));
588 }
589
590 if let Some(session_lock) = ctx.session.as_ref() {
591 if let Some(mut session) =
592 crate::server::bounded_lock::write(session_lock, "ctx_patch session write")
593 {
594 session.mark_modified(&path);
595 }
596 }
597
598 Ok(output)
599 }
600}
601
602fn delegate_replace_symbol(
607 args: &Map<String, Value>,
608 ctx: &ToolContext,
609) -> Result<ToolOutput, ErrorData> {
610 let refactor_args = crate::tools::ctx_patch::build_refactor_args(args)
611 .map_err(|e| ErrorData::invalid_params(e, None))?;
612
613 if get_bool(args, "dry_run").unwrap_or(false) {
614 let name = get_str(args, "name").unwrap_or_default();
615 let path = get_str(args, "path").unwrap_or_default();
616 return Ok(ToolOutput::simple(format!(
617 "DRY RUN: replace_symbol would rewrite symbol {name:?} in {path}"
618 )));
619 }
620
621 let has_path = args.get("path").and_then(Value::as_str).is_some();
625 let abs_path = if has_path {
626 require_resolved_path(ctx, args, "path")?
627 } else {
628 String::new()
629 };
630
631 let args_value = Value::Object(refactor_args);
632 let result = crate::tools::ctx_refactor::handle(&args_value, &ctx.project_root, &abs_path);
633 let changed = !result.starts_with("ERROR") && !result.starts_with("CONFLICT");
634 if !changed {
635 return Err(tool_execution_error(result));
636 }
637
638 Ok(ToolOutput {
639 text: result,
640 original_tokens: 0,
641 saved_tokens: 0,
642 mode: Some("replace_symbol".to_string()),
643 path: get_str(args, "path"),
644 changed,
645 shell_outcome: None,
646 content_blocks: None,
647 })
648}
649
650fn resolve_find_replace(args: &Map<String, Value>) -> Result<(String, String), String> {
657 let find = get_str(args, "find")
658 .filter(|s| !s.is_empty())
659 .ok_or("replace_all requires non-empty 'find'")?;
660
661 for foreign in ["new_text", "new_string", "old_string"] {
662 if args.contains_key(foreign) {
663 return Err(format!(
664 "replace_all names its replacement 'replace', not '{foreign}' — rename it \
665 (an unrecognized replacement key would silently delete every match)"
666 ));
667 }
668 }
669
670 let replace = args
671 .get("replace")
672 .and_then(Value::as_str)
673 .map(String::from)
674 .ok_or(
675 "replace_all requires 'replace' (the replacement text); pass replace=\"\" \
676 explicitly to delete every match",
677 )?;
678
679 Ok((find, replace))
680}
681
682fn handle_replace_all(
684 args: &Map<String, Value>,
685 ctx: &ToolContext,
686) -> Result<ToolOutput, ErrorData> {
687 let path = require_resolved_path(ctx, args, "path")?;
688 let (find, replace) =
689 resolve_find_replace(args).map_err(|e| ErrorData::invalid_params(e, None))?;
690 let dry_run = get_bool(args, "dry_run").unwrap_or(false);
691
692 let content = std::fs::read_to_string(&path)
693 .map_err(|e| tool_execution_error(format!("cannot read {path}: {e}")))?;
694
695 let count = content.matches(find.as_str()).count();
696 if count == 0 {
697 return Ok(ToolOutput::simple(format!(
698 "No matches for {find:?} in {path}"
699 )));
700 }
701
702 if dry_run {
703 return Ok(ToolOutput::simple(format!(
704 "DRY RUN: {count} occurrence(s) of {find:?} would be replaced with {replace:?} in {path}"
705 )));
706 }
707
708 let file_lock = crate::core::path_locks::per_file_lock(&path);
709 let _guard = file_lock
710 .lock()
711 .map_err(|_| ErrorData::internal_error(format!("lock contention for {path}"), None))?;
712
713 let new_content = content.replace(find.as_str(), &replace);
714 crate::config_io::write_atomic(std::path::Path::new(&path), &new_content)
715 .map_err(|e| tool_execution_error(format!("write failed: {e}")))?;
716 super::ctx_edit::observe_mcp_edit(
717 ctx,
718 &path,
719 "ctx_patch",
720 content.as_bytes(),
721 new_content.as_bytes(),
722 );
723
724 if let Some(cache) = ctx.cache.as_ref() {
725 if let Some(mut c) =
726 crate::server::bounded_lock::write(cache, "ctx_patch replace_all cache invalidate")
727 {
728 c.invalidate(&path);
729 }
730 }
731
732 Ok(ToolOutput::simple(format!(
733 "Replaced {count} occurrence(s) of {find:?} with {replace:?} in {path}"
734 )))
735}
736
737#[cfg(test)]
738mod replace_all_tests {
739 use super::*;
740 use serde_json::json;
741
742 fn obj(v: Value) -> Map<String, Value> {
743 match v {
744 Value::Object(m) => m,
745 _ => panic!("expected object"),
746 }
747 }
748
749 #[test]
750 fn resolves_find_and_replace() {
751 let (f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": "b"}))).unwrap();
752 assert_eq!((f.as_str(), r.as_str()), ("a", "b"));
753 }
754
755 #[test]
756 fn explicit_empty_replace_is_a_deletion() {
757 let (_f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": ""}))).unwrap();
758 assert_eq!(r, "");
759 }
760
761 #[test]
762 fn missing_replace_is_rejected_not_silent_delete() {
763 let err = resolve_find_replace(&obj(json!({"find": "a"}))).unwrap_err();
764 assert!(err.contains("requires 'replace'"), "got: {err}");
765 }
766
767 #[test]
768 fn foreign_replacement_key_is_rejected() {
769 for key in ["new_string", "new_text", "old_string"] {
770 let err = resolve_find_replace(&obj(json!({"find": "a", key: "b"}))).unwrap_err();
771 assert!(
772 err.contains(key),
773 "must name the offending key {key}: {err}"
774 );
775 }
776 }
777
778 #[test]
779 fn empty_find_is_rejected() {
780 let err = resolve_find_replace(&obj(json!({"find": "", "replace": "b"}))).unwrap_err();
781 assert!(err.contains("find"), "got: {err}");
782 }
783}
784
785#[cfg(test)]
786mod batch_grouping_tests {
787 use super::*;
788 use serde_json::json;
789
790 #[test]
793 fn groups_ops_across_files_preserving_order() {
794 let ops = vec![
795 json!({"op":"insert_after","path":"a.go","line":1,"hash":"aa","new_text":"x"}),
796 json!({"op":"insert_after","path":"b.go","line":2,"hash":"bb","new_text":"y"}),
797 json!({"op":"set_line","path":"a.go","line":3,"hash":"cc","new_text":"z"}),
798 ];
799 let g = group_ops_by_path(&ops, None).unwrap();
800 assert_eq!(g.len(), 2);
801 assert_eq!(g[0].0, "a.go");
802 assert_eq!(g[0].1.len(), 2);
803 assert_eq!(g[1].0, "b.go");
804 assert_eq!(g[1].1.len(), 1);
805 }
806
807 #[test]
808 fn ops_without_path_fall_back_to_top_level() {
809 let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
810 let g = group_ops_by_path(&ops, Some("top.go")).unwrap();
811 assert_eq!(g.len(), 1);
812 assert_eq!(g[0].0, "top.go");
813 }
814
815 #[test]
816 fn op_without_path_and_no_top_level_is_rejected() {
817 let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
818 let err = group_ops_by_path(&ops, None).unwrap_err();
819 assert!(err.contains("path"), "got: {err}");
820 }
821
822 #[test]
823 fn empty_ops_rejected() {
824 let err = group_ops_by_path(&[], None).unwrap_err();
825 assert!(err.contains("empty"), "got: {err}");
826 }
827
828 #[test]
829 fn cross_file_rejects_single_value_preimage_and_backup_options() {
830 for key in ["expected_blake3", "expected_md5", "backup_path"] {
831 let args = Map::from_iter([(key.to_string(), json!("one-value"))]);
832 assert!(validate_cross_file_options(&args, 2).is_err());
833 assert!(validate_cross_file_options(&args, 1).is_ok());
834 }
835 }
836
837 #[test]
838 fn replace_unique_maps_to_a_single_safe_ctx_edit_replacement() {
839 let args = Map::from_iter([
840 ("path".into(), json!("a.rs")),
841 ("op".into(), json!("replace_unique")),
842 ("old_text".into(), json!("old")),
843 ("new_text".into(), json!("new")),
844 ]);
845 let mapped = build_unique_edit_args(&args).expect("valid mapping");
846 assert_eq!(mapped.get("old_string"), Some(&json!("old")));
847 assert_eq!(mapped.get("new_string"), Some(&json!("new")));
848 assert_eq!(mapped.get("replace_all"), Some(&json!(false)));
849 assert!(!mapped.contains_key("op"));
850 assert!(!mapped.contains_key("old_text"));
851 }
852
853 #[test]
854 fn replace_unique_requires_explicit_old_and_new_text() {
855 assert!(build_unique_edit_args(&Map::new()).is_err());
856 let only_old = Map::from_iter([("old_text".into(), json!("old"))]);
857 assert!(build_unique_edit_args(&only_old).is_err());
858 }
859
860 #[test]
861 fn dry_run_replace_unique_does_not_apply() {
862 let args = Map::from_iter([
863 ("path".into(), json!("a.rs")),
864 ("op".into(), json!("replace_unique")),
865 ("old_text".into(), json!("old")),
866 ("new_text".into(), json!("new")),
867 ("dry_run".into(), json!(true)),
868 ]);
869 let edit_args = build_unique_edit_args(&args).expect("validation passes");
870 assert!(
871 edit_args.contains_key("old_string"),
872 "args mapped correctly"
873 );
874 assert!(
875 args.get("dry_run").and_then(Value::as_bool) == Some(true),
876 "dry_run flag preserved in original args"
877 );
878 }
879
880 #[test]
881 fn text_replacement_without_op_is_inferred_as_replace_unique() {
882 let top = Map::from_iter([
883 ("path".into(), json!("a.rs")),
884 ("old_string".into(), json!("old")),
885 ("new_string".into(), json!("new")),
886 ]);
887 let inferred = infer_replace_unique(&top).expect("op inferred");
888 assert_eq!(inferred.get("op"), Some(&json!("replace_unique")));
889
890 let batch = Map::from_iter([(
891 "ops".into(),
892 json!([
893 {"path": "a.rs", "old_text": "a", "new_text": "b"},
894 {"op": "set_line", "line": 1, "hash": "aa", "new_text": "x"}
895 ]),
896 )]);
897 let inferred = infer_replace_unique(&batch).expect("op inferred in ops[]");
898 assert_eq!(inferred["ops"][0]["op"], json!("replace_unique"));
899 assert_eq!(inferred["ops"][1]["op"], json!("set_line"));
900
901 for unchanged in [
903 json!({"op": "set_line", "old_text": "a", "new_text": "b"}),
904 json!({"old_text": "", "new_text": "b"}),
905 json!({"old_text": "a"}),
906 ] {
907 assert!(infer_replace_unique(unchanged.as_object().unwrap()).is_none());
908 }
909 }
910}