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