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> {
662 let find = aliased(args, "find", &["old_string", "old_text"])?
663 .filter(|s| !s.is_empty())
664 .ok_or("replace_all requires non-empty 'find' (old_string also accepted)")?;
665 let replace = aliased(args, "replace", &["new_string", "new_text"])?.ok_or(
666 "replace_all requires 'replace' (the replacement text, new_string also accepted); \
667 pass replace=\"\" explicitly to delete every match",
668 )?;
669 Ok((find, replace))
670}
671
672fn aliased(
675 args: &Map<String, Value>,
676 key: &str,
677 aliases: &[&str],
678) -> Result<Option<String>, String> {
679 let mut found: Option<(&str, &str)> = None;
680 for name in std::iter::once(key).chain(aliases.iter().copied()) {
681 let Some(value) = args.get(name).and_then(Value::as_str) else {
682 continue;
683 };
684 match found {
685 Some((first, seen)) if seen != value => {
686 return Err(format!(
687 "'{first}' and '{name}' name the same field with different values — pass only one"
688 ));
689 }
690 Some(_) => {}
691 None => found = Some((name, value)),
692 }
693 }
694 Ok(found.map(|(_, value)| value.to_string()))
695}
696
697fn handle_replace_all(
699 args: &Map<String, Value>,
700 ctx: &ToolContext,
701) -> Result<ToolOutput, ErrorData> {
702 let path = require_resolved_path(ctx, args, "path")?;
703 let (find, replace) =
704 resolve_find_replace(args).map_err(|e| ErrorData::invalid_params(e, None))?;
705 let dry_run = get_bool(args, "dry_run").unwrap_or(false);
706
707 let content = std::fs::read_to_string(&path)
708 .map_err(|e| tool_execution_error(format!("cannot read {path}: {e}")))?;
709
710 let count = content.matches(find.as_str()).count();
711 if count == 0 {
712 return Ok(ToolOutput::simple(format!(
713 "No matches for {find:?} in {path}"
714 )));
715 }
716
717 if dry_run {
718 return Ok(ToolOutput::simple(format!(
719 "DRY RUN: {count} occurrence(s) of {find:?} would be replaced with {replace:?} in {path}"
720 )));
721 }
722
723 let file_lock = crate::core::path_locks::per_file_lock(&path);
724 let _guard = file_lock
725 .lock()
726 .map_err(|_| ErrorData::internal_error(format!("lock contention for {path}"), None))?;
727
728 let new_content = content.replace(find.as_str(), &replace);
729 crate::config_io::write_atomic(std::path::Path::new(&path), &new_content)
730 .map_err(|e| tool_execution_error(format!("write failed: {e}")))?;
731 super::ctx_edit::observe_mcp_edit(
732 ctx,
733 &path,
734 "ctx_patch",
735 content.as_bytes(),
736 new_content.as_bytes(),
737 );
738
739 if let Some(cache) = ctx.cache.as_ref() {
740 if let Some(mut c) =
741 crate::server::bounded_lock::write(cache, "ctx_patch replace_all cache invalidate")
742 {
743 c.invalidate(&path);
744 }
745 }
746
747 Ok(ToolOutput::simple(format!(
748 "Replaced {count} occurrence(s) of {find:?} with {replace:?} in {path}"
749 )))
750}
751
752#[cfg(test)]
753mod replace_all_tests {
754 use super::*;
755 use serde_json::json;
756
757 fn obj(v: Value) -> Map<String, Value> {
758 match v {
759 Value::Object(m) => m,
760 _ => panic!("expected object"),
761 }
762 }
763
764 #[test]
765 fn resolves_find_and_replace() {
766 let (f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": "b"}))).unwrap();
767 assert_eq!((f.as_str(), r.as_str()), ("a", "b"));
768 }
769
770 #[test]
771 fn explicit_empty_replace_is_a_deletion() {
772 let (_f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": ""}))).unwrap();
773 assert_eq!(r, "");
774 }
775
776 #[test]
777 fn missing_replace_is_rejected_not_silent_delete() {
778 let err = resolve_find_replace(&obj(json!({"find": "a"}))).unwrap_err();
779 assert!(err.contains("requires 'replace'"), "got: {err}");
780 }
781
782 #[test]
783 fn other_ops_names_are_aliases() {
784 for (old, new) in [("old_string", "new_string"), ("old_text", "new_text")] {
785 let (f, r) = resolve_find_replace(&obj(json!({old: "a", new: "b"}))).unwrap();
786 assert_eq!((f.as_str(), r.as_str()), ("a", "b"), "{old}/{new}");
787 }
788 }
789
790 #[test]
791 fn alias_never_turns_a_missing_replacement_into_a_delete() {
792 let err = resolve_find_replace(&obj(json!({"old_string": "a"}))).unwrap_err();
793 assert!(err.contains("requires 'replace'"), "got: {err}");
794 }
795
796 #[test]
797 fn conflicting_spellings_are_rejected() {
798 let err = resolve_find_replace(&obj(
799 json!({"find": "a", "old_string": "x", "replace": "b"}),
800 ))
801 .unwrap_err();
802 assert!(
803 err.contains("find") && err.contains("old_string"),
804 "got: {err}"
805 );
806 let same = resolve_find_replace(&obj(
807 json!({"find": "a", "old_string": "a", "replace": "b"}),
808 ));
809 assert!(same.is_ok(), "identical spellings agree");
810 }
811
812 #[test]
813 fn empty_find_is_rejected() {
814 let err = resolve_find_replace(&obj(json!({"find": "", "replace": "b"}))).unwrap_err();
815 assert!(err.contains("find"), "got: {err}");
816 }
817}
818
819#[cfg(test)]
820mod batch_grouping_tests {
821 use super::*;
822 use serde_json::json;
823
824 #[test]
827 fn groups_ops_across_files_preserving_order() {
828 let ops = vec![
829 json!({"op":"insert_after","path":"a.go","line":1,"hash":"aa","new_text":"x"}),
830 json!({"op":"insert_after","path":"b.go","line":2,"hash":"bb","new_text":"y"}),
831 json!({"op":"set_line","path":"a.go","line":3,"hash":"cc","new_text":"z"}),
832 ];
833 let g = group_ops_by_path(&ops, None).unwrap();
834 assert_eq!(g.len(), 2);
835 assert_eq!(g[0].0, "a.go");
836 assert_eq!(g[0].1.len(), 2);
837 assert_eq!(g[1].0, "b.go");
838 assert_eq!(g[1].1.len(), 1);
839 }
840
841 #[test]
842 fn ops_without_path_fall_back_to_top_level() {
843 let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
844 let g = group_ops_by_path(&ops, Some("top.go")).unwrap();
845 assert_eq!(g.len(), 1);
846 assert_eq!(g[0].0, "top.go");
847 }
848
849 #[test]
850 fn op_without_path_and_no_top_level_is_rejected() {
851 let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
852 let err = group_ops_by_path(&ops, None).unwrap_err();
853 assert!(err.contains("path"), "got: {err}");
854 }
855
856 #[test]
857 fn empty_ops_rejected() {
858 let err = group_ops_by_path(&[], None).unwrap_err();
859 assert!(err.contains("empty"), "got: {err}");
860 }
861
862 #[test]
863 fn cross_file_rejects_single_value_preimage_and_backup_options() {
864 for key in ["expected_blake3", "expected_md5", "backup_path"] {
865 let args = Map::from_iter([(key.to_string(), json!("one-value"))]);
866 assert!(validate_cross_file_options(&args, 2).is_err());
867 assert!(validate_cross_file_options(&args, 1).is_ok());
868 }
869 }
870
871 #[test]
872 fn replace_unique_maps_to_a_single_safe_ctx_edit_replacement() {
873 let args = Map::from_iter([
874 ("path".into(), json!("a.rs")),
875 ("op".into(), json!("replace_unique")),
876 ("old_text".into(), json!("old")),
877 ("new_text".into(), json!("new")),
878 ]);
879 let mapped = build_unique_edit_args(&args).expect("valid mapping");
880 assert_eq!(mapped.get("old_string"), Some(&json!("old")));
881 assert_eq!(mapped.get("new_string"), Some(&json!("new")));
882 assert_eq!(mapped.get("replace_all"), Some(&json!(false)));
883 assert!(!mapped.contains_key("op"));
884 assert!(!mapped.contains_key("old_text"));
885 }
886
887 #[test]
888 fn replace_unique_requires_explicit_old_and_new_text() {
889 assert!(build_unique_edit_args(&Map::new()).is_err());
890 let only_old = Map::from_iter([("old_text".into(), json!("old"))]);
891 assert!(build_unique_edit_args(&only_old).is_err());
892 }
893
894 #[test]
895 fn dry_run_replace_unique_does_not_apply() {
896 let args = Map::from_iter([
897 ("path".into(), json!("a.rs")),
898 ("op".into(), json!("replace_unique")),
899 ("old_text".into(), json!("old")),
900 ("new_text".into(), json!("new")),
901 ("dry_run".into(), json!(true)),
902 ]);
903 let edit_args = build_unique_edit_args(&args).expect("validation passes");
904 assert!(
905 edit_args.contains_key("old_string"),
906 "args mapped correctly"
907 );
908 assert!(
909 args.get("dry_run").and_then(Value::as_bool) == Some(true),
910 "dry_run flag preserved in original args"
911 );
912 }
913
914 #[test]
915 fn text_replacement_without_op_is_inferred_as_replace_unique() {
916 let top = Map::from_iter([
917 ("path".into(), json!("a.rs")),
918 ("old_string".into(), json!("old")),
919 ("new_string".into(), json!("new")),
920 ]);
921 let inferred = infer_replace_unique(&top).expect("op inferred");
922 assert_eq!(inferred.get("op"), Some(&json!("replace_unique")));
923
924 let batch = Map::from_iter([(
925 "ops".into(),
926 json!([
927 {"path": "a.rs", "old_text": "a", "new_text": "b"},
928 {"op": "set_line", "line": 1, "hash": "aa", "new_text": "x"}
929 ]),
930 )]);
931 let inferred = infer_replace_unique(&batch).expect("op inferred in ops[]");
932 assert_eq!(inferred["ops"][0]["op"], json!("replace_unique"));
933 assert_eq!(inferred["ops"][1]["op"], json!("set_line"));
934
935 for unchanged in [
937 json!({"op": "set_line", "old_text": "a", "new_text": "b"}),
938 json!({"old_text": "", "new_text": "b"}),
939 json!({"old_text": "a"}),
940 ] {
941 assert!(infer_replace_unique(unchanged.as_object().unwrap()).is_none());
942 }
943 }
944}