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