Skip to main content

lean_ctx/tools/registered/
ctx_edit.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4use similar::{ChangeTag, TextDiff};
5use std::path::Path;
6
7use crate::server::tool_trait::{
8    McpTool, ToolContext, ToolOutput, get_bool, get_int, get_str, require_resolved_path,
9    tool_execution_error,
10};
11use crate::tool_defs::tool_def;
12
13pub struct CtxEditTool;
14
15impl McpTool for CtxEditTool {
16    fn name(&self) -> &'static str {
17        "ctx_edit"
18    }
19
20    fn tool_def(&self) -> Tool {
21        tool_def(
22            "ctx_edit",
23            "Search-and-replace edit with race-condition guards — for simple text replacement in a single file.\n\
24             For editing code you've read, prefer ctx_patch (hash-anchored): it never makes you reproduce old text byte-for-byte. Read with ctx_read(mode=\"anchored\") first.\n\
25             old_string must be unique unless replace_all=true. create=true writes new files.\n\
26             backup creates .bak. MD5/size/mtime pre-guards prevent race conditions.\n\
27             ANTIPATTERN: Do NOT loop on failures — switch to ctx_patch (anchored), or verify file content and adjust old_string.\n\
28             To replace a whole symbol body use ctx_patch(op=\"replace_symbol\"); find its references with ctx_callgraph.",
29            json!({
30                "type": "object",
31                "properties": {
32                    "path": { "type": "string", "description": "File path to edit" },
33                    "old_string": { "type": "string", "description": "Text to replace (unique unless replace_all=true)" },
34                    "new_string": { "type": "string", "description": "Replacement text" },
35                    "replace_all": { "type": "boolean", "description": "Replace all occurrences (default false)", "default": false },
36                    "create": { "type": "boolean", "description": "Create file", "default": false }
37                },
38                "required": ["path", "new_string"]
39            }),
40        )
41    }
42
43    fn handle(
44        &self,
45        args: &Map<String, Value>,
46        ctx: &ToolContext,
47    ) -> Result<ToolOutput, ErrorData> {
48        let path = require_resolved_path(ctx, args, "path")?;
49
50        let old_string = get_str(args, "old_string").unwrap_or_default();
51        let new_string = get_str(args, "new_string")
52            .ok_or_else(|| ErrorData::invalid_params("new_string is required", None))?;
53        let replace_all = get_bool(args, "replace_all").unwrap_or(false);
54        let create = get_bool(args, "create").unwrap_or(false);
55        // #1592: the guard is a BLAKE3 digest; `expected_md5` was a misnomer and
56        // stays accepted so existing callers keep working.
57        let expected_blake3 =
58            get_str(args, "expected_blake3").or_else(|| get_str(args, "expected_md5"));
59        let expected_size = get_int(args, "expected_size").and_then(|v| u64::try_from(v).ok());
60        let expected_mtime_ms =
61            get_int(args, "expected_mtime_ms").and_then(|v| u64::try_from(v).ok());
62        let backup = get_bool(args, "backup").unwrap_or(false);
63        let backup_path = get_str(args, "backup_path")
64            .map(|p| ctx.resolved_paths.get("backup_path").cloned().unwrap_or(p))
65            .map(|p| crate::core::workspace_authority::confine(&p, &ctx.project_root, true))
66            .transpose()
67            .map_err(|error| ErrorData::invalid_params(error, None))?;
68        let evidence = get_bool(args, "evidence").unwrap_or(true);
69        let diff_max_lines = get_int(args, "diff_max_lines")
70            .and_then(|v| usize::try_from(v.max(0)).ok())
71            .unwrap_or(200);
72        let allow_lossy_utf8 = get_bool(args, "allow_lossy_utf8").unwrap_or(false);
73
74        let edit_params = crate::tools::ctx_edit::EditParams {
75            path: path.clone(),
76            old_string,
77            new_string,
78            replace_all,
79            create,
80            expected_blake3,
81            expected_size,
82            expected_mtime_ms,
83            backup,
84            backup_path,
85            evidence,
86            diff_max_lines,
87            allow_lossy_utf8,
88        };
89
90        {
91            let cache_lock = ctx
92                .cache
93                .as_ref()
94                .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
95
96            // Serialize edits to the SAME file via a cheap per-file lock. This
97            // lets the (slow) disk read/replace/write run WITHOUT holding the
98            // global cache write-lock, so concurrent agents editing different
99            // files never block each other (issue #320). Correctness for same-file
100            // edits is still guaranteed by the TOCTOU preimage guard + atomic
101            // rename inside run_io.
102            let file_lock = crate::core::path_locks::per_file_lock(&path);
103            let _file_guard = {
104                let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
105                loop {
106                    if let Ok(guard) = file_lock.try_lock() {
107                        break guard;
108                    }
109                    if std::time::Instant::now() >= deadline {
110                        return Err(ErrorData::internal_error(
111                            format!(
112                                "per-file edit lock contention for {path} — another edit to the same file is in progress, retry in a moment"
113                            ),
114                            None,
115                        ));
116                    }
117                    std::thread::sleep(std::time::Duration::from_millis(20));
118                }
119            };
120
121            // Brief shared lock: read the recorded read-mode for auto-escalation.
122            // On contention we simply skip escalation rather than blocking I/O.
123            let last_mode =
124                match crate::server::bounded_lock::read(cache_lock, "ctx_edit cache read") {
125                    Some(cache) => cache
126                        .get(&path)
127                        .map(|e| e.last_mode.clone())
128                        .unwrap_or_default(),
129                    None => String::new(),
130                };
131
132            // Heavy disk I/O — no global cache lock held here.
133            let before = std::fs::read(&path).unwrap_or_default();
134            let (output, effect) = crate::tools::ctx_edit::run_io(&edit_params, &last_mode);
135            let written = matches!(effect, crate::tools::ctx_edit::CacheEffect::Invalidate);
136            // The file already holds the requested text: nothing written, and
137            // nothing failed either.
138            let unchanged =
139                !written && output.starts_with(crate::tools::ctx_edit::NO_CHANGE_PREFIX);
140
141            if written {
142                let after = std::fs::read(&path).unwrap_or_default();
143                observe_mcp_edit(ctx, &path, "ctx_edit", &before, &after);
144            }
145
146            // Quality loop (#494): feed success/old_string-miss back into
147            // per-(ext × mode) stats and the one-shot read escalation.
148            crate::tools::ctx_edit::record_outcome(&edit_params, &last_mode, &output, &effect);
149
150            // Apply the deferred cache mutation under a brief exclusive lock.
151            if !matches!(effect, crate::tools::ctx_edit::CacheEffect::None) {
152                crate::tools::ctx_read::dedup_hook::on_write(&path);
153                match crate::server::bounded_lock::write(cache_lock, "ctx_edit cache write") {
154                    Some(mut cache) => {
155                        crate::tools::ctx_edit::apply_cache_effect(&mut cache, &path, effect);
156                    }
157                    None => {
158                        tracing::warn!(
159                            "ctx_edit: cache write-lock timeout applying post-edit effect for {path}"
160                        );
161                    }
162                }
163            }
164
165            // Keep recovery/cache effects, but never report a rejected edit as
166            // successful or mark its file modified. Dispatch turns this into a
167            // filtered MCP tool error through the full output pipeline.
168            if !written && !unchanged {
169                return Err(tool_execution_error(output));
170            }
171
172            if let (true, Some(session_lock)) = (written, ctx.session.as_ref()) {
173                if let Some(mut session) =
174                    crate::server::bounded_lock::write(session_lock, "ctx_edit session write")
175                {
176                    session.mark_modified(&path);
177                }
178            }
179
180            Ok(ToolOutput {
181                text: output,
182                original_tokens: 0,
183                saved_tokens: 0,
184                mode: None,
185                path: Some(path),
186                changed: false,
187                shell_outcome: None,
188                content_blocks: None,
189            })
190        }
191    }
192}
193
194pub(crate) fn observe_mcp_edit(
195    ctx: &ToolContext,
196    path: &str,
197    tool: &str,
198    before: &[u8],
199    after: &[u8],
200) {
201    let config = crate::core::config::Config::load();
202    if !config.provenance.enabled || !config.provenance.capture_mcp_edits || before == after {
203        return;
204    }
205
206    let root = ctx.project_root.as_str();
207    if root.is_empty() {
208        return;
209    }
210
211    let before_text = String::from_utf8_lossy(before);
212    let after_text = String::from_utf8_lossy(after);
213    let (lines_added, lines_removed) = TextDiff::from_lines(&before_text, &after_text)
214        .iter_all_changes()
215        .fold((0_u64, 0_u64), |(added, removed), change| {
216            match change.tag() {
217                ChangeTag::Insert => (added.saturating_add(1), removed),
218                ChangeTag::Delete => (added, removed.saturating_add(1)),
219                ChangeTag::Equal => (added, removed),
220            }
221        });
222    let tracked_path = Path::new(path)
223        .strip_prefix(root)
224        .ok()
225        .filter(|relative| !relative.as_os_str().is_empty())
226        .map(|relative| relative.to_string_lossy().into_owned())
227        .unwrap_or_else(|| path.to_owned());
228    let session_id = ctx
229        .session
230        .as_ref()
231        .and_then(|session| {
232            crate::server::bounded_lock::read(session, "provenance session read")
233                .map(|session| session.id.clone())
234        })
235        .unwrap_or_else(|| "mcp".to_owned());
236    let agent_id = ctx
237        .agent_id
238        .as_ref()
239        .and_then(|agent_id| {
240            crate::server::bounded_lock::read(agent_id, "provenance agent read")
241                .and_then(|agent_id| (*agent_id).clone())
242        })
243        .unwrap_or_else(|| "mcp".to_owned());
244
245    let _ = crate::core::provenance::ProvenanceTracker::new(root).and_then(|tracker| {
246        tracker.observe_edit(
247            tracked_path,
248            tool,
249            sha256_hex(before),
250            sha256_hex(after),
251            lines_added,
252            lines_removed,
253            session_id,
254            agent_id,
255        )
256    });
257}
258
259fn sha256_hex(data: &[u8]) -> String {
260    use sha2::{Digest, Sha256};
261    let hash = Sha256::digest(data);
262    let mut hex = String::with_capacity(64);
263    for b in &hash {
264        use std::fmt::Write;
265        let _ = write!(hex, "{b:02x}");
266    }
267    hex
268}