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 .map(|p| crate::core::workspace_authority::confine(&p, &ctx.project_root, true))
143 .transpose()
144 .map_err(|error| ErrorData::invalid_params(error, None))?;
145 let evidence = get_bool(args, "evidence").unwrap_or(true);
146 let diff_max_lines = get_int(args, "diff_max_lines")
147 .and_then(|v| usize::try_from(v.max(0)).ok())
148 .unwrap_or(200);
149 let allow_lossy_utf8 = get_bool(args, "allow_lossy_utf8").unwrap_or(false);
150 let validate_syntax = get_bool(args, "validate_syntax").unwrap_or(true);
151
152 let groups = plan_groups(args, ctx)?;
156 validate_cross_file_options(args, groups.len())?;
157 let output_path = (groups.len() == 1).then(|| groups[0].0.clone());
158
159 let mut texts = Vec::with_capacity(groups.len());
160 for (path, ops) in groups {
161 let patch_params = crate::tools::ctx_patch::PatchParams {
162 path: path.clone(),
163 ops,
164 expected_blake3: expected_blake3.clone(),
165 backup,
166 backup_path: backup_path.clone(),
167 evidence,
168 diff_max_lines,
169 allow_lossy_utf8,
170 validate_syntax,
171 };
172 let output =
173 apply_one(ctx, &patch_params).map_err(|error| with_prior_edits(error, &texts))?;
174 texts.push(format!("[{path}]\n{output}"));
175 }
176
177 Ok(ToolOutput {
178 text: texts.join("\n\n"),
179 original_tokens: 0,
180 saved_tokens: 0,
181 mode: None,
182 path: output_path,
183 changed: false,
184 shell_outcome: None,
185 content_blocks: None,
186 })
187}
188
189fn infer_replace_unique(args: &Map<String, Value>) -> Option<Map<String, Value>> {
194 fn is_text_replacement(obj: &Map<String, Value>) -> bool {
195 let text = |keys: [&str; 2]| keys.iter().find_map(|key| obj.get(*key)?.as_str());
196 !obj.contains_key("op")
197 && text(["old_text", "old_string"]).is_some_and(|old| !old.is_empty())
198 && text(["new_text", "new_string"]).is_some()
199 }
200 let mut out = args.clone();
201 let mut inferred = false;
202 if !out.contains_key("ops") && is_text_replacement(&out) {
203 out.insert("op".into(), json!("replace_unique"));
204 inferred = true;
205 }
206 if let Some(Value::Array(ops)) = out.get_mut("ops") {
207 for op in ops.iter_mut().filter_map(Value::as_object_mut) {
208 if is_text_replacement(op) {
209 op.insert("op".into(), json!("replace_unique"));
210 inferred = true;
211 }
212 }
213 }
214 inferred.then_some(out)
215}
216
217fn delegated_op_kind(v: &Value) -> Option<&str> {
220 v.get("op")
221 .and_then(Value::as_str)
222 .filter(|k| matches!(*k, "replace_unique" | "replace_symbol"))
223}
224
225fn is_unbatchable_op(v: &Value) -> Option<&str> {
233 v.get("op")
234 .and_then(Value::as_str)
235 .filter(|k| matches!(*k, "replace_all" | "create"))
236}
237
238fn handle_mixed_batch(
239 args: &Map<String, Value>,
240 arr: &[Value],
241 ctx: &ToolContext,
242) -> Result<ToolOutput, ErrorData> {
243 for (i, v) in arr.iter().enumerate() {
245 if !v.is_object() {
246 return Err(ErrorData::invalid_params(
247 format!("ops[{i}] must be an object"),
248 None,
249 ));
250 }
251 if let Some(kind) = is_unbatchable_op(v) {
252 return Err(ErrorData::invalid_params(
253 format!(
254 "ops[{i}]: {kind} cannot be batched in ops[] \
255 — send it as a separate top-level ctx_patch call"
256 ),
257 None,
258 ));
259 }
260 }
261
262 let mut texts: Vec<String> = Vec::new();
263 let mut run: Vec<Value> = Vec::new();
264 for (i, v) in arr.iter().enumerate() {
265 let obj = v.as_object().ok_or_else(|| {
266 ErrorData::invalid_params(format!("ops[{i}] must be an object"), None)
267 })?;
268 let Some(kind) = delegated_op_kind(v) else {
269 run.push(v.clone());
270 continue;
271 };
272 flush_anchored_run(args, ctx, &mut run, &mut texts)?;
273
274 let (sub_args, sub_ctx) = delegated_op_call(args, obj, ctx, i, kind)
275 .map_err(|error| with_prior_edits(error, &texts))?;
276 let out = if kind == "replace_unique" {
277 delegate_replace_unique(&sub_args, &sub_ctx)
278 } else {
279 delegate_replace_symbol(&sub_args, &sub_ctx)
280 }
281 .map_err(|mut e| {
282 e.message = format!("ops[{i}] ({kind}): {}", e.message).into();
283 with_prior_edits(e, &texts)
284 })?;
285 let label = get_str(&sub_args, "path").unwrap_or_else(|| kind.to_string());
286 texts.push(format!("[{label}]\n{}", out.text));
287 }
288 flush_anchored_run(args, ctx, &mut run, &mut texts)?;
289
290 Ok(ToolOutput::simple(texts.join("\n\n")))
291}
292
293fn flush_anchored_run(
295 args: &Map<String, Value>,
296 ctx: &ToolContext,
297 run: &mut Vec<Value>,
298 texts: &mut Vec<String>,
299) -> Result<(), ErrorData> {
300 if run.is_empty() {
301 return Ok(());
302 }
303 let mut sub = args.clone();
304 sub.insert("ops".into(), Value::Array(std::mem::take(run)));
305 texts.push(
306 handle_anchored(&sub, ctx)
307 .map_err(|error| with_prior_edits(error, texts))?
308 .text,
309 );
310 Ok(())
311}
312
313fn with_prior_edits(mut error: ErrorData, texts: &[String]) -> ErrorData {
316 if !texts.is_empty() {
317 error.code = crate::server::tool_trait::TOOL_EXECUTION_ERROR;
318 error.message = format!(
319 "{}\nEarlier ops in this batch were already applied:\n{}",
320 error.message,
321 texts.join("\n\n")
322 )
323 .into();
324 }
325 error
326}
327
328fn delegated_op_call(
333 args: &Map<String, Value>,
334 op: &Map<String, Value>,
335 ctx: &ToolContext,
336 i: usize,
337 kind: &str,
338) -> Result<(Map<String, Value>, ToolContext), ErrorData> {
339 let mut sub = op.clone();
340 for key in ["path", "dry_run"] {
341 if !sub.contains_key(key)
342 && let Some(v) = args.get(key)
343 {
344 sub.insert(key.to_string(), v.clone());
345 }
346 }
347
348 let mut sub_ctx = ctx.clone();
349 sub_ctx.resolved_paths.remove("path");
350 sub_ctx.path_errors.remove("path");
351 match get_str(&sub, "path") {
352 Some(raw) => {
353 let resolved = sub_ctx
354 .resolve_path_sync(&raw)
355 .map_err(|e| ErrorData::invalid_params(format!("ops[{i}]: path: {e}"), None))?;
356 sub_ctx
357 .ensure_writable(&resolved)
358 .map_err(|e| ErrorData::invalid_params(format!("ops[{i}]: {e}"), None))?;
359 sub_ctx.resolved_paths.insert("path".to_string(), resolved);
360 }
361 None if kind == "replace_unique" => {
364 return Err(ErrorData::invalid_params(
365 format!("ops[{i}] needs its own 'path' (no top-level 'path' to fall back to)"),
366 None,
367 ));
368 }
369 None => {}
370 }
371 Ok((sub, sub_ctx))
372}
373
374fn delegate_replace_unique(
378 args: &Map<String, Value>,
379 ctx: &ToolContext,
380) -> Result<ToolOutput, ErrorData> {
381 let edit_args =
382 build_unique_edit_args(args).map_err(|message| ErrorData::invalid_params(message, None))?;
383
384 if get_bool(args, "dry_run").unwrap_or(false) {
385 let old_text = get_str(args, "old_text")
386 .or_else(|| get_str(args, "old_string"))
387 .unwrap_or_default();
388 let new_text = get_str(args, "new_text")
389 .or_else(|| get_str(args, "new_string"))
390 .unwrap_or_default();
391 let path = get_str(args, "path").unwrap_or_default();
392 return Ok(ToolOutput::simple(format!(
393 "DRY RUN: replace_unique would replace {old_text:?} with {new_text:?} in {path}"
394 )));
395 }
396
397 crate::tools::registered::ctx_edit::CtxEditTool.handle(&edit_args, ctx)
398}
399
400fn build_unique_edit_args(args: &Map<String, Value>) -> Result<Map<String, Value>, String> {
401 let old_text = get_str(args, "old_text")
402 .or_else(|| get_str(args, "old_string"))
403 .filter(|text| !text.is_empty())
404 .ok_or_else(|| {
405 "replace_unique requires non-empty old_text (old_string also accepted)".to_string()
406 })?;
407 let new_text = get_str(args, "new_text")
408 .or_else(|| get_str(args, "new_string"))
409 .ok_or_else(|| "replace_unique requires new_text (new_string also accepted)".to_string())?;
410
411 let mut edit_args = args.clone();
412 edit_args.insert("old_string".into(), Value::String(old_text));
413 edit_args.insert("new_string".into(), Value::String(new_text));
414 edit_args.insert("replace_all".into(), Value::Bool(false));
415 edit_args.remove("old_text");
416 edit_args.remove("op");
417 Ok(edit_args)
418}
419
420fn validate_cross_file_options(
424 args: &Map<String, Value>,
425 file_count: usize,
426) -> Result<(), ErrorData> {
427 if file_count <= 1 {
428 return Ok(());
429 }
430 for key in ["expected_blake3", "expected_md5", "backup_path"] {
431 if args.contains_key(key) {
432 return Err(ErrorData::invalid_params(
433 format!("cross-file ctx_patch batches do not support top-level '{key}'"),
434 None,
435 ));
436 }
437 }
438 Ok(())
439}
440
441fn plan_groups(
446 args: &Map<String, Value>,
447 ctx: &ToolContext,
448) -> Result<Vec<(String, Vec<crate::tools::ctx_patch::AnchorOp>)>, ErrorData> {
449 let Some(ops_val) = args.get("ops") else {
450 let path = require_resolved_path(ctx, args, "path")?;
451 let ops = crate::tools::ctx_patch::parse_ops(args)
452 .map_err(|e| ErrorData::invalid_params(e, None))?;
453 return Ok(vec![(path, ops)]);
454 };
455
456 let arr = ops_val
457 .as_array()
458 .ok_or_else(|| ErrorData::invalid_params("ops must be an array of edit objects", None))?;
459 let grouped = group_ops_by_path(arr, get_str(args, "path").as_deref())
460 .map_err(|e| ErrorData::invalid_params(e, None))?;
461
462 let mut groups = Vec::with_capacity(grouped.len());
463 for (raw_path, op_objs) in grouped {
464 let resolved = ctx
465 .resolve_path_sync(&raw_path)
466 .map_err(|e| ErrorData::invalid_params(format!("path: {e}"), None))?;
467 ctx.ensure_writable(&resolved)
468 .map_err(|e| ErrorData::invalid_params(e, None))?;
469 let sub = Map::from_iter([("ops".to_string(), Value::Array(op_objs))]);
470 let ops = crate::tools::ctx_patch::parse_ops(&sub)
471 .map_err(|e| ErrorData::invalid_params(e, None))?;
472 groups.push((resolved, ops));
473 }
474 Ok(groups)
475}
476
477fn group_ops_by_path(
481 ops: &[Value],
482 top_path: Option<&str>,
483) -> Result<Vec<(String, Vec<Value>)>, String> {
484 if ops.is_empty() {
485 return Err("ops[] is empty — provide at least one edit".to_string());
486 }
487 let mut order: Vec<String> = Vec::new();
488 let mut by_path: std::collections::HashMap<String, Vec<Value>> =
489 std::collections::HashMap::new();
490 for (i, op) in ops.iter().enumerate() {
491 let obj = op
492 .as_object()
493 .ok_or_else(|| format!("ops[{i}] must be an object"))?;
494 let raw = obj
495 .get("path")
496 .and_then(Value::as_str)
497 .map(str::to_string)
498 .or_else(|| top_path.map(str::to_string))
499 .ok_or_else(|| {
500 format!("ops[{i}] needs its own 'path' (no top-level 'path' to fall back to)")
501 })?;
502 if !by_path.contains_key(&raw) {
503 order.push(raw.clone());
504 }
505 by_path.entry(raw).or_default().push(op.clone());
506 }
507 Ok(order
508 .into_iter()
509 .map(|p| {
510 let ops = by_path.remove(&p).unwrap_or_default();
511 (p, ops)
512 })
513 .collect())
514}
515
516fn apply_one(
521 ctx: &ToolContext,
522 params: &crate::tools::ctx_patch::PatchParams,
523) -> Result<String, ErrorData> {
524 let path = params.path.clone();
525 {
526 let cache_lock = ctx
527 .cache
528 .as_ref()
529 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
530
531 let file_lock = crate::core::path_locks::per_file_lock(&path);
536 let _file_guard = {
537 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
538 loop {
539 if let Ok(guard) = file_lock.try_lock() {
540 break guard;
541 }
542 if std::time::Instant::now() >= deadline {
543 return Err(ErrorData::internal_error(
544 format!(
545 "per-file edit lock contention for {path} — another edit to the same file is in progress, retry in a moment"
546 ),
547 None,
548 ));
549 }
550 std::thread::sleep(std::time::Duration::from_millis(20));
551 }
552 };
553
554 let last_mode = match crate::server::bounded_lock::read(cache_lock, "ctx_patch cache read")
555 {
556 Some(cache) => cache
557 .get(&path)
558 .map(|e| e.last_mode.clone())
559 .unwrap_or_default(),
560 None => String::new(),
561 };
562
563 let before = std::fs::read(&path).unwrap_or_default();
565 let (output, effect) = crate::tools::ctx_patch::run_io(params, &last_mode);
566 let written = matches!(effect, crate::tools::ctx_edit::CacheEffect::Invalidate);
567
568 if written {
569 let after = std::fs::read(&path).unwrap_or_default();
570 super::ctx_edit::observe_mcp_edit(ctx, &path, "ctx_patch", &before, &after);
571 }
572
573 crate::tools::ctx_patch::record_outcome(params, &last_mode, &output, &effect);
574
575 if !matches!(effect, crate::tools::ctx_edit::CacheEffect::None) {
576 crate::tools::ctx_read::dedup_hook::on_write(&path);
577 match crate::server::bounded_lock::write(cache_lock, "ctx_patch cache write") {
578 Some(mut cache) => {
579 crate::tools::ctx_edit::apply_cache_effect(&mut cache, &path, effect);
580 }
581 None => {
582 tracing::warn!(
583 "ctx_patch: cache write-lock timeout applying effect for {path}"
584 );
585 }
586 }
587 }
588
589 if !written {
590 return Err(tool_execution_error(output));
591 }
592
593 if let Some(session_lock) = ctx.session.as_ref() {
594 if let Some(mut session) =
595 crate::server::bounded_lock::write(session_lock, "ctx_patch session write")
596 {
597 session.mark_modified(&path);
598 }
599 }
600
601 Ok(output)
602 }
603}
604
605fn delegate_replace_symbol(
610 args: &Map<String, Value>,
611 ctx: &ToolContext,
612) -> Result<ToolOutput, ErrorData> {
613 let refactor_args = crate::tools::ctx_patch::build_refactor_args(args)
614 .map_err(|e| ErrorData::invalid_params(e, None))?;
615
616 if get_bool(args, "dry_run").unwrap_or(false) {
617 let name = get_str(args, "name").unwrap_or_default();
618 let path = get_str(args, "path").unwrap_or_default();
619 return Ok(ToolOutput::simple(format!(
620 "DRY RUN: replace_symbol would rewrite symbol {name:?} in {path}"
621 )));
622 }
623
624 let has_path = args.get("path").and_then(Value::as_str).is_some();
628 let abs_path = if has_path {
629 require_resolved_path(ctx, args, "path")?
630 } else {
631 String::new()
632 };
633
634 let args_value = Value::Object(refactor_args);
635 let result = crate::tools::ctx_refactor::handle(&args_value, &ctx.project_root, &abs_path);
636 let changed = !result.starts_with("ERROR") && !result.starts_with("CONFLICT");
637 if !changed {
638 return Err(tool_execution_error(result));
639 }
640
641 Ok(ToolOutput {
642 text: result,
643 original_tokens: 0,
644 saved_tokens: 0,
645 mode: Some("replace_symbol".to_string()),
646 path: get_str(args, "path"),
647 changed,
648 shell_outcome: None,
649 content_blocks: None,
650 })
651}
652
653fn resolve_find_replace(args: &Map<String, Value>) -> Result<(String, String), String> {
665 let find = aliased(args, "find", &["old_string", "old_text"])?
666 .filter(|s| !s.is_empty())
667 .ok_or("replace_all requires non-empty 'find' (old_string also accepted)")?;
668 let replace = aliased(args, "replace", &["new_string", "new_text"])?.ok_or(
669 "replace_all requires 'replace' (the replacement text, new_string also accepted); \
670 pass replace=\"\" explicitly to delete every match",
671 )?;
672 Ok((find, replace))
673}
674
675fn aliased(
678 args: &Map<String, Value>,
679 key: &str,
680 aliases: &[&str],
681) -> Result<Option<String>, String> {
682 let mut found: Option<(&str, &str)> = None;
683 for name in std::iter::once(key).chain(aliases.iter().copied()) {
684 let Some(value) = args.get(name).and_then(Value::as_str) else {
685 continue;
686 };
687 match found {
688 Some((first, seen)) if seen != value => {
689 return Err(format!(
690 "'{first}' and '{name}' name the same field with different values — pass only one"
691 ));
692 }
693 Some(_) => {}
694 None => found = Some((name, value)),
695 }
696 }
697 Ok(found.map(|(_, value)| value.to_string()))
698}
699
700fn replace_all_plan(path: &str, root: &str, find: &str) -> Result<(String, usize), String> {
713 use crate::tools::admitted_sources::SourceRead;
714 let mut remaining = crate::core::limits::max_read_bytes();
715 let admitted =
716 match crate::tools::admitted_sources::read(path, root, "ctx_patch", &mut remaining) {
717 SourceRead::Admitted(read) => read.content,
718 SourceRead::Withheld(reason) | SourceRead::Unavailable(reason) => {
719 return Err(format!("cannot read {path}: {reason}"));
720 }
721 };
722 let original = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
723 let count = admitted.matches(find).count();
724 if count != original.matches(find).count() {
725 return Err(format!(
726 "replace_all refused for {path}: the pattern overlaps content the context gateway \
727 masks; nothing was changed"
728 ));
729 }
730 Ok((original, count))
731}
732
733fn handle_replace_all(
735 args: &Map<String, Value>,
736 ctx: &ToolContext,
737) -> Result<ToolOutput, ErrorData> {
738 let path = require_resolved_path(ctx, args, "path")?;
739 let (find, replace) =
740 resolve_find_replace(args).map_err(|e| ErrorData::invalid_params(e, None))?;
741 let dry_run = get_bool(args, "dry_run").unwrap_or(false);
742
743 let root = crate::tools::admitted_sources::root_in_context(&path, ctx);
744 let (content, count) = replace_all_plan(&path, &root, &find).map_err(tool_execution_error)?;
745 if count == 0 {
746 return Ok(ToolOutput::simple(format!(
747 "No matches for {find:?} in {path}"
748 )));
749 }
750
751 if dry_run {
752 return Ok(ToolOutput::simple(format!(
753 "DRY RUN: {count} occurrence(s) of {find:?} would be replaced with {replace:?} in {path}"
754 )));
755 }
756
757 let file_lock = crate::core::path_locks::per_file_lock(&path);
758 let _guard = file_lock
759 .lock()
760 .map_err(|_| ErrorData::internal_error(format!("lock contention for {path}"), None))?;
761
762 let new_content = content.replace(find.as_str(), &replace);
763 crate::core::pathjail::enforce_writable(std::path::Path::new(&path))
764 .map_err(|e| ErrorData::invalid_params(e, None))?;
765 crate::config_io::write_atomic(std::path::Path::new(&path), &new_content)
766 .map_err(|e| tool_execution_error(format!("write failed: {e}")))?;
767 super::ctx_edit::observe_mcp_edit(
768 ctx,
769 &path,
770 "ctx_patch",
771 content.as_bytes(),
772 new_content.as_bytes(),
773 );
774
775 if let Some(cache) = ctx.cache.as_ref() {
776 if let Some(mut c) =
777 crate::server::bounded_lock::write(cache, "ctx_patch replace_all cache invalidate")
778 {
779 c.invalidate(&path);
780 }
781 }
782
783 Ok(ToolOutput::simple(format!(
784 "Replaced {count} occurrence(s) of {find:?} with {replace:?} in {path}"
785 )))
786}
787
788#[cfg(test)]
789mod replace_all_tests {
790 use super::*;
791 use serde_json::json;
792
793 fn obj(v: Value) -> Map<String, Value> {
794 match v {
795 Value::Object(m) => m,
796 _ => panic!("expected object"),
797 }
798 }
799
800 #[test]
801 fn resolves_find_and_replace() {
802 let (f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": "b"}))).unwrap();
803 assert_eq!((f.as_str(), r.as_str()), ("a", "b"));
804 }
805
806 #[test]
807 fn explicit_empty_replace_is_a_deletion() {
808 let (_f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": ""}))).unwrap();
809 assert_eq!(r, "");
810 }
811
812 #[test]
813 fn missing_replace_is_rejected_not_silent_delete() {
814 let err = resolve_find_replace(&obj(json!({"find": "a"}))).unwrap_err();
815 assert!(err.contains("requires 'replace'"), "got: {err}");
816 }
817
818 #[test]
819 fn other_ops_names_are_aliases() {
820 for (old, new) in [("old_string", "new_string"), ("old_text", "new_text")] {
821 let (f, r) = resolve_find_replace(&obj(json!({old: "a", new: "b"}))).unwrap();
822 assert_eq!((f.as_str(), r.as_str()), ("a", "b"), "{old}/{new}");
823 }
824 }
825
826 #[test]
827 fn alias_never_turns_a_missing_replacement_into_a_delete() {
828 let err = resolve_find_replace(&obj(json!({"old_string": "a"}))).unwrap_err();
829 assert!(err.contains("requires 'replace'"), "got: {err}");
830 }
831
832 #[test]
833 fn conflicting_spellings_are_rejected() {
834 let err = resolve_find_replace(&obj(
835 json!({"find": "a", "old_string": "x", "replace": "b"}),
836 ))
837 .unwrap_err();
838 assert!(
839 err.contains("find") && err.contains("old_string"),
840 "got: {err}"
841 );
842 let same = resolve_find_replace(&obj(
843 json!({"find": "a", "old_string": "a", "replace": "b"}),
844 ));
845 assert!(same.is_ok(), "identical spellings agree");
846 }
847
848 #[test]
849 fn empty_find_is_rejected() {
850 let err = resolve_find_replace(&obj(json!({"find": "", "replace": "b"}))).unwrap_err();
851 assert!(err.contains("find"), "got: {err}");
852 }
853
854 #[test]
860 fn the_reported_count_comes_from_the_admitted_text_and_the_original_is_what_is_written() {
861 use crate::core::policy::runtime::TestPolicyOverride;
862 let _data = crate::core::data_dir::isolated_data_dir();
863 let policy = crate::core::policy::load(
864 "name = \"ctx-patch-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
865 [redaction]\ncustomer = \"CUS-[0-9]{4}\"\n\
866 [filters]\nclassification = \"block\"\nblocked_labels = [\"CONFIDENTIAL\"]\n",
867 )
868 .unwrap();
869 let project = tempfile::tempdir().unwrap();
870 let root = project.path().to_string_lossy().into_owned();
871 let file = |name: &str, content: &str| {
872 let path = project.path().join(name);
873 std::fs::write(&path, content).unwrap();
874 path.to_string_lossy().into_owned()
875 };
876 let original = "let owner = \"CUS-1234\";\nlet mode = old_mode();\nold_mode();\n";
877 let orders = file("orders.rs", original);
878 let plan = file("plan.rs", "CONFIDENTIAL\nold_mode();\n");
879 {
880 let _community = TestPolicyOverride::set(None);
882 assert_eq!(
883 replace_all_plan(&orders, &root, "old_mode"),
884 Ok((original.to_string(), 2))
885 );
886 }
887 let _policy = TestPolicyOverride::set(Some(policy));
888 assert_eq!(
890 replace_all_plan(&orders, &root, "old_mode"),
891 Ok((original.to_string(), 2))
892 );
893 let refused = replace_all_plan(&orders, &root, "CUS-1234").unwrap_err();
895 assert!(refused.contains("refused"), "{refused}");
896 assert!(!refused.contains("1 occurrence"), "{refused}");
897 let withheld = replace_all_plan(&plan, &root, "old_mode").unwrap_err();
899 assert!(withheld.contains("withheld"), "{withheld}");
900 assert!(replace_all_plan(&orders, "", "old_mode").is_err());
902 }
903}
904
905#[cfg(test)]
906mod batch_grouping_tests {
907 use super::*;
908 use serde_json::json;
909
910 #[test]
913 fn groups_ops_across_files_preserving_order() {
914 let ops = vec![
915 json!({"op":"insert_after","path":"a.go","line":1,"hash":"aa","new_text":"x"}),
916 json!({"op":"insert_after","path":"b.go","line":2,"hash":"bb","new_text":"y"}),
917 json!({"op":"set_line","path":"a.go","line":3,"hash":"cc","new_text":"z"}),
918 ];
919 let g = group_ops_by_path(&ops, None).unwrap();
920 assert_eq!(g.len(), 2);
921 assert_eq!(g[0].0, "a.go");
922 assert_eq!(g[0].1.len(), 2);
923 assert_eq!(g[1].0, "b.go");
924 assert_eq!(g[1].1.len(), 1);
925 }
926
927 #[test]
928 fn ops_without_path_fall_back_to_top_level() {
929 let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
930 let g = group_ops_by_path(&ops, Some("top.go")).unwrap();
931 assert_eq!(g.len(), 1);
932 assert_eq!(g[0].0, "top.go");
933 }
934
935 #[test]
936 fn op_without_path_and_no_top_level_is_rejected() {
937 let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
938 let err = group_ops_by_path(&ops, None).unwrap_err();
939 assert!(err.contains("path"), "got: {err}");
940 }
941
942 #[test]
943 fn empty_ops_rejected() {
944 let err = group_ops_by_path(&[], None).unwrap_err();
945 assert!(err.contains("empty"), "got: {err}");
946 }
947
948 #[test]
949 fn cross_file_rejects_single_value_preimage_and_backup_options() {
950 for key in ["expected_blake3", "expected_md5", "backup_path"] {
951 let args = Map::from_iter([(key.to_string(), json!("one-value"))]);
952 assert!(validate_cross_file_options(&args, 2).is_err());
953 assert!(validate_cross_file_options(&args, 1).is_ok());
954 }
955 }
956
957 #[test]
958 fn replace_unique_maps_to_a_single_safe_ctx_edit_replacement() {
959 let args = Map::from_iter([
960 ("path".into(), json!("a.rs")),
961 ("op".into(), json!("replace_unique")),
962 ("old_text".into(), json!("old")),
963 ("new_text".into(), json!("new")),
964 ]);
965 let mapped = build_unique_edit_args(&args).expect("valid mapping");
966 assert_eq!(mapped.get("old_string"), Some(&json!("old")));
967 assert_eq!(mapped.get("new_string"), Some(&json!("new")));
968 assert_eq!(mapped.get("replace_all"), Some(&json!(false)));
969 assert!(!mapped.contains_key("op"));
970 assert!(!mapped.contains_key("old_text"));
971 }
972
973 #[test]
974 fn replace_unique_requires_explicit_old_and_new_text() {
975 assert!(build_unique_edit_args(&Map::new()).is_err());
976 let only_old = Map::from_iter([("old_text".into(), json!("old"))]);
977 assert!(build_unique_edit_args(&only_old).is_err());
978 }
979
980 #[test]
981 fn dry_run_replace_unique_does_not_apply() {
982 let args = Map::from_iter([
983 ("path".into(), json!("a.rs")),
984 ("op".into(), json!("replace_unique")),
985 ("old_text".into(), json!("old")),
986 ("new_text".into(), json!("new")),
987 ("dry_run".into(), json!(true)),
988 ]);
989 let edit_args = build_unique_edit_args(&args).expect("validation passes");
990 assert!(
991 edit_args.contains_key("old_string"),
992 "args mapped correctly"
993 );
994 assert!(
995 args.get("dry_run").and_then(Value::as_bool) == Some(true),
996 "dry_run flag preserved in original args"
997 );
998 }
999
1000 #[test]
1001 fn text_replacement_without_op_is_inferred_as_replace_unique() {
1002 let top = Map::from_iter([
1003 ("path".into(), json!("a.rs")),
1004 ("old_string".into(), json!("old")),
1005 ("new_string".into(), json!("new")),
1006 ]);
1007 let inferred = infer_replace_unique(&top).expect("op inferred");
1008 assert_eq!(inferred.get("op"), Some(&json!("replace_unique")));
1009
1010 let batch = Map::from_iter([(
1011 "ops".into(),
1012 json!([
1013 {"path": "a.rs", "old_text": "a", "new_text": "b"},
1014 {"op": "set_line", "line": 1, "hash": "aa", "new_text": "x"}
1015 ]),
1016 )]);
1017 let inferred = infer_replace_unique(&batch).expect("op inferred in ops[]");
1018 assert_eq!(inferred["ops"][0]["op"], json!("replace_unique"));
1019 assert_eq!(inferred["ops"][1]["op"], json!("set_line"));
1020
1021 for unchanged in [
1023 json!({"op": "set_line", "old_text": "a", "new_text": "b"}),
1024 json!({"old_text": "", "new_text": "b"}),
1025 json!({"old_text": "a"}),
1026 ] {
1027 assert!(infer_replace_unique(unchanged.as_object().unwrap()).is_none());
1028 }
1029 }
1030}