Skip to main content

lean_ctx/tools/registered/
ctx_patch.rs

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};
8use crate::tool_defs::tool_def;
9
10pub struct CtxPatchTool;
11
12impl McpTool for CtxPatchTool {
13    fn name(&self) -> &'static str {
14        "ctx_patch"
15    }
16
17    // Schema diet (#576 pattern): the advertised surface carries only the
18    // functional teaching (anchor source, op routing, batch atomicity).
19    // Handler-only params stay supported but unadvertised: expected_md5,
20    // backup, backup_path, validate_syntax, evidence, diff_max_lines,
21    // allow_lossy_utf8 — same hidden-params contract as ctx_edit.
22    fn tool_def(&self) -> Tool {
23        tool_def(
24            "ctx_patch",
25            "Safe file edit. Anchored ops use line+hash from ctx_read(mode=\"anchored\"); \
26             CONFLICT means re-read. replace_unique(path,old_text,new_text) is a no-read, \
27             exact unique replacement. replace_symbol/create/replace_all supported as \
28             top-level ops. Cross-file ops[] batch (incl. replace_unique) supported; \
29             replace_all and create must be sent as separate top-level calls, not inside ops[].",
30            json!({
31                "type": "object",
32                "properties": {
33                    "path": { "type": "string" },
34                    "op": { "type": "string", "enum": ["set_line", "replace_lines", "insert_after", "delete", "replace_unique", "replace_symbol", "create", "replace_all"] },
35                    "line": { "type": "integer" },
36                    "hash": { "type": "string" },
37                    "start_line": { "type": "integer" },
38                    "start_hash": { "type": "string" },
39                    "end_line": { "type": "integer" },
40                    "end_hash": { "type": "string" },
41                    "new_text": { "type": "string" },
42                    "old_text": { "type": "string" },
43                    "name": { "type": "string" },
44                    "find": { "type": "string" },
45                    "replace": { "type": "string" },
46                    "dry_run": { "type": "boolean" },
47                    "ops": { "type": "array", "items": { "type": "object" } }
48                },
49                // Per-op required params encoded as the source of truth (#1020):
50                // a client reading the schema knows which fields an op needs
51                // BEFORE calling. Each `if` requires `op` so it stays dormant for
52                // batch calls (which carry `op` inside ops[], not at top level).
53                // Only ops with UNCONDITIONAL requirements are listed — insert_after
54                // (hash optional when line=0) and delete (single vs range) keep their
55                // requirements in the parser to avoid rejecting valid calls.
56                "allOf": [
57                    { "if": { "properties": { "op": { "const": "set_line" } }, "required": ["op"] },
58                      "then": { "required": ["op", "line", "hash", "new_text"] } },
59                    { "if": { "properties": { "op": { "const": "replace_lines" } }, "required": ["op"] },
60                      "then": { "required": ["op", "start_line", "start_hash", "end_line", "end_hash", "new_text"] } },
61                    { "if": { "properties": { "op": { "const": "replace_unique" } }, "required": ["op"] },
62                      "then": { "required": ["op", "old_text", "new_text"] } },
63                    { "if": { "properties": { "op": { "const": "replace_symbol" } }, "required": ["op"] },
64                      "then": { "required": ["op", "new_text"] } },
65                    { "if": { "properties": { "op": { "const": "create" } }, "required": ["op"] },
66                      "then": { "required": ["op", "new_text"] } },
67                    { "if": { "properties": { "op": { "const": "replace_all" } }, "required": ["op"] },
68                      "then": { "required": ["op", "find", "replace"] } }
69                ]
70            }),
71        )
72    }
73
74    fn handle(
75        &self,
76        args: &Map<String, Value>,
77        ctx: &ToolContext,
78    ) -> Result<ToolOutput, ErrorData> {
79        // replace_symbol is a whole-symbol rewrite — delegate to the LSP/IDE-aware
80        // ctx_refactor so there is one symbol-edit implementation (epic #1008).
81        if crate::tools::ctx_patch::is_replace_symbol(args) {
82            return delegate_replace_symbol(args, ctx);
83        }
84
85        if get_str(args, "op").as_deref() == Some("replace_unique") {
86            return delegate_replace_unique(args, ctx);
87        }
88
89        // #825: replace_all short-circuits before anchor parsing.
90        if get_str(args, "op").as_deref() == Some("replace_all") {
91            return handle_replace_all(args, ctx);
92        }
93
94        // #1088: replace_unique/replace_symbol are allowed inside ops[]. Split
95        // the batch into runs: each delegated op reuses its single-op write
96        // path; consecutive anchored ops keep shared-preimage batch semantics.
97        if let Some(arr) = args.get("ops").and_then(Value::as_array) {
98            // GH #1433: pre-validate before any ops are applied.
99            for (i, v) in arr.iter().enumerate() {
100                if let Some(kind) = is_unbatchable_op(v) {
101                    return Err(ErrorData::invalid_params(
102                        format!(
103                            "ops[{i}]: {kind} cannot be batched in ops[] \
104                             — send it as a separate top-level ctx_patch call"
105                        ),
106                        None,
107                    ));
108                }
109            }
110            if arr.iter().any(|v| delegated_op_kind(v).is_some()) {
111                return handle_mixed_batch(args, arr, ctx);
112            }
113        }
114
115        handle_anchored(args, ctx)
116    }
117}
118
119/// Anchored pipeline: a single anchored op or an ops[] batch of anchored edits
120/// (grouped per file, batch-atomic per file). Split out of `handle` so the
121/// mixed-batch path (#1088) can reuse it per anchored run.
122fn handle_anchored(args: &Map<String, Value>, ctx: &ToolContext) -> Result<ToolOutput, ErrorData> {
123    if get_bool(args, "dry_run").unwrap_or(false) {
124        let path = get_str(args, "path").unwrap_or_default();
125        return Ok(ToolOutput::simple(format!(
126            "DRY RUN: ctx_patch would apply anchor-based ops to {path}"
127        )));
128    }
129
130    let expected_md5 = get_str(args, "expected_md5");
131    let backup = get_bool(args, "backup").unwrap_or(false);
132    let backup_path = get_str(args, "backup_path")
133        .map(|p| ctx.resolved_paths.get("backup_path").cloned().unwrap_or(p));
134    let evidence = get_bool(args, "evidence").unwrap_or(true);
135    let diff_max_lines = get_int(args, "diff_max_lines")
136        .and_then(|v| usize::try_from(v.max(0)).ok())
137        .unwrap_or(200);
138    let allow_lossy_utf8 = get_bool(args, "allow_lossy_utf8").unwrap_or(false);
139    let validate_syntax = get_bool(args, "validate_syntax").unwrap_or(true);
140
141    // #1005: a batch (`ops[]`) groups its ops by each op's own `path`, so a
142    // batch may span files and needs no top-level `path`. A single op still
143    // requires the top-level `path`.
144    let groups = plan_groups(args, ctx)?;
145    validate_cross_file_options(args, groups.len())?;
146    let output_path = (groups.len() == 1).then(|| groups[0].0.clone());
147
148    let mut texts = Vec::with_capacity(groups.len());
149    for (path, ops) in groups {
150        let patch_params = crate::tools::ctx_patch::PatchParams {
151            path: path.clone(),
152            ops,
153            expected_md5: expected_md5.clone(),
154            backup,
155            backup_path: backup_path.clone(),
156            evidence,
157            diff_max_lines,
158            allow_lossy_utf8,
159            validate_syntax,
160        };
161        let output = apply_one(ctx, &patch_params)?;
162        texts.push(format!("[{path}]\n{output}"));
163    }
164
165    Ok(ToolOutput {
166        text: texts.join("\n\n"),
167        original_tokens: 0,
168        saved_tokens: 0,
169        mode: None,
170        path: output_path,
171        changed: false,
172        shell_outcome: None,
173        content_blocks: None,
174    })
175}
176
177/// `Some(op)` when a batch op must be dispatched through its own single-op
178/// write path rather than the anchored pipeline (#1088).
179fn delegated_op_kind(v: &Value) -> Option<&str> {
180    v.get("op")
181        .and_then(Value::as_str)
182        .filter(|k| matches!(*k, "replace_unique" | "replace_symbol"))
183}
184
185/// #1088: an ops[] batch containing replace_unique/replace_symbol. Ops apply
186/// strictly in the order given, as if issued as separate calls: consecutive
187/// anchored ops flush as one shared-preimage batch; each delegated op is
188/// dispatched through the same delegate as its top-level form, evaluated
189/// against the file state left by the preceding ops.
190/// Ops that require their own top-level ctx_patch call and cannot be
191/// batched inside ops[].
192fn is_unbatchable_op(v: &Value) -> Option<&str> {
193    v.get("op")
194        .and_then(Value::as_str)
195        .filter(|k| matches!(*k, "replace_all" | "create"))
196}
197
198fn handle_mixed_batch(
199    args: &Map<String, Value>,
200    arr: &[Value],
201    ctx: &ToolContext,
202) -> Result<ToolOutput, ErrorData> {
203    // GH #1433: pre-validate the entire batch before applying any op.
204    for (i, v) in arr.iter().enumerate() {
205        if !v.is_object() {
206            return Err(ErrorData::invalid_params(
207                format!("ops[{i}] must be an object"),
208                None,
209            ));
210        }
211        if let Some(kind) = is_unbatchable_op(v) {
212            return Err(ErrorData::invalid_params(
213                format!(
214                    "ops[{i}]: {kind} cannot be batched in ops[] \
215                     — send it as a separate top-level ctx_patch call"
216                ),
217                None,
218            ));
219        }
220    }
221
222    let mut texts: Vec<String> = Vec::new();
223    let mut run: Vec<Value> = Vec::new();
224    for (i, v) in arr.iter().enumerate() {
225        let obj = v.as_object().ok_or_else(|| {
226            ErrorData::invalid_params(format!("ops[{i}] must be an object"), None)
227        })?;
228        let Some(kind) = delegated_op_kind(v) else {
229            run.push(v.clone());
230            continue;
231        };
232        flush_anchored_run(args, ctx, &mut run, &mut texts)?;
233
234        let (sub_args, sub_ctx) = delegated_op_call(args, obj, ctx, i, kind)?;
235        let out = if kind == "replace_unique" {
236            delegate_replace_unique(&sub_args, &sub_ctx)
237        } else {
238            delegate_replace_symbol(&sub_args, &sub_ctx)
239        }
240        .map_err(|e| {
241            let applied = if texts.is_empty() {
242                ""
243            } else {
244                " (earlier ops in this batch were already applied)"
245            };
246            ErrorData::invalid_params(format!("ops[{i}] ({kind}): {}{applied}", e.message), None)
247        })?;
248        let label = get_str(&sub_args, "path").unwrap_or_else(|| kind.to_string());
249        texts.push(format!("[{label}]\n{}", out.text));
250    }
251    flush_anchored_run(args, ctx, &mut run, &mut texts)?;
252
253    Ok(ToolOutput::simple(texts.join("\n\n")))
254}
255
256/// Flush buffered anchored ops through the anchored pipeline as one batch.
257fn flush_anchored_run(
258    args: &Map<String, Value>,
259    ctx: &ToolContext,
260    run: &mut Vec<Value>,
261    texts: &mut Vec<String>,
262) -> Result<(), ErrorData> {
263    if run.is_empty() {
264        return Ok(());
265    }
266    let mut sub = args.clone();
267    sub.insert("ops".into(), Value::Array(std::mem::take(run)));
268    texts.push(handle_anchored(&sub, ctx)?.text);
269    Ok(())
270}
271
272/// Build the (args, ctx) for one delegated batch op: the op object inherits the
273/// batch's top-level `path`/`dry_run` when it doesn't set its own, and the op's
274/// path is resolved into a per-op ctx — the dispatch layer only pre-resolves
275/// the top-level `path`, which may differ or be absent (#1088).
276fn delegated_op_call(
277    args: &Map<String, Value>,
278    op: &Map<String, Value>,
279    ctx: &ToolContext,
280    i: usize,
281    kind: &str,
282) -> Result<(Map<String, Value>, ToolContext), ErrorData> {
283    let mut sub = op.clone();
284    for key in ["path", "dry_run"] {
285        if !sub.contains_key(key)
286            && let Some(v) = args.get(key)
287        {
288            sub.insert(key.to_string(), v.clone());
289        }
290    }
291
292    let mut sub_ctx = ctx.clone();
293    sub_ctx.resolved_paths.remove("path");
294    sub_ctx.path_errors.remove("path");
295    match get_str(&sub, "path") {
296        Some(raw) => {
297            let resolved = sub_ctx
298                .resolve_path_sync(&raw)
299                .map_err(|e| ErrorData::invalid_params(format!("ops[{i}]: path: {e}"), None))?;
300            sub_ctx
301                .ensure_writable(&resolved)
302                .map_err(|e| ErrorData::invalid_params(format!("ops[{i}]: {e}"), None))?;
303            sub_ctx.resolved_paths.insert("path".to_string(), resolved);
304        }
305        // replace_symbol's `name` route resolves its own path inside
306        // ctx_refactor; replace_unique always needs one.
307        None if kind == "replace_unique" => {
308            return Err(ErrorData::invalid_params(
309                format!("ops[{i}] needs its own 'path' (no top-level 'path' to fall back to)"),
310                None,
311            ));
312        }
313        None => {}
314    }
315    Ok((sub, sub_ctx))
316}
317
318/// One-shot content-anchored edit (#1010). Delegate to ctx_edit's audited
319/// unique-replacement path so ambiguity checks, TOCTOU guards, atomic writes,
320/// cache invalidation, evidence and session tracking remain single-sourced.
321fn delegate_replace_unique(
322    args: &Map<String, Value>,
323    ctx: &ToolContext,
324) -> Result<ToolOutput, ErrorData> {
325    let edit_args =
326        build_unique_edit_args(args).map_err(|message| ErrorData::invalid_params(message, None))?;
327
328    if get_bool(args, "dry_run").unwrap_or(false) {
329        let old_text = get_str(args, "old_text")
330            .or_else(|| get_str(args, "old_string"))
331            .unwrap_or_default();
332        let new_text = get_str(args, "new_text")
333            .or_else(|| get_str(args, "new_string"))
334            .unwrap_or_default();
335        let path = get_str(args, "path").unwrap_or_default();
336        return Ok(ToolOutput::simple(format!(
337            "DRY RUN: replace_unique would replace {old_text:?} with {new_text:?} in {path}"
338        )));
339    }
340
341    crate::tools::registered::ctx_edit::CtxEditTool.handle(&edit_args, ctx)
342}
343
344fn build_unique_edit_args(args: &Map<String, Value>) -> Result<Map<String, Value>, String> {
345    let old_text = get_str(args, "old_text")
346        .or_else(|| get_str(args, "old_string"))
347        .filter(|text| !text.is_empty())
348        .ok_or_else(|| {
349            "replace_unique requires non-empty old_text (old_string also accepted)".to_string()
350        })?;
351    let new_text = get_str(args, "new_text")
352        .or_else(|| get_str(args, "new_string"))
353        .ok_or_else(|| "replace_unique requires new_text (new_string also accepted)".to_string())?;
354
355    let mut edit_args = args.clone();
356    edit_args.insert("old_string".into(), Value::String(old_text));
357    edit_args.insert("new_string".into(), Value::String(new_text));
358    edit_args.insert("replace_all".into(), Value::Bool(false));
359    edit_args.remove("old_text");
360    edit_args.remove("op");
361    Ok(edit_args)
362}
363
364/// Options with one top-level value cannot be applied safely to multiple files:
365/// one digest cannot describe several preimages, and one explicit backup path
366/// would be overwritten by the second file. Reject before any write occurs.
367fn validate_cross_file_options(
368    args: &Map<String, Value>,
369    file_count: usize,
370) -> Result<(), ErrorData> {
371    if file_count <= 1 {
372        return Ok(());
373    }
374    for key in ["expected_md5", "backup_path"] {
375        if args.contains_key(key) {
376            return Err(ErrorData::invalid_params(
377                format!("cross-file ctx_patch batches do not support top-level '{key}'"),
378                None,
379            ));
380        }
381    }
382    Ok(())
383}
384
385/// Build the per-file work list. A single op targets the top-level `path`
386/// (still required). A batch (`ops[]`) groups its ops by each op's own `path`,
387/// falling back to the top-level `path`, so a batch may span files without a
388/// top-level `path` (#1005).
389fn plan_groups(
390    args: &Map<String, Value>,
391    ctx: &ToolContext,
392) -> Result<Vec<(String, Vec<crate::tools::ctx_patch::AnchorOp>)>, ErrorData> {
393    let Some(ops_val) = args.get("ops") else {
394        let path = require_resolved_path(ctx, args, "path")?;
395        let ops = crate::tools::ctx_patch::parse_ops(args)
396            .map_err(|e| ErrorData::invalid_params(e, None))?;
397        return Ok(vec![(path, ops)]);
398    };
399
400    let arr = ops_val
401        .as_array()
402        .ok_or_else(|| ErrorData::invalid_params("ops must be an array of edit objects", None))?;
403    let grouped = group_ops_by_path(arr, get_str(args, "path").as_deref())
404        .map_err(|e| ErrorData::invalid_params(e, None))?;
405
406    let mut groups = Vec::with_capacity(grouped.len());
407    for (raw_path, op_objs) in grouped {
408        let resolved = ctx
409            .resolve_path_sync(&raw_path)
410            .map_err(|e| ErrorData::invalid_params(format!("path: {e}"), None))?;
411        ctx.ensure_writable(&resolved)
412            .map_err(|e| ErrorData::invalid_params(e, None))?;
413        let sub = Map::from_iter([("ops".to_string(), Value::Array(op_objs))]);
414        let ops = crate::tools::ctx_patch::parse_ops(&sub)
415            .map_err(|e| ErrorData::invalid_params(e, None))?;
416        groups.push((resolved, ops));
417    }
418    Ok(groups)
419}
420
421/// Pure grouping: bucket batch op objects by their own `path` (or the batch's
422/// top-level `path` fallback), preserving first-seen file order. Errors if an op
423/// names no path and there is no top-level fallback.
424fn group_ops_by_path(
425    ops: &[Value],
426    top_path: Option<&str>,
427) -> Result<Vec<(String, Vec<Value>)>, String> {
428    if ops.is_empty() {
429        return Err("ops[] is empty — provide at least one edit".to_string());
430    }
431    let mut order: Vec<String> = Vec::new();
432    let mut by_path: std::collections::HashMap<String, Vec<Value>> =
433        std::collections::HashMap::new();
434    for (i, op) in ops.iter().enumerate() {
435        let obj = op
436            .as_object()
437            .ok_or_else(|| format!("ops[{i}] must be an object"))?;
438        let raw = obj
439            .get("path")
440            .and_then(Value::as_str)
441            .map(str::to_string)
442            .or_else(|| top_path.map(str::to_string))
443            .ok_or_else(|| {
444                format!("ops[{i}] needs its own 'path' (no top-level 'path' to fall back to)")
445            })?;
446        if !by_path.contains_key(&raw) {
447            order.push(raw.clone());
448        }
449        by_path.entry(raw).or_default().push(op.clone());
450    }
451    Ok(order
452        .into_iter()
453        .map(|p| {
454            let ops = by_path.remove(&p).unwrap_or_default();
455            (p, ops)
456        })
457        .collect())
458}
459
460/// Apply one file's anchored patch: acquire the per-file lock, run the I/O off
461/// the global cache lock, then fold the resulting cache effect and session mark.
462/// Returns the rendered patch/CONFLICT text. Shared by the single-op and the
463/// per-file batch paths (#1005).
464fn apply_one(
465    ctx: &ToolContext,
466    params: &crate::tools::ctx_patch::PatchParams,
467) -> Result<String, ErrorData> {
468    let path = params.path.clone();
469    {
470        let cache_lock = ctx
471            .cache
472            .as_ref()
473            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
474
475        // Serialize edits to the SAME file via the shared per-file lock (the same
476        // registry ctx_edit/ctx_read use), so anchored and str_replace edits of
477        // one file never interleave (issue #320). Correctness across processes
478        // still rests on the TOCTOU preimage guard + atomic rename.
479        let file_lock = crate::core::path_locks::per_file_lock(&path);
480        let _file_guard = {
481            let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
482            loop {
483                if let Ok(guard) = file_lock.try_lock() {
484                    break guard;
485                }
486                if std::time::Instant::now() >= deadline {
487                    return Err(ErrorData::internal_error(
488                        format!(
489                            "per-file edit lock contention for {path} — another edit to the same file is in progress, retry in a moment"
490                        ),
491                        None,
492                    ));
493                }
494                std::thread::sleep(std::time::Duration::from_millis(20));
495            }
496        };
497
498        let last_mode = match crate::server::bounded_lock::read(cache_lock, "ctx_patch cache read")
499        {
500            Some(cache) => cache
501                .get(&path)
502                .map(|e| e.last_mode.clone())
503                .unwrap_or_default(),
504            None => String::new(),
505        };
506
507        // Heavy disk I/O — no global cache lock held here.
508        let before = std::fs::read(&path).unwrap_or_default();
509        let (output, effect) = crate::tools::ctx_patch::run_io(params, &last_mode);
510
511        if matches!(effect, crate::tools::ctx_edit::CacheEffect::Invalidate) {
512            let after = std::fs::read(&path).unwrap_or_default();
513            super::ctx_edit::observe_mcp_edit(ctx, &path, "ctx_patch", &before, &after);
514        }
515
516        crate::tools::ctx_patch::record_outcome(params, &last_mode, &output, &effect);
517
518        if !matches!(effect, crate::tools::ctx_edit::CacheEffect::None) {
519            crate::tools::ctx_read::dedup_hook::on_write(&path);
520            match crate::server::bounded_lock::write(cache_lock, "ctx_patch cache write") {
521                Some(mut cache) => {
522                    crate::tools::ctx_edit::apply_cache_effect(&mut cache, &path, effect);
523                }
524                None => {
525                    tracing::warn!(
526                        "ctx_patch: cache write-lock timeout applying effect for {path}"
527                    );
528                }
529            }
530        }
531
532        if let Some(session_lock) = ctx.session.as_ref() {
533            if let Some(mut session) =
534                crate::server::bounded_lock::write(session_lock, "ctx_patch session write")
535            {
536                session.mark_modified(&path);
537            }
538        }
539
540        Ok(output)
541    }
542}
543
544/// Handle `op="replace_symbol"` by translating to `ctx_refactor`'s
545/// `replace_symbol_body` and dispatching through it. The symbol-resolution,
546/// CONFLICT guard and atomic write all live in ctx_refactor — this is a thin,
547/// pure-mapping adapter (mapping logic lives in `ctx_patch::symbol`).
548fn delegate_replace_symbol(
549    args: &Map<String, Value>,
550    ctx: &ToolContext,
551) -> Result<ToolOutput, ErrorData> {
552    let refactor_args = crate::tools::ctx_patch::build_refactor_args(args)
553        .map_err(|e| ErrorData::invalid_params(e, None))?;
554
555    if get_bool(args, "dry_run").unwrap_or(false) {
556        let name = get_str(args, "name").unwrap_or_default();
557        let path = get_str(args, "path").unwrap_or_default();
558        return Ok(ToolOutput::simple(format!(
559            "DRY RUN: replace_symbol would rewrite symbol {name:?} in {path}"
560        )));
561    }
562
563    // Resolve `path` at the boundary when given (the name route resolves its own
564    // path inside ctx_refactor). abs_path is unused by the symbol-edit branch but
565    // we mirror ctx_refactor's wrapper to keep jail behaviour identical.
566    let has_path = args.get("path").and_then(Value::as_str).is_some();
567    let abs_path = if has_path {
568        require_resolved_path(ctx, args, "path")?
569    } else {
570        String::new()
571    };
572
573    let args_value = Value::Object(refactor_args);
574    let result = crate::tools::ctx_refactor::handle(&args_value, &ctx.project_root, &abs_path);
575    let changed = !result.starts_with("ERROR") && !result.starts_with("CONFLICT");
576
577    Ok(ToolOutput {
578        text: result,
579        original_tokens: 0,
580        saved_tokens: 0,
581        mode: Some("replace_symbol".to_string()),
582        path: get_str(args, "path"),
583        changed,
584        shell_outcome: None,
585        content_blocks: None,
586    })
587}
588
589/// #879: resolve `find`/`replace` for replace_all, failing *closed* on the
590/// destructive path. Historically a missing `replace` defaulted to "" — so a
591/// typo'd replacement key (`new_string=`/`new_text=` carried over from the other
592/// ops) meant "delete every match" and still reported success. Now: reject
593/// replacement keys that belong to other ops, and require `replace` to be
594/// present. An empty deletion must be opted into explicitly with `replace=""`.
595fn resolve_find_replace(args: &Map<String, Value>) -> Result<(String, String), String> {
596    let find = get_str(args, "find")
597        .filter(|s| !s.is_empty())
598        .ok_or("replace_all requires non-empty 'find'")?;
599
600    for foreign in ["new_text", "new_string", "old_string"] {
601        if args.contains_key(foreign) {
602            return Err(format!(
603                "replace_all names its replacement 'replace', not '{foreign}' — rename it \
604                 (an unrecognized replacement key would silently delete every match)"
605            ));
606        }
607    }
608
609    let replace = args
610        .get("replace")
611        .and_then(Value::as_str)
612        .map(String::from)
613        .ok_or(
614            "replace_all requires 'replace' (the replacement text); pass replace=\"\" \
615             explicitly to delete every match",
616        )?;
617
618    Ok((find, replace))
619}
620
621/// #825: Bulk literal find-and-replace — no anchors needed.
622fn handle_replace_all(
623    args: &Map<String, Value>,
624    ctx: &ToolContext,
625) -> Result<ToolOutput, ErrorData> {
626    let path = require_resolved_path(ctx, args, "path")?;
627    let (find, replace) =
628        resolve_find_replace(args).map_err(|e| ErrorData::invalid_params(e, None))?;
629    let dry_run = get_bool(args, "dry_run").unwrap_or(false);
630
631    let content = std::fs::read_to_string(&path)
632        .map_err(|e| ErrorData::internal_error(format!("cannot read {path}: {e}"), None))?;
633
634    let count = content.matches(find.as_str()).count();
635    if count == 0 {
636        return Ok(ToolOutput::simple(format!(
637            "No matches for {find:?} in {path}"
638        )));
639    }
640
641    if dry_run {
642        return Ok(ToolOutput::simple(format!(
643            "DRY RUN: {count} occurrence(s) of {find:?} would be replaced with {replace:?} in {path}"
644        )));
645    }
646
647    let file_lock = crate::core::path_locks::per_file_lock(&path);
648    let _guard = file_lock
649        .lock()
650        .map_err(|_| ErrorData::internal_error(format!("lock contention for {path}"), None))?;
651
652    let new_content = content.replace(find.as_str(), &replace);
653    crate::config_io::write_atomic(std::path::Path::new(&path), &new_content)
654        .map_err(|e| ErrorData::internal_error(format!("write failed: {e}"), None))?;
655    super::ctx_edit::observe_mcp_edit(
656        ctx,
657        &path,
658        "ctx_patch",
659        content.as_bytes(),
660        new_content.as_bytes(),
661    );
662
663    if let Some(cache) = ctx.cache.as_ref() {
664        if let Some(mut c) =
665            crate::server::bounded_lock::write(cache, "ctx_patch replace_all cache invalidate")
666        {
667            c.invalidate(&path);
668        }
669    }
670
671    Ok(ToolOutput::simple(format!(
672        "Replaced {count} occurrence(s) of {find:?} with {replace:?} in {path}"
673    )))
674}
675
676#[cfg(test)]
677mod replace_all_tests {
678    use super::*;
679    use serde_json::json;
680
681    fn obj(v: Value) -> Map<String, Value> {
682        match v {
683            Value::Object(m) => m,
684            _ => panic!("expected object"),
685        }
686    }
687
688    #[test]
689    fn resolves_find_and_replace() {
690        let (f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": "b"}))).unwrap();
691        assert_eq!((f.as_str(), r.as_str()), ("a", "b"));
692    }
693
694    #[test]
695    fn explicit_empty_replace_is_a_deletion() {
696        let (_f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": ""}))).unwrap();
697        assert_eq!(r, "");
698    }
699
700    #[test]
701    fn missing_replace_is_rejected_not_silent_delete() {
702        let err = resolve_find_replace(&obj(json!({"find": "a"}))).unwrap_err();
703        assert!(err.contains("requires 'replace'"), "got: {err}");
704    }
705
706    #[test]
707    fn foreign_replacement_key_is_rejected() {
708        for key in ["new_string", "new_text", "old_string"] {
709            let err = resolve_find_replace(&obj(json!({"find": "a", key: "b"}))).unwrap_err();
710            assert!(
711                err.contains(key),
712                "must name the offending key {key}: {err}"
713            );
714        }
715    }
716
717    #[test]
718    fn empty_find_is_rejected() {
719        let err = resolve_find_replace(&obj(json!({"find": "", "replace": "b"}))).unwrap_err();
720        assert!(err.contains("find"), "got: {err}");
721    }
722}
723
724#[cfg(test)]
725mod batch_grouping_tests {
726    use super::*;
727    use serde_json::json;
728
729    /// #1005: a batch spanning two files groups ops per file, preserving the
730    /// first-seen file order — no top-level `path` needed.
731    #[test]
732    fn groups_ops_across_files_preserving_order() {
733        let ops = vec![
734            json!({"op":"insert_after","path":"a.go","line":1,"hash":"aa","new_text":"x"}),
735            json!({"op":"insert_after","path":"b.go","line":2,"hash":"bb","new_text":"y"}),
736            json!({"op":"set_line","path":"a.go","line":3,"hash":"cc","new_text":"z"}),
737        ];
738        let g = group_ops_by_path(&ops, None).unwrap();
739        assert_eq!(g.len(), 2);
740        assert_eq!(g[0].0, "a.go");
741        assert_eq!(g[0].1.len(), 2);
742        assert_eq!(g[1].0, "b.go");
743        assert_eq!(g[1].1.len(), 1);
744    }
745
746    #[test]
747    fn ops_without_path_fall_back_to_top_level() {
748        let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
749        let g = group_ops_by_path(&ops, Some("top.go")).unwrap();
750        assert_eq!(g.len(), 1);
751        assert_eq!(g[0].0, "top.go");
752    }
753
754    #[test]
755    fn op_without_path_and_no_top_level_is_rejected() {
756        let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
757        let err = group_ops_by_path(&ops, None).unwrap_err();
758        assert!(err.contains("path"), "got: {err}");
759    }
760
761    #[test]
762    fn empty_ops_rejected() {
763        let err = group_ops_by_path(&[], None).unwrap_err();
764        assert!(err.contains("empty"), "got: {err}");
765    }
766
767    #[test]
768    fn cross_file_rejects_single_value_preimage_and_backup_options() {
769        for key in ["expected_md5", "backup_path"] {
770            let args = Map::from_iter([(key.to_string(), json!("one-value"))]);
771            assert!(validate_cross_file_options(&args, 2).is_err());
772            assert!(validate_cross_file_options(&args, 1).is_ok());
773        }
774    }
775
776    #[test]
777    fn replace_unique_maps_to_a_single_safe_ctx_edit_replacement() {
778        let args = Map::from_iter([
779            ("path".into(), json!("a.rs")),
780            ("op".into(), json!("replace_unique")),
781            ("old_text".into(), json!("old")),
782            ("new_text".into(), json!("new")),
783        ]);
784        let mapped = build_unique_edit_args(&args).expect("valid mapping");
785        assert_eq!(mapped.get("old_string"), Some(&json!("old")));
786        assert_eq!(mapped.get("new_string"), Some(&json!("new")));
787        assert_eq!(mapped.get("replace_all"), Some(&json!(false)));
788        assert!(!mapped.contains_key("op"));
789        assert!(!mapped.contains_key("old_text"));
790    }
791
792    #[test]
793    fn replace_unique_requires_explicit_old_and_new_text() {
794        assert!(build_unique_edit_args(&Map::new()).is_err());
795        let only_old = Map::from_iter([("old_text".into(), json!("old"))]);
796        assert!(build_unique_edit_args(&only_old).is_err());
797    }
798
799    #[test]
800    fn dry_run_replace_unique_does_not_apply() {
801        let args = Map::from_iter([
802            ("path".into(), json!("a.rs")),
803            ("op".into(), json!("replace_unique")),
804            ("old_text".into(), json!("old")),
805            ("new_text".into(), json!("new")),
806            ("dry_run".into(), json!(true)),
807        ]);
808        let edit_args = build_unique_edit_args(&args).expect("validation passes");
809        assert!(
810            edit_args.contains_key("old_string"),
811            "args mapped correctly"
812        );
813        assert!(
814            args.get("dry_run").and_then(Value::as_bool) == Some(true),
815            "dry_run flag preserved in original args"
816        );
817    }
818}