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