1use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5
6use crate::server::tool_trait::{
7 McpTool, ToolContext, ToolOutput, get_bool, get_int, get_str, require_resolved_path,
8 tool_execution_error,
9};
10use lean_ctx::tool_defs::tool_def;
11
12pub struct CtxPatchTool;
13
14pub(crate) fn host_draws_diffs(ctx: &ToolContext) -> bool {
18 static MOD_PRESENT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
19 let claude = ctx
20 .client_name
21 .as_ref()
22 .and_then(|name| {
23 name.try_read()
24 .ok()
25 .map(|n| n.to_ascii_lowercase().contains("claude"))
26 })
27 .unwrap_or(false);
28 claude
29 && *MOD_PRESENT.get_or_init(|| {
30 std::env::var_os("CLAUDE_CONFIG_DIR")
31 .map(std::path::PathBuf::from)
32 .or_else(|| dirs::home_dir().map(|home| home.join(".claude")))
33 .is_some_and(|dir| {
34 !lean_ctx_hooks::hooks::agents::claude_mod::cached_versions(&dir).is_empty()
35 })
36 })
37}
38
39impl McpTool for CtxPatchTool {
40 fn name(&self) -> &'static str {
41 "ctx_patch"
42 }
43
44 fn tool_def(&self) -> Tool {
51 tool_def(
52 "ctx_patch",
53 "Safe file edit; relative paths as in ctx_read. replace_unique(path,old_text,new_text): \
54 exact unique replacement, needs no anchors. Line ops take line+hash from \
55 ctx_read(mode=\"anchored:N-M\"); CONFLICT means re-read. ops[] batch \
56 (cross-file, incl. replace_unique/replace_symbol); create and replace_all only \
57 as top-level calls. A 0-byte file: create, or replace_unique with old_text=\"\".",
58 json!({
59 "type": "object",
60 "properties": {
61 "path": { "type": "string", "description": "Absolute, or relative to project root (in a git worktree use absolute paths)" },
62 "op": { "type": "string", "enum": ["set_line", "replace_lines", "insert_after", "delete", "replace_unique", "replace_symbol", "create", "replace_all"] },
63 "line": { "type": "integer" },
64 "hash": { "type": "string" },
65 "start_line": { "type": "integer" },
66 "start_hash": { "type": "string" },
67 "end_line": { "type": "integer" },
68 "end_hash": { "type": "string" },
69 "new_text": { "type": "string" },
70 "old_text": { "type": "string" },
71 "name": { "type": "string" },
72 "find": { "type": "string" },
73 "replace": { "type": "string" },
74 "dry_run": { "type": "boolean" },
75 "ops": { "type": "array", "items": { "type": "object" } }
76 },
77 "allOf": [
85 { "if": { "properties": { "op": { "const": "set_line" } }, "required": ["op"] },
86 "then": { "required": ["op", "line", "hash", "new_text"] } },
87 { "if": { "properties": { "op": { "const": "replace_lines" } }, "required": ["op"] },
88 "then": { "required": ["op", "start_line", "start_hash", "end_line", "end_hash", "new_text"] } },
89 { "if": { "properties": { "op": { "const": "replace_unique" } }, "required": ["op"] },
90 "then": { "required": ["op", "old_text", "new_text"] } },
91 { "if": { "properties": { "op": { "const": "replace_symbol" } }, "required": ["op"] },
92 "then": { "required": ["op", "new_text"] } },
93 { "if": { "properties": { "op": { "const": "create" } }, "required": ["op"] },
94 "then": { "required": ["op", "new_text"] } },
95 { "if": { "properties": { "op": { "const": "replace_all" } }, "required": ["op"] },
96 "then": { "required": ["op", "find", "replace"] } }
97 ]
98 }),
99 )
100 }
101
102 fn handle(
103 &self,
104 args: &Map<String, Value>,
105 ctx: &ToolContext,
106 ) -> Result<ToolOutput, ErrorData> {
107 crate::tools::claims_gate::scoped(ctx, || handle_patch(args, ctx))
112 }
113}
114
115fn handle_patch(args: &Map<String, Value>, ctx: &ToolContext) -> Result<ToolOutput, ErrorData> {
116 let inferred = infer_replace_unique(args);
117 let args = inferred.as_ref().unwrap_or(args);
118
119 if crate::tools::ctx_patch::is_replace_symbol(args) {
122 return delegate_replace_symbol(args, ctx);
123 }
124
125 if get_str(args, "op").as_deref() == Some("replace_unique") {
126 return delegate_replace_unique(args, ctx);
127 }
128
129 if get_str(args, "op").as_deref() == Some("replace_all") {
131 return handle_replace_all(args, ctx);
132 }
133
134 if let Some(arr) = args.get("ops").and_then(Value::as_array) {
138 for (i, v) in arr.iter().enumerate() {
140 if let Some(kind) = is_unbatchable_op(v) {
141 return Err(ErrorData::invalid_params(
142 format!(
143 "ops[{i}]: {kind} cannot be batched in ops[] \
144 — send it as a separate top-level ctx_patch call"
145 ),
146 None,
147 ));
148 }
149 }
150 if arr.iter().any(|v| delegated_op_kind(v).is_some()) {
151 return handle_mixed_batch(args, arr, ctx);
152 }
153 }
154
155 handle_anchored(args, ctx)
156}
157
158fn handle_anchored(args: &Map<String, Value>, ctx: &ToolContext) -> Result<ToolOutput, ErrorData> {
162 if get_bool(args, "dry_run").unwrap_or(false) {
163 let path = get_str(args, "path").unwrap_or_default();
164 return Ok(ToolOutput::simple(format!(
165 "DRY RUN: ctx_patch would apply anchor-based ops to {path}"
166 )));
167 }
168
169 let expected_blake3 =
172 get_str(args, "expected_blake3").or_else(|| get_str(args, "expected_md5"));
173 let backup = get_bool(args, "backup").unwrap_or(false);
174 let backup_path = get_str(args, "backup_path")
175 .map(|p| ctx.resolved_paths.get("backup_path").cloned().unwrap_or(p))
176 .map(|p| lean_ctx::core::workspace_authority::confine(&p, &ctx.project_root, true))
177 .transpose()
178 .map_err(|error| ErrorData::invalid_params(error, None))?;
179 let evidence = get_bool(args, "evidence").unwrap_or(false);
181 let diff_max_lines = get_int(args, "diff_max_lines")
182 .and_then(|v| usize::try_from(v.max(0)).ok())
183 .unwrap_or(200);
184 let allow_lossy_utf8 = get_bool(args, "allow_lossy_utf8").unwrap_or(false);
185 let validate_syntax = get_bool(args, "validate_syntax").unwrap_or(true);
186
187 let groups = plan_groups(args, ctx)?;
191 validate_cross_file_options(args, groups.len())?;
192 let output_path = (groups.len() == 1).then(|| groups[0].0.clone());
193 let label_parts = groups.len() > 1;
196 let diff_artifact = host_draws_diffs(ctx);
197
198 let mut texts = Vec::with_capacity(groups.len());
199 for (path, ops) in groups {
200 let patch_params = crate::tools::ctx_patch::PatchParams {
201 path: path.clone(),
202 ops,
203 expected_blake3: expected_blake3.clone(),
204 backup,
205 backup_path: backup_path.clone(),
206 evidence,
207 diff_artifact,
208 diff_max_lines,
209 allow_lossy_utf8,
210 validate_syntax,
211 };
212 let output =
213 apply_one(ctx, &patch_params).map_err(|error| with_prior_edits(error, &texts))?;
214 texts.push(if label_parts {
215 format!("[{}]\n{output}", receipt_label(&path, &ctx.project_root))
216 } else {
217 output
218 });
219 }
220
221 Ok(ToolOutput {
222 text: texts.join("\n\n"),
223 original_tokens: 0,
224 saved_tokens: 0,
225 mode: None,
226 path: output_path,
227 changed: false,
228 shell_outcome: None,
229 content_blocks: None,
230 })
231}
232
233fn infer_replace_unique(args: &Map<String, Value>) -> Option<Map<String, Value>> {
243 fn is_text_replacement(obj: &Map<String, Value>) -> bool {
244 let text = |keys: [&str; 2]| keys.iter().find_map(|key| obj.get(*key)?.as_str());
245 !obj.contains_key("op")
246 && text(["old_text", "old_string"]).is_some_and(|old| !old.is_empty())
247 && text(["new_text", "new_string"]).is_some()
248 }
249 fn alias(obj: &mut Map<String, Value>, key: &str, aliases: &[&str]) -> bool {
251 if obj.contains_key(key) {
252 return false;
253 }
254 let Some(value) = aliases
255 .iter()
256 .find_map(|alias| obj.get(*alias).filter(|v| v.is_string()).cloned())
257 else {
258 return false;
259 };
260 obj.insert(key.to_string(), value);
261 true
262 }
263 fn repair(obj: &mut Map<String, Value>) -> bool {
264 let mut changed = false;
265 if is_text_replacement(obj) {
266 obj.insert("op".into(), json!("replace_unique"));
267 changed = true;
268 }
269 match obj.get("op").and_then(Value::as_str) {
270 Some("replace_unique") => {
271 changed |= alias(obj, "old_text", &["old_string", "find"]);
272 changed |= alias(obj, "new_text", &["new_string", "replace"]);
273 }
274 Some("create") => changed |= alias(obj, "new_text", &["new_string", "content"]),
275 Some("set_line" | "replace_lines" | "insert_after") => {
276 changed |= alias(obj, "new_text", &["new_string"]);
277 }
278 _ => {}
279 }
280 changed
281 }
282 let mut out = args.clone();
283 let mut repaired = false;
284 if let Some(Value::String(encoded)) = out.get("ops")
285 && let Ok(Value::Array(ops)) = serde_json::from_str::<Value>(encoded)
286 {
287 out.insert("ops".into(), Value::Array(ops));
288 repaired = true;
289 }
290 if !out.contains_key("ops") {
291 repaired |= repair(&mut out);
292 }
293 if let Some(Value::Array(ops)) = out.get_mut("ops") {
294 for op in ops.iter_mut().filter_map(Value::as_object_mut) {
295 repaired |= repair(op);
296 }
297 }
298 repaired.then_some(out)
299}
300
301fn delegated_op_kind(v: &Value) -> Option<&str> {
304 v.get("op")
305 .and_then(Value::as_str)
306 .filter(|k| matches!(*k, "replace_unique" | "replace_symbol"))
307}
308
309fn is_unbatchable_op(v: &Value) -> Option<&str> {
317 v.get("op")
318 .and_then(Value::as_str)
319 .filter(|k| matches!(*k, "replace_all" | "create"))
320}
321
322fn handle_mixed_batch(
323 args: &Map<String, Value>,
324 arr: &[Value],
325 ctx: &ToolContext,
326) -> Result<ToolOutput, ErrorData> {
327 for (i, v) in arr.iter().enumerate() {
329 if !v.is_object() {
330 return Err(ErrorData::invalid_params(
331 format!("ops[{i}] must be an object"),
332 None,
333 ));
334 }
335 if let Some(kind) = is_unbatchable_op(v) {
336 return Err(ErrorData::invalid_params(
337 format!(
338 "ops[{i}]: {kind} cannot be batched in ops[] \
339 — send it as a separate top-level ctx_patch call"
340 ),
341 None,
342 ));
343 }
344 }
345
346 let top_path = get_str(args, "path");
349 let mut targets = std::collections::BTreeSet::new();
350 let mut unknown_target = false;
351 for v in arr {
352 match v
353 .get("path")
354 .and_then(Value::as_str)
355 .or(top_path.as_deref())
356 {
357 Some(p) => {
358 targets.insert(p);
359 }
360 None => unknown_target = true,
361 }
362 }
363 let label_parts = unknown_target || targets.len() > 1;
364
365 let mut texts: Vec<String> = Vec::new();
366 let mut run: Vec<Value> = Vec::new();
367 for (i, v) in arr.iter().enumerate() {
368 let obj = v.as_object().ok_or_else(|| {
369 ErrorData::invalid_params(format!("ops[{i}] must be an object"), None)
370 })?;
371 let Some(kind) = delegated_op_kind(v) else {
372 run.push(v.clone());
373 continue;
374 };
375 flush_anchored_run(args, ctx, &mut run, &mut texts)?;
376
377 let (sub_args, sub_ctx) = delegated_op_call(args, obj, ctx, i, kind)
378 .map_err(|error| with_prior_edits(error, &texts))?;
379 let out = if kind == "replace_unique" {
380 delegate_replace_unique(&sub_args, &sub_ctx)
381 } else {
382 delegate_replace_symbol(&sub_args, &sub_ctx)
383 }
384 .map_err(|mut e| {
385 e.message = format!("ops[{i}] ({kind}): {}", e.message).into();
386 with_prior_edits(e, &texts)
387 })?;
388 if label_parts {
389 let label = sub_ctx.resolved_path("path").map_or_else(
390 || kind.to_string(),
391 |resolved| receipt_label(resolved, &ctx.project_root),
392 );
393 texts.push(format!("[{label}]\n{}", out.text));
394 } else {
395 texts.push(out.text);
396 }
397 }
398 flush_anchored_run(args, ctx, &mut run, &mut texts)?;
399
400 Ok(ToolOutput::simple(texts.join("\n\n")))
401}
402
403fn receipt_label(resolved: &str, project_root: &str) -> String {
409 let display = lean_ctx::core::protocol::display_path(resolved);
410 let canonical_root = std::fs::canonicalize(project_root).ok().map(|p| {
411 lean_ctx::core::pathutil::strip_verbatim(p)
412 .to_string_lossy()
413 .into_owned()
414 });
415 for root in std::iter::once(project_root.to_string()).chain(canonical_root) {
416 let root = lean_ctx::core::protocol::display_path(&root);
417 let root = root.trim_end_matches('/');
418 let (Some(head), Some(rest)) = (display.get(..root.len()), display.get(root.len()..))
419 else {
420 continue;
421 };
422 if root.is_empty() || rest.len() < 2 {
423 continue;
424 }
425 let same_root = if cfg!(windows) {
426 head.eq_ignore_ascii_case(root)
427 } else {
428 head == root
429 };
430 if same_root && let Some(rel) = rest.strip_prefix('/') {
431 return rel.to_string();
432 }
433 }
434 display
435}
436
437fn flush_anchored_run(
439 args: &Map<String, Value>,
440 ctx: &ToolContext,
441 run: &mut Vec<Value>,
442 texts: &mut Vec<String>,
443) -> Result<(), ErrorData> {
444 if run.is_empty() {
445 return Ok(());
446 }
447 let mut sub = args.clone();
448 sub.insert("ops".into(), Value::Array(std::mem::take(run)));
449 texts.push(
450 handle_anchored(&sub, ctx)
451 .map_err(|error| with_prior_edits(error, texts))?
452 .text,
453 );
454 Ok(())
455}
456
457fn with_prior_edits(mut error: ErrorData, texts: &[String]) -> ErrorData {
460 if !texts.is_empty() {
461 error.code = crate::server::tool_trait::TOOL_EXECUTION_ERROR;
462 error.message = format!(
463 "{}\nEarlier ops in this batch were already applied:\n{}",
464 error.message,
465 texts.join("\n\n")
466 )
467 .into();
468 }
469 error
470}
471
472fn delegated_op_call(
477 args: &Map<String, Value>,
478 op: &Map<String, Value>,
479 ctx: &ToolContext,
480 i: usize,
481 kind: &str,
482) -> Result<(Map<String, Value>, ToolContext), ErrorData> {
483 let mut sub = op.clone();
484 for key in ["path", "dry_run"] {
485 if !sub.contains_key(key)
486 && let Some(v) = args.get(key)
487 {
488 sub.insert(key.to_string(), v.clone());
489 }
490 }
491
492 let mut sub_ctx = ctx.clone();
493 sub_ctx.resolved_paths.remove("path");
494 sub_ctx.path_errors.remove("path");
495 match get_str(&sub, "path") {
496 Some(raw) => {
497 let resolved = resolve_op_path(&sub_ctx, &raw)
498 .map_err(|e| ErrorData::invalid_params(format!("ops[{i}]: path: {e}"), None))?;
499 sub_ctx
500 .ensure_writable(&resolved)
501 .map_err(|e| ErrorData::invalid_params(format!("ops[{i}]: {e}"), None))?;
502 sub_ctx.resolved_paths.insert("path".to_string(), resolved);
503 }
504 None if kind == "replace_unique" => {
507 return Err(ErrorData::invalid_params(
508 format!("ops[{i}] needs its own 'path' (no top-level 'path' to fall back to)"),
509 None,
510 ));
511 }
512 None => {}
513 }
514 Ok((sub, sub_ctx))
515}
516
517fn delegate_replace_unique(
521 args: &Map<String, Value>,
522 ctx: &ToolContext,
523) -> Result<ToolOutput, ErrorData> {
524 let edit_args =
525 build_unique_edit_args(args).map_err(|message| ErrorData::invalid_params(message, None))?;
526
527 if get_str(&edit_args, "old_string").is_some_and(|old| old.is_empty()) {
532 let path = require_resolved_path(ctx, args, "path")?;
533 if let Some(message) = empty_old_text_refusal(std::path::Path::new(&path)) {
534 return Err(ErrorData::invalid_params(message, None));
535 }
536 }
537
538 if get_bool(args, "dry_run").unwrap_or(false) {
539 let old_text = get_str(args, "old_text")
540 .or_else(|| get_str(args, "old_string"))
541 .unwrap_or_default();
542 let new_text = get_str(args, "new_text")
543 .or_else(|| get_str(args, "new_string"))
544 .unwrap_or_default();
545 let path = get_str(args, "path").unwrap_or_default();
546 return Ok(ToolOutput::simple(format!(
547 "DRY RUN: replace_unique would replace {old_text:?} with {new_text:?} in {path}"
548 )));
549 }
550
551 crate::tools::registered::ctx_edit::handle_edit(&edit_args, ctx, host_draws_diffs(ctx))
552}
553
554fn empty_old_text_refusal(path: &std::path::Path) -> Option<String> {
558 let shown = path.display();
559 match std::fs::symlink_metadata(path) {
560 Ok(meta) if meta.file_type().is_file() && meta.len() == 0 => None,
561 Ok(meta) if meta.file_type().is_file() => Some(format!(
562 "replace_unique with empty old_text only fills an existing empty (0-byte) file; \
563 {shown} has content. Quote unique text from it as old_text, or use anchored ops \
564 (ctx_read mode=\"anchored\" → insert_after/set_line/replace_lines)"
565 )),
566 Ok(_) => Some(format!(
567 "replace_unique with empty old_text only fills an existing empty regular file; \
568 {shown} is not one (symlink or directory)"
569 )),
570 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Some(format!(
571 "replace_unique with empty old_text only fills an existing empty file; \
572 {shown} does not exist — use op=create to write a new file"
573 )),
574 Err(error) => Some(format!("cannot inspect {shown}: {error}")),
575 }
576}
577
578fn build_unique_edit_args(args: &Map<String, Value>) -> Result<Map<String, Value>, String> {
579 let old_text = get_str(args, "old_text")
582 .or_else(|| get_str(args, "old_string"))
583 .ok_or_else(|| {
584 "replace_unique requires old_text (old_string also accepted); an empty \
585 old_text fills an existing empty file"
586 .to_string()
587 })?;
588 let new_text = get_str(args, "new_text")
589 .or_else(|| get_str(args, "new_string"))
590 .ok_or_else(|| "replace_unique requires new_text (new_string also accepted)".to_string())?;
591
592 let mut edit_args = args.clone();
593 edit_args.insert("old_string".into(), Value::String(old_text));
594 edit_args.insert("new_string".into(), Value::String(new_text));
595 edit_args.insert("replace_all".into(), Value::Bool(false));
596 edit_args.remove("old_text");
597 edit_args.remove("op");
598 edit_args.remove("create");
601 Ok(edit_args)
602}
603
604fn validate_cross_file_options(
608 args: &Map<String, Value>,
609 file_count: usize,
610) -> Result<(), ErrorData> {
611 if file_count <= 1 {
612 return Ok(());
613 }
614 for key in ["expected_blake3", "expected_md5", "backup_path"] {
615 if args.contains_key(key) {
616 return Err(ErrorData::invalid_params(
617 format!("cross-file ctx_patch batches do not support top-level '{key}'"),
618 None,
619 ));
620 }
621 }
622 Ok(())
623}
624
625fn plan_groups(
630 args: &Map<String, Value>,
631 ctx: &ToolContext,
632) -> Result<Vec<(String, Vec<crate::tools::ctx_patch::AnchorOp>)>, ErrorData> {
633 let Some(ops_val) = args.get("ops") else {
634 let path = require_resolved_path(ctx, args, "path")?;
635 let ops = crate::tools::ctx_patch::parse_ops(args)
636 .map_err(|e| ErrorData::invalid_params(e, None))?;
637 return Ok(vec![(path, ops)]);
638 };
639
640 let arr = ops_val
641 .as_array()
642 .ok_or_else(|| ErrorData::invalid_params("ops must be an array of edit objects", None))?;
643 let grouped = group_ops_by_path(arr, get_str(args, "path").as_deref())
644 .map_err(|e| ErrorData::invalid_params(e, None))?;
645
646 let mut groups = Vec::with_capacity(grouped.len());
647 for (raw_path, op_objs) in grouped {
648 let resolved = resolve_op_path(ctx, &raw_path)
649 .map_err(|e| ErrorData::invalid_params(format!("path: {e}"), None))?;
650 ctx.ensure_writable(&resolved)
651 .map_err(|e| ErrorData::invalid_params(e, None))?;
652 let sub = Map::from_iter([("ops".to_string(), Value::Array(op_objs))]);
653 let ops = crate::tools::ctx_patch::parse_ops(&sub)
654 .map_err(|e| ErrorData::invalid_params(e, None))?;
655 groups.push((resolved, ops));
656 }
657 Ok(groups)
658}
659
660fn resolve_op_path(ctx: &ToolContext, raw: &str) -> Result<String, String> {
663 ctx.resolve_path_sync(raw)
664}
665
666fn group_ops_by_path(
670 ops: &[Value],
671 top_path: Option<&str>,
672) -> Result<Vec<(String, Vec<Value>)>, String> {
673 if ops.is_empty() {
674 return Err("ops[] is empty — provide at least one edit".to_string());
675 }
676 let mut order: Vec<String> = Vec::new();
677 let mut by_path: std::collections::HashMap<String, Vec<Value>> =
678 std::collections::HashMap::new();
679 for (i, op) in ops.iter().enumerate() {
680 let obj = op
681 .as_object()
682 .ok_or_else(|| format!("ops[{i}] must be an object"))?;
683 let raw = obj
684 .get("path")
685 .and_then(Value::as_str)
686 .map(str::to_string)
687 .or_else(|| top_path.map(str::to_string))
688 .ok_or_else(|| {
689 format!("ops[{i}] needs its own 'path' (no top-level 'path' to fall back to)")
690 })?;
691 if !by_path.contains_key(&raw) {
692 order.push(raw.clone());
693 }
694 by_path.entry(raw).or_default().push(op.clone());
695 }
696 Ok(order
697 .into_iter()
698 .map(|p| {
699 let ops = by_path.remove(&p).unwrap_or_default();
700 (p, ops)
701 })
702 .collect())
703}
704
705fn apply_one(
710 ctx: &ToolContext,
711 params: &crate::tools::ctx_patch::PatchParams,
712) -> Result<String, ErrorData> {
713 let path = params.path.clone();
714 {
715 let cache_lock = ctx
716 .cache
717 .as_ref()
718 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
719
720 let file_lock = lean_ctx_ext::core::path_locks::per_file_lock(&path);
725 let _file_guard = {
726 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
727 loop {
728 if let Ok(guard) = file_lock.try_lock() {
729 break guard;
730 }
731 if std::time::Instant::now() >= deadline {
732 return Err(ErrorData::internal_error(
733 format!(
734 "per-file edit lock contention for {path} — another edit to the same file is in progress, retry in a moment"
735 ),
736 None,
737 ));
738 }
739 std::thread::sleep(std::time::Duration::from_millis(20));
740 }
741 };
742
743 let last_mode = match crate::server::bounded_lock::read(cache_lock, "ctx_patch cache read")
744 {
745 Some(cache) => cache
746 .get(&path)
747 .map(|e| e.last_mode.clone())
748 .unwrap_or_default(),
749 None => String::new(),
750 };
751
752 let before = std::fs::read(&path).unwrap_or_default();
754 let (output, effect) =
755 crate::tools::edit_recovery::with_project_root(&ctx.project_root, || {
756 crate::tools::ctx_patch::run_io(params, &last_mode)
757 });
758 let written = matches!(effect, crate::tools::ctx_edit::CacheEffect::Invalidate);
759
760 if written {
761 let after = std::fs::read(&path).unwrap_or_default();
762 super::ctx_edit::observe_mcp_edit(ctx, &path, "ctx_patch", &before, &after);
763 }
764
765 crate::tools::ctx_patch::record_outcome(params, &last_mode, &output, &effect);
766
767 if !matches!(effect, crate::tools::ctx_edit::CacheEffect::None) {
768 crate::tools::ctx_read::dedup_hook::on_write(&path);
769 match crate::server::bounded_lock::write(cache_lock, "ctx_patch cache write") {
770 Some(mut cache) => {
771 crate::tools::ctx_edit::apply_cache_effect(&mut cache, &path, effect);
772 }
773 None => {
774 tracing::warn!(
775 "ctx_patch: cache write-lock timeout applying effect for {path}"
776 );
777 }
778 }
779 }
780
781 if !written {
782 return Err(tool_execution_error(output));
783 }
784
785 if let Some(session_lock) = ctx.session.as_ref() {
786 if let Some(mut session) =
787 crate::server::bounded_lock::write(session_lock, "ctx_patch session write")
788 {
789 session.mark_modified(&path);
790 }
791 }
792
793 Ok(output)
794 }
795}
796
797fn delegate_replace_symbol(
802 args: &Map<String, Value>,
803 ctx: &ToolContext,
804) -> Result<ToolOutput, ErrorData> {
805 let refactor_args = crate::tools::ctx_patch::build_refactor_args(args)
806 .map_err(|e| ErrorData::invalid_params(e, None))?;
807
808 if get_bool(args, "dry_run").unwrap_or(false) {
809 let name = get_str(args, "name").unwrap_or_default();
810 let path = get_str(args, "path").unwrap_or_default();
811 return Ok(ToolOutput::simple(format!(
812 "DRY RUN: replace_symbol would rewrite symbol {name:?} in {path}"
813 )));
814 }
815
816 let has_path = args.get("path").and_then(Value::as_str).is_some();
820 let abs_path = if has_path {
821 require_resolved_path(ctx, args, "path")?
822 } else {
823 String::new()
824 };
825
826 let args_value = Value::Object(refactor_args);
827 let result = crate::tools::ctx_refactor::handle(&args_value, &ctx.project_root, &abs_path);
828 let changed = !result.starts_with("ERROR") && !result.starts_with("CONFLICT");
829 if !changed {
830 return Err(tool_execution_error(result));
831 }
832
833 Ok(ToolOutput {
834 text: result,
835 original_tokens: 0,
836 saved_tokens: 0,
837 mode: Some("replace_symbol".to_string()),
838 path: get_str(args, "path"),
839 changed,
840 shell_outcome: None,
841 content_blocks: None,
842 })
843}
844
845fn resolve_find_replace(args: &Map<String, Value>) -> Result<(String, String), String> {
857 let find = aliased(args, "find", &["old_string", "old_text"])?
858 .filter(|s| !s.is_empty())
859 .ok_or("replace_all requires non-empty 'find' (old_string also accepted)")?;
860 let replace = aliased(args, "replace", &["new_string", "new_text"])?.ok_or(
861 "replace_all requires 'replace' (the replacement text, new_string also accepted); \
862 pass replace=\"\" explicitly to delete every match",
863 )?;
864 Ok((find, replace))
865}
866
867fn aliased(
870 args: &Map<String, Value>,
871 key: &str,
872 aliases: &[&str],
873) -> Result<Option<String>, String> {
874 let mut found: Option<(&str, &str)> = None;
875 for name in std::iter::once(key).chain(aliases.iter().copied()) {
876 let Some(value) = args.get(name).and_then(Value::as_str) else {
877 continue;
878 };
879 match found {
880 Some((first, seen)) if seen != value => {
881 return Err(format!(
882 "'{first}' and '{name}' name the same field with different values — pass only one"
883 ));
884 }
885 Some(_) => {}
886 None => found = Some((name, value)),
887 }
888 }
889 Ok(found.map(|(_, value)| value.to_string()))
890}
891
892fn replace_all_plan(
909 path: &str,
910 root: &str,
911 find: &str,
912) -> Result<(crate::tools::edit_io::FilePreimage, usize), String> {
913 use crate::tools::admitted_sources::SourceRead;
914 let cap = lean_ctx::core::limits::max_read_bytes();
915 let original = crate::tools::edit_io::read_preimage(std::path::Path::new(path), cap, false)?;
916 let mut remaining = cap;
917 let admitted =
918 match crate::tools::admitted_sources::read(path, root, "ctx_patch", &mut remaining) {
919 SourceRead::Admitted(read) => read.content,
920 SourceRead::Withheld(reason) | SourceRead::Unavailable(reason) => {
921 return Err(format!("cannot read {path}: {reason}"));
922 }
923 };
924 let count = admitted.matches(find).count();
925 if count != original.text.matches(find).count() {
926 return Err(format!(
927 "replace_all refused for {path}: the pattern overlaps content the context gateway \
928 masks; nothing was changed"
929 ));
930 }
931 Ok((original, count))
932}
933
934fn replace_all_write(
938 path: &str,
939 pre: &crate::tools::edit_io::FilePreimage,
940 new_content: &str,
941) -> Result<(), String> {
942 let path = std::path::Path::new(path);
943 crate::tools::claims_gate::before_write(path, Some(&pre.text), new_content)?;
944 crate::tools::edit_io::ensure_preimage_still_matches(
945 path,
946 &pre.fp,
947 lean_ctx::core::limits::max_read_bytes(),
948 )?;
949 crate::tools::edit_io::write_atomic_bytes_with_permissions(
950 path,
951 new_content.as_bytes(),
952 Some(&pre.permissions),
953 )
954}
955
956fn handle_replace_all(
958 args: &Map<String, Value>,
959 ctx: &ToolContext,
960) -> Result<ToolOutput, ErrorData> {
961 let path = require_resolved_path(ctx, args, "path")?;
962 let (find, replace) =
963 resolve_find_replace(args).map_err(|e| ErrorData::invalid_params(e, None))?;
964 let dry_run = get_bool(args, "dry_run").unwrap_or(false);
965
966 let file_lock = lean_ctx_ext::core::path_locks::per_file_lock(&path);
969 let _guard = file_lock
970 .lock()
971 .map_err(|_| ErrorData::internal_error(format!("lock contention for {path}"), None))?;
972
973 let root = crate::tools::admitted_sources::root_in_context(&path, ctx);
974 let (pre, count) = replace_all_plan(&path, &root, &find).map_err(tool_execution_error)?;
975 if count == 0 {
976 return Ok(ToolOutput::simple(format!(
977 "No matches for {find:?} in {path}"
978 )));
979 }
980
981 if dry_run {
982 return Ok(ToolOutput::simple(format!(
983 "DRY RUN: {count} occurrence(s) of {find:?} would be replaced with {replace:?} in {path}"
984 )));
985 }
986
987 let new_content = pre.text.replace(find.as_str(), &replace);
988 replace_all_write(&path, &pre, &new_content).map_err(tool_execution_error)?;
989 super::ctx_edit::observe_mcp_edit(ctx, &path, "ctx_patch", &pre.bytes, new_content.as_bytes());
990
991 crate::tools::ctx_read::dedup_hook::on_write(&path);
992 if let Some(cache) = ctx.cache.as_ref() {
993 if let Some(mut c) =
994 crate::server::bounded_lock::write(cache, "ctx_patch replace_all cache invalidate")
995 {
996 c.invalidate(&path);
997 }
998 }
999 if let Some(session_lock) = ctx.session.as_ref() {
1000 if let Some(mut session) =
1001 crate::server::bounded_lock::write(session_lock, "ctx_patch replace_all session")
1002 {
1003 session.mark_modified(&path);
1004 }
1005 }
1006
1007 Ok(ToolOutput::simple(format!(
1008 "Replaced {count} occurrence(s) of {find:?} with {replace:?} in {path}"
1009 )))
1010}
1011
1012#[cfg(test)]
1013mod replace_all_tests {
1014 use super::*;
1015 use serde_json::json;
1016
1017 fn obj(v: Value) -> Map<String, Value> {
1018 match v {
1019 Value::Object(m) => m,
1020 _ => panic!("expected object"),
1021 }
1022 }
1023
1024 #[test]
1025 fn resolves_find_and_replace() {
1026 let (f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": "b"}))).unwrap();
1027 assert_eq!((f.as_str(), r.as_str()), ("a", "b"));
1028 }
1029
1030 #[test]
1031 fn explicit_empty_replace_is_a_deletion() {
1032 let (_f, r) = resolve_find_replace(&obj(json!({"find": "a", "replace": ""}))).unwrap();
1033 assert_eq!(r, "");
1034 }
1035
1036 #[test]
1037 fn missing_replace_is_rejected_not_silent_delete() {
1038 let err = resolve_find_replace(&obj(json!({"find": "a"}))).unwrap_err();
1039 assert!(err.contains("requires 'replace'"), "got: {err}");
1040 }
1041
1042 #[test]
1043 fn other_ops_names_are_aliases() {
1044 for (old, new) in [("old_string", "new_string"), ("old_text", "new_text")] {
1045 let (f, r) = resolve_find_replace(&obj(json!({old: "a", new: "b"}))).unwrap();
1046 assert_eq!((f.as_str(), r.as_str()), ("a", "b"), "{old}/{new}");
1047 }
1048 }
1049
1050 #[test]
1051 fn alias_never_turns_a_missing_replacement_into_a_delete() {
1052 let err = resolve_find_replace(&obj(json!({"old_string": "a"}))).unwrap_err();
1053 assert!(err.contains("requires 'replace'"), "got: {err}");
1054 }
1055
1056 #[test]
1057 fn conflicting_spellings_are_rejected() {
1058 let err = resolve_find_replace(&obj(
1059 json!({"find": "a", "old_string": "x", "replace": "b"}),
1060 ))
1061 .unwrap_err();
1062 assert!(
1063 err.contains("find") && err.contains("old_string"),
1064 "got: {err}"
1065 );
1066 let same = resolve_find_replace(&obj(
1067 json!({"find": "a", "old_string": "a", "replace": "b"}),
1068 ));
1069 assert!(same.is_ok(), "identical spellings agree");
1070 }
1071
1072 #[test]
1073 fn empty_find_is_rejected() {
1074 let err = resolve_find_replace(&obj(json!({"find": "", "replace": "b"}))).unwrap_err();
1075 assert!(err.contains("find"), "got: {err}");
1076 }
1077
1078 #[test]
1084 fn the_reported_count_comes_from_the_admitted_text_and_the_original_is_what_is_written() {
1085 use lean_ctx::core::policy::runtime::TestPolicyOverride;
1086 let _data = lean_ctx::core::data_dir::isolated_data_dir();
1087 let policy = lean_ctx::core::policy::load(
1088 "name = \"ctx-patch-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
1089 [redaction]\ncustomer = \"CUS-[0-9]{4}\"\n\
1090 [filters]\nclassification = \"block\"\nblocked_labels = [\"CONFIDENTIAL\"]\n",
1091 )
1092 .unwrap();
1093 let project = tempfile::tempdir().unwrap();
1094 let root = project.path().to_string_lossy().into_owned();
1095 let file = |name: &str, content: &str| {
1096 let path = project.path().join(name);
1097 std::fs::write(&path, content).unwrap();
1098 path.to_string_lossy().into_owned()
1099 };
1100 let original = "let owner = \"CUS-1234\";\nlet mode = old_mode();\nold_mode();\n";
1101 let orders = file("orders.rs", original);
1102 let plan = file("plan.rs", "CONFIDENTIAL\nold_mode();\n");
1103 let planned = |path: &str, find: &str| {
1104 replace_all_plan(path, &root, find).map(|(pre, count)| (pre.text, count))
1105 };
1106 {
1107 let _community = TestPolicyOverride::set(None);
1109 assert_eq!(planned(&orders, "old_mode"), Ok((original.to_string(), 2)));
1110 }
1111 let _policy = TestPolicyOverride::set(Some(policy));
1112 assert_eq!(planned(&orders, "old_mode"), Ok((original.to_string(), 2)));
1114 let refused = replace_all_plan(&orders, &root, "CUS-1234").unwrap_err();
1116 assert!(refused.contains("refused"), "{refused}");
1117 assert!(!refused.contains("1 occurrence"), "{refused}");
1118 let withheld = replace_all_plan(&plan, &root, "old_mode").unwrap_err();
1120 assert!(withheld.contains("withheld"), "{withheld}");
1121 assert!(replace_all_plan(&orders, "", "old_mode").is_err());
1123 }
1124
1125 #[test]
1129 fn replace_all_uses_the_edit_boundary() {
1130 let _data = lean_ctx::core::data_dir::isolated_data_dir();
1131 let project = tempfile::tempdir().unwrap();
1132 let root = project.path().to_string_lossy().into_owned();
1133 let target = project.path().join("a.rs");
1134 std::fs::write(&target, "old();\nold();\n").unwrap();
1135 let target_str = target.to_string_lossy().into_owned();
1136
1137 #[cfg(unix)]
1138 {
1139 let link = project.path().join("link.rs");
1140 std::os::unix::fs::symlink(&target, &link).unwrap();
1141 let err = replace_all_plan(&link.to_string_lossy(), &root, "old").unwrap_err();
1142 assert!(err.contains("symlink"), "{err}");
1143 }
1144
1145 let (pre, count) = replace_all_plan(&target_str, &root, "old").unwrap();
1146 assert_eq!(count, 2);
1147 std::fs::write(&target, "old();\nnewer();\n").unwrap();
1149 let new_content = pre.text.replace("old", "new");
1150 let err = replace_all_write(&target_str, &pre, &new_content).unwrap_err();
1151 assert!(err.contains("TOCTOU"), "{err}");
1152 assert_eq!(
1153 std::fs::read_to_string(&target).unwrap(),
1154 "old();\nnewer();\n"
1155 );
1156
1157 let (pre, _) = replace_all_plan(&target_str, &root, "old").unwrap();
1159 let new_content = pre.text.replace("old", "new");
1160 replace_all_write(&target_str, &pre, &new_content).unwrap();
1161 assert_eq!(
1162 std::fs::read_to_string(&target).unwrap(),
1163 "new();\nnewer();\n"
1164 );
1165 }
1166}
1167
1168#[cfg(test)]
1169mod batch_grouping_tests {
1170 use super::*;
1171 use serde_json::json;
1172
1173 #[test]
1176 fn groups_ops_across_files_preserving_order() {
1177 let ops = vec![
1178 json!({"op":"insert_after","path":"a.go","line":1,"hash":"aa","new_text":"x"}),
1179 json!({"op":"insert_after","path":"b.go","line":2,"hash":"bb","new_text":"y"}),
1180 json!({"op":"set_line","path":"a.go","line":3,"hash":"cc","new_text":"z"}),
1181 ];
1182 let g = group_ops_by_path(&ops, None).unwrap();
1183 assert_eq!(g.len(), 2);
1184 assert_eq!(g[0].0, "a.go");
1185 assert_eq!(g[0].1.len(), 2);
1186 assert_eq!(g[1].0, "b.go");
1187 assert_eq!(g[1].1.len(), 1);
1188 }
1189
1190 #[test]
1191 fn ops_without_path_fall_back_to_top_level() {
1192 let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
1193 let g = group_ops_by_path(&ops, Some("top.go")).unwrap();
1194 assert_eq!(g.len(), 1);
1195 assert_eq!(g[0].0, "top.go");
1196 }
1197
1198 #[test]
1199 fn op_without_path_and_no_top_level_is_rejected() {
1200 let ops = vec![json!({"op":"set_line","line":1,"hash":"aa","new_text":"x"})];
1201 let err = group_ops_by_path(&ops, None).unwrap_err();
1202 assert!(err.contains("path"), "got: {err}");
1203 }
1204
1205 #[test]
1206 fn empty_ops_rejected() {
1207 let err = group_ops_by_path(&[], None).unwrap_err();
1208 assert!(err.contains("empty"), "got: {err}");
1209 }
1210
1211 #[test]
1212 fn cross_file_rejects_single_value_preimage_and_backup_options() {
1213 for key in ["expected_blake3", "expected_md5", "backup_path"] {
1214 let args = Map::from_iter([(key.to_string(), json!("one-value"))]);
1215 assert!(validate_cross_file_options(&args, 2).is_err());
1216 assert!(validate_cross_file_options(&args, 1).is_ok());
1217 }
1218 }
1219
1220 #[test]
1221 fn replace_unique_maps_to_a_single_safe_ctx_edit_replacement() {
1222 let args = Map::from_iter([
1223 ("path".into(), json!("a.rs")),
1224 ("op".into(), json!("replace_unique")),
1225 ("old_text".into(), json!("old")),
1226 ("new_text".into(), json!("new")),
1227 ]);
1228 let mapped = build_unique_edit_args(&args).expect("valid mapping");
1229 assert_eq!(mapped.get("old_string"), Some(&json!("old")));
1230 assert_eq!(mapped.get("new_string"), Some(&json!("new")));
1231 assert_eq!(mapped.get("replace_all"), Some(&json!(false)));
1232 assert!(!mapped.contains_key("op"));
1233 assert!(!mapped.contains_key("old_text"));
1234 }
1235
1236 #[test]
1237 fn replace_unique_requires_explicit_old_and_new_text() {
1238 assert!(build_unique_edit_args(&Map::new()).is_err());
1239 let only_old = Map::from_iter([("old_text".into(), json!("old"))]);
1240 assert!(build_unique_edit_args(&only_old).is_err());
1241 }
1242
1243 #[test]
1244 fn dry_run_replace_unique_does_not_apply() {
1245 let args = Map::from_iter([
1246 ("path".into(), json!("a.rs")),
1247 ("op".into(), json!("replace_unique")),
1248 ("old_text".into(), json!("old")),
1249 ("new_text".into(), json!("new")),
1250 ("dry_run".into(), json!(true)),
1251 ]);
1252 let edit_args = build_unique_edit_args(&args).expect("validation passes");
1253 assert!(
1254 edit_args.contains_key("old_string"),
1255 "args mapped correctly"
1256 );
1257 assert!(
1258 args.get("dry_run").and_then(Value::as_bool) == Some(true),
1259 "dry_run flag preserved in original args"
1260 );
1261 }
1262
1263 #[test]
1264 fn text_replacement_without_op_is_inferred_as_replace_unique() {
1265 let top = Map::from_iter([
1266 ("path".into(), json!("a.rs")),
1267 ("old_string".into(), json!("old")),
1268 ("new_string".into(), json!("new")),
1269 ]);
1270 let inferred = infer_replace_unique(&top).expect("op inferred");
1271 assert_eq!(inferred.get("op"), Some(&json!("replace_unique")));
1272
1273 let batch = Map::from_iter([(
1274 "ops".into(),
1275 json!([
1276 {"path": "a.rs", "old_text": "a", "new_text": "b"},
1277 {"op": "set_line", "line": 1, "hash": "aa", "new_text": "x"}
1278 ]),
1279 )]);
1280 let inferred = infer_replace_unique(&batch).expect("op inferred in ops[]");
1281 assert_eq!(inferred["ops"][0]["op"], json!("replace_unique"));
1282 assert_eq!(inferred["ops"][1]["op"], json!("set_line"));
1283
1284 for unchanged in [
1286 json!({"op": "set_line", "old_text": "a", "new_text": "b"}),
1287 json!({"old_text": "", "new_text": "b"}),
1288 json!({"old_text": "a"}),
1289 ] {
1290 assert!(infer_replace_unique(unchanged.as_object().unwrap()).is_none());
1291 }
1292
1293 let encoded = json!({"ops": "[{\"op\":\"replace_unique\",\"path\":\"a.rs\",\"old_text\":\"a\",\"new_text\":\"b\"}]"});
1295 let repaired = infer_replace_unique(encoded.as_object().unwrap()).expect("ops decoded");
1296 assert_eq!(repaired["ops"][0]["old_text"], json!("a"));
1297 let create = json!({"op": "create", "path": "n.py", "new_string": "x = 1\n"});
1298 let repaired = infer_replace_unique(create.as_object().unwrap()).expect("create aliased");
1299 assert_eq!(repaired["new_text"], json!("x = 1\n"));
1300 let find_replace =
1301 json!({"op": "replace_unique", "path": "a.rs", "find": "a", "replace": "b"});
1302 let repaired = infer_replace_unique(find_replace.as_object().unwrap()).expect("aliased");
1303 assert_eq!(
1304 (&repaired["old_text"], &repaired["new_text"]),
1305 (&json!("a"), &json!("b"))
1306 );
1307 let replace_all = json!({"op": "replace_all", "path": "a.rs", "find": "a", "replace": "b"});
1309 assert!(infer_replace_unique(replace_all.as_object().unwrap()).is_none());
1310 }
1311
1312 fn empty_old_text_patch(
1315 root: &std::path::Path,
1316 path: &std::path::Path,
1317 ) -> Result<String, ErrorData> {
1318 let resolved = path.to_string_lossy().into_owned();
1319 let ctx = ToolContext {
1320 project_root: root.to_string_lossy().into_owned(),
1321 resolved_paths: std::collections::HashMap::from([("path".into(), resolved.clone())]),
1322 cache: Some(std::sync::Arc::new(tokio::sync::RwLock::new(
1323 lean_ctx::core::cache::SessionCache::new(),
1324 ))),
1325 ..ToolContext::default()
1326 };
1327 let args = json!({
1328 "op": "replace_unique", "path": resolved, "old_text": "", "new_text": "filled\n"
1329 });
1330 tokio::task::block_in_place(|| CtxPatchTool.handle(args.as_object().unwrap(), &ctx))
1331 .map(|out| out.text)
1332 }
1333
1334 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1335 async fn replace_unique_with_empty_old_text_fills_an_empty_file() {
1336 let _iso = lean_ctx::core::data_dir::isolated_data_dir();
1338 let dir = tempfile::tempdir().unwrap();
1339 let file = dir.path().join("empty.txt");
1340 std::fs::write(&file, "").unwrap();
1341 let text = empty_old_text_patch(dir.path(), &file).expect("empty file is filled");
1342 assert!(text.contains("created empty.txt"), "{text}");
1343 assert_eq!(std::fs::read_to_string(&file).unwrap(), "filled\n");
1344 }
1345
1346 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1347 async fn replace_unique_with_empty_old_text_refuses_other_targets() {
1348 let _iso = lean_ctx::core::data_dir::isolated_data_dir();
1349 let dir = tempfile::tempdir().unwrap();
1350
1351 let full = dir.path().join("full.txt");
1352 std::fs::write(&full, "keep\n").unwrap();
1353 let err = empty_old_text_patch(dir.path(), &full).unwrap_err();
1354 assert!(err.message.contains("anchored"), "{}", err.message);
1355 assert_eq!(std::fs::read_to_string(&full).unwrap(), "keep\n");
1356
1357 let missing = dir.path().join("missing.txt");
1358 let err = empty_old_text_patch(dir.path(), &missing).unwrap_err();
1359 assert!(err.message.contains("op=create"), "{}", err.message);
1360 assert!(!missing.exists(), "replace_unique must not create files");
1361
1362 #[cfg(unix)]
1363 {
1364 let target = dir.path().join("target.txt");
1365 std::fs::write(&target, "").unwrap();
1366 let link = dir.path().join("link.txt");
1367 std::os::unix::fs::symlink(&target, &link).unwrap();
1368 let err = empty_old_text_patch(dir.path(), &link).unwrap_err();
1369 assert!(err.message.contains("not one"), "{}", err.message);
1370 assert_eq!(std::fs::read_to_string(&target).unwrap(), "");
1371 }
1372 }
1373
1374 #[test]
1375 fn replace_unique_never_forwards_a_whole_file_create() {
1376 let args = Map::from_iter([
1377 ("old_text".into(), json!("old")),
1378 ("new_text".into(), json!("new")),
1379 ("create".into(), json!(true)),
1380 ]);
1381 let mapped = build_unique_edit_args(&args).expect("valid mapping");
1382 assert!(!mapped.contains_key("create"));
1383 }
1384}