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