Skip to main content

lean_ctx/tools/ctx_patch/
mod.rs

1//! `ctx_patch` — hash-anchored editing (epic #1008).
2//!
3//! "Edit by reference, not by reproduction": the model edits lines by their
4//! `(line, hash)` anchor (from `ctx_read(mode="anchored")`) instead of quoting
5//! the old text byte-for-byte. Each anchor is verified against the *current*
6//! file; on drift the edit is rejected with fresh anchors — except a
7//! single-line anchor (`set_line`/`insert_after`) whose content moved intact
8//! to exactly one other line (e.g. an earlier, separate edit shifted it):
9//! that's resolved automatically rather than failing (#812). Multiple edits
10//! in one call are **batch-atomic** — all validated against the same
11//! preimage and applied all-or-nothing, bottom-up.
12//!
13//! Reuses the exact `ctx_edit` I/O boundary (`crate::tools::edit_io`):
14//! TOCTOU preimage guard, permission-preserving atomic write, read-only-roots
15//! deny, symlink rejection. `ctx_edit` (str_replace) stays as the fallback.
16
17mod anchors;
18mod apply;
19mod metering;
20mod output;
21mod symbol;
22#[cfg(test)]
23mod tests;
24
25pub use anchors::AnchorOp;
26pub(crate) use symbol::{build_refactor_args, is_replace_symbol};
27
28use std::path::{Path, PathBuf};
29
30use crate::core::cache::SessionCache;
31use crate::core::tokens::count_tokens;
32use crate::tools::ctx_edit::{CacheEffect, apply_cache_effect, build_diff_evidence};
33use crate::tools::edit_io::{
34    default_backup_path, ensure_preimage_still_matches, read_preimage,
35    write_atomic_bytes_with_permissions,
36};
37
38/// Parameters for an anchored patch: the target file and one or more anchored
39/// edit ops, plus optional guards/evidence (mirrors `EditParams` where it makes
40/// sense so the registered wrapper stays uniform).
41pub struct PatchParams {
42    pub path: String,
43    pub ops: Vec<AnchorOp>,
44    /// Optional whole-file preimage guard (BLAKE3 hex, as printed by ctx_edit's
45    /// `postimage:` line). When set, the edit fails if the file's hash differs.
46    ///
47    /// Named for the algorithm it actually uses (#1592); the wire parameter
48    /// `expected_md5` stays accepted as an alias for existing callers.
49    pub expected_blake3: Option<String>,
50    pub backup: bool,
51    pub backup_path: Option<String>,
52    pub evidence: bool,
53    pub diff_max_lines: usize,
54    pub allow_lossy_utf8: bool,
55    /// Post-edit tree-sitter gate (#1008): reject a write that turns a cleanly
56    /// parsing file into a broken one. Default `true`; set `false` to override
57    /// (e.g. intentionally writing an incomplete snippet).
58    pub validate_syntax: bool,
59}
60
61/// Parse the raw tool arguments into [`AnchorOp`]s (single op or `ops[]`).
62pub fn parse_ops(
63    args: &serde_json::Map<String, serde_json::Value>,
64) -> Result<Vec<AnchorOp>, String> {
65    anchors::parse_ops(args)
66}
67
68/// Apply an anchored patch and the resulting cache effect in one shot (tests and
69/// in-process callers that hold the cache exclusively).
70pub fn handle(cache: &mut SessionCache, params: &PatchParams) -> String {
71    let last_mode = cache
72        .get(&params.path)
73        .map(|e| e.last_mode.clone())
74        .unwrap_or_default();
75    let (text, effect) = run_io(params, &last_mode);
76    record_outcome(params, &last_mode, &text, &effect);
77    apply_cache_effect(cache, &params.path, effect);
78    text
79}
80
81/// Quality loop (#494/#1008): a clean anchored edit is a success signal for the
82/// read mode that produced the anchors; a stale-anchor `CONFLICT` is a failure
83/// signal (the view the model edited against had drifted) that arms a one-shot
84/// escalation of the next auto read to `anchored` — fresh line anchors to retry
85/// by reference. Structural errors say nothing about the read mode and are
86/// skipped.
87pub fn record_outcome(params: &PatchParams, last_mode: &str, text: &str, effect: &CacheEffect) {
88    let success = matches!(effect, CacheEffect::Invalidate);
89    let conflict = matches!(effect, CacheEffect::None) && text.starts_with("CONFLICT:");
90    if success || conflict {
91        crate::core::edit_quality::record_anchored_edit_outcome(&params.path, last_mode, success);
92    }
93}
94
95/// Perform the anchored patch on disk **without** touching the cache; returns
96/// the [`CacheEffect`] for the caller to apply. `last_mode` is currently only
97/// used by [`record_outcome`]; pass `""` when unknown.
98pub fn run_io(params: &PatchParams, _last_mode: &str) -> (String, CacheEffect) {
99    let file_path = &params.path;
100    let path = Path::new(file_path);
101    let cap = crate::core::limits::max_read_bytes();
102
103    // `create` short-circuits the anchored pipeline: no preimage exists to
104    // anchor against, so it must be the only op and the file must be new.
105    if let Some(content) = single_create_op(&params.ops) {
106        return match content {
107            Ok(text) => handle_create(params, path, text),
108            Err(e) => (e, CacheEffect::None),
109        };
110    }
111
112    let pre = match read_preimage(path, cap, params.allow_lossy_utf8) {
113        Ok(p) => p,
114        Err(e) => {
115            if !path.exists() {
116                let hint = crate::tools::edit_recovery::moved_or_deleted_hint(path);
117                return (format!("{e}{hint}"), CacheEffect::None);
118            }
119            return (e, CacheEffect::None);
120        }
121    };
122
123    if let Some(expected) = params.expected_blake3.as_deref()
124        && expected != pre.fp.blake3
125    {
126        return (
127            format!(
128                "ERROR: preimage mismatch for {file_path}: expected_blake3={expected}, actual_blake3={}",
129                pre.fp.blake3
130            ),
131            CacheEffect::None,
132        );
133    }
134
135    if params.ops.is_empty() {
136        return (
137            "ERROR: no edits provided (pass an op or ops:[…])".to_string(),
138            CacheEffect::None,
139        );
140    }
141
142    // BOM parity with `ctx_read` (GH #683 follow-up): the read side strips a
143    // UTF-8 BOM before hashing line 1, so anchors must be validated against
144    // the BOM-less body — otherwise every line-1 edit of a BOM file conflicts
145    // forever. The BOM itself is preserved on write (prepended below); it is
146    // an encoding artifact of the file, not of the edit.
147    let (bom, body) = match pre.text.strip_prefix('\u{feff}') {
148        Some(rest) => ("\u{feff}", rest),
149        None => ("", pre.text.as_str()),
150    };
151    let (lines, sep, trailing) = apply::split_lines(body);
152
153    let edits = match apply::resolve_ops(&lines, &params.ops) {
154        Ok(e) => e,
155        Err(apply::ResolveError::Conflict(misses)) => {
156            // Edit-efficiency channel (#1008): a stale-anchor CONFLICT is one
157            // extra self-heal round-trip — count it, never print it (#498).
158            crate::core::edit_metering::record_anchored_conflict();
159            return (
160                output::render_conflict(file_path, &lines, &misses),
161                CacheEffect::None,
162            );
163        }
164        Err(apply::ResolveError::Invalid(msg)) => {
165            return (format!("ERROR: {msg}"), CacheEffect::None);
166        }
167    };
168
169    // Preimage math for the edit-efficiency channel — must run before the
170    // splice consumes the old span text.
171    let avoided_tokens = metering::avoided_output_tokens(&lines, &params.ops);
172
173    let n_edits = edits.len();
174    let lines_added = edits.iter().fold(0u64, |total, edit| {
175        total.saturating_add(u64::try_from(edit.new_lines.len()).unwrap_or(u64::MAX))
176    });
177    let lines_removed = edits.iter().fold(0u64, |total, edit| {
178        total.saturating_add(u64::try_from(edit.remove_count).unwrap_or(u64::MAX))
179    });
180    let lines_before = lines.len();
181    let new_lines = apply::apply_edits(lines.clone(), edits);
182    let new_content = format!("{bom}{}", apply::join_lines(&new_lines, sep, trailing));
183
184    if new_content == pre.text {
185        return (
186            "ERROR: edits produced no change to the file".to_string(),
187            CacheEffect::None,
188        );
189    }
190
191    let ext = Path::new(file_path)
192        .extension()
193        .and_then(|e| e.to_str())
194        .unwrap_or("");
195
196    // Post-edit syntax gate (#1008): block a clean → broken regression before any
197    // write. Pure (no I/O), so it runs before the TOCTOU re-read.
198    if params.validate_syntax
199        && let Some(reason) = crate::core::syntax_validate::gate_edit(ext, &pre.text, &new_content)
200    {
201        return (reason, CacheEffect::None);
202    }
203
204    // Code-health gate: warn on (or block) cognitive-complexity drift before write.
205    let health_notice = match crate::core::code_health::gate::evaluate(&pre.text, &new_content, ext)
206    {
207        crate::core::code_health::gate::GateOutcome::Block(reason) => {
208            return (
209                format!("ERROR: code-health gate: {reason}"),
210                CacheEffect::None,
211            );
212        }
213        crate::core::code_health::gate::GateOutcome::Allow(notice) => notice,
214    };
215
216    // TOCTOU guard: confirm the file did not change between read and write.
217    // #960: a point-in-time check, not a held lock — see
218    // ensure_preimage_still_matches' doc for the residual window between
219    // this check and the write below.
220    if let Err(e) = ensure_preimage_still_matches(path, &pre.fp, cap) {
221        return (e, CacheEffect::None);
222    }
223
224    let backup_path = match make_backup(params, path, &pre.bytes, &pre.permissions) {
225        Ok(bp) => bp,
226        Err(e) => return (e, CacheEffect::None),
227    };
228
229    if let Err(e) =
230        write_atomic_bytes_with_permissions(path, new_content.as_bytes(), Some(&pre.permissions))
231    {
232        return (e, CacheEffect::None);
233    }
234
235    crate::core::edit_metering::record_loc_change(Some(file_path), lines_added, lines_removed);
236
237    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
238        bt.record_edit(file_path);
239    }
240
241    // Edit-efficiency channel (#1008): the span the model did NOT re-emit.
242    crate::core::edit_metering::record_anchored_success(n_edits as u64, avoided_tokens);
243
244    let mut out = render_success(
245        params,
246        &pre.text,
247        &new_content,
248        pre.fp.size,
249        pre.fp.mtime_ms,
250        &pre.fp.blake3,
251        lines_before,
252        new_lines.len(),
253        n_edits,
254        backup_path,
255    );
256    if let Some(notice) = health_notice {
257        out.push_str("\n\n");
258        out.push_str(&notice);
259    }
260    (out, CacheEffect::Invalidate)
261}
262
263/// If the ops contain a `create`, return its content — or an error when it is
264/// mixed with anchored ops (a batch validates against one *existing* preimage,
265/// which a new file by definition does not have).
266fn single_create_op(ops: &[AnchorOp]) -> Option<Result<&str, String>> {
267    let create = ops.iter().find_map(|op| match op {
268        AnchorOp::Create { new_text } => Some(new_text.as_str()),
269        _ => None,
270    })?;
271    if ops.len() > 1 {
272        return Some(Err(
273            "ERROR: create cannot be batched with anchored ops — a new file has no \
274             preimage to anchor against; send create as a single op"
275                .to_string(),
276        ));
277    }
278    Some(Ok(create))
279}
280
281/// `op=create`: write a NEW file (strict — an existing file is an error, unlike
282/// `ctx_edit create=true` which overwrites). Reuses the PathJail +
283/// atomic-write boundary of the anchored path.
284fn handle_create(params: &PatchParams, path: &Path, content: &str) -> (String, CacheEffect) {
285    if path.exists() {
286        return (
287            format!(
288                "ERROR: {} already exists — create is for new files only. \
289                 Use anchored ops (ctx_read mode=\"anchored\" → set_line/replace_lines) to modify it.",
290                params.path
291            ),
292            CacheEffect::None,
293        );
294    }
295
296    // Deny before create_dir_all can materialise a directory inside a
297    // read-only root (mirrors ctx_edit's create guard, #475).
298    if let Err(e) = crate::core::pathjail::enforce_writable(path) {
299        return (format!("ERROR: {e}"), CacheEffect::None);
300    }
301
302    if let Some(parent) = path.parent()
303        && !parent.exists()
304        && let Err(e) = std::fs::create_dir_all(parent)
305    {
306        return (
307            format!("ERROR: cannot create directory {}: {e}", parent.display()),
308            CacheEffect::None,
309        );
310    }
311
312    if let Err(e) = write_atomic_bytes_with_permissions(path, content.as_bytes(), None) {
313        return (e, CacheEffect::None);
314    }
315
316    let lines_added = u64::try_from(content.lines().count()).unwrap_or(u64::MAX);
317    crate::core::edit_metering::record_loc_change(Some(&params.path), lines_added, 0);
318
319    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
320        bt.record_edit(&params.path);
321    }
322
323    let lines = content.lines().count();
324    let tokens = count_tokens(content);
325    let short = output::short_name(&params.path);
326    let post_md5 = crate::core::hasher::hash_hex(content.as_bytes());
327    let mut out = format!(
328        "✓ created {short}: {lines} lines, {tokens} tok\npostimage: bytes={}, md5={post_md5}",
329        content.len()
330    );
331    if params.evidence {
332        let diff = build_diff_evidence("", content, &short, params.diff_max_lines);
333        out.push_str("\n\nevidence (diff, redacted, bounded):\n```diff\n");
334        out.push_str(&diff);
335        out.push_str("\n```");
336    }
337    (out, CacheEffect::Invalidate)
338}
339
340/// Write a pre-edit backup when requested; returns the backup path (if any).
341fn make_backup(
342    params: &PatchParams,
343    path: &Path,
344    bytes: &[u8],
345    permissions: &std::fs::Permissions,
346) -> Result<Option<String>, String> {
347    if !params.backup {
348        return Ok(None);
349    }
350    let bp = params
351        .backup_path
352        .as_deref()
353        .map(PathBuf::from)
354        .or_else(|| default_backup_path(path))
355        .ok_or_else(|| format!("ERROR: cannot compute backup path for {}", path.display()))?;
356    write_atomic_bytes_with_permissions(&bp, bytes, Some(permissions))
357        .map_err(|e| format!("ERROR: cannot create backup {}: {e}", bp.display()))?;
358    Ok(Some(bp.to_string_lossy().to_string()))
359}
360
361#[allow(clippy::too_many_arguments)]
362fn render_success(
363    params: &PatchParams,
364    old_content: &str,
365    new_content: &str,
366    pre_size: u64,
367    pre_mtime_ms: u64,
368    pre_md5: &str,
369    lines_before: usize,
370    lines_after: usize,
371    n_edits: usize,
372    backup_path: Option<String>,
373) -> String {
374    let short = output::short_name(&params.path);
375    let line_delta = lines_after as i64 - lines_before as i64;
376    let delta_str = if line_delta >= 0 {
377        format!("+{line_delta}")
378    } else {
379        format!("{line_delta}")
380    };
381    let old_tokens = count_tokens(old_content);
382    let new_tokens = count_tokens(new_content);
383
384    let post_mtime_ms = std::fs::metadata(&params.path)
385        .ok()
386        .and_then(|m| m.modified().ok())
387        .map_or(0, crate::tools::edit_io::system_time_to_millis);
388    let post_md5 = crate::core::hasher::hash_hex(new_content.as_bytes());
389
390    let edit_word = if n_edits == 1 { "edit" } else { "edits" };
391    let mut out = format!(
392        "✓ {short}: {n_edits} anchored {edit_word}, {delta_str} lines ({old_tokens}→{new_tokens} tok)\n\
393preimage: bytes={pre_size}, mtime_ms={pre_mtime_ms}, md5={pre_md5}\n\
394postimage: bytes={}, mtime_ms={post_mtime_ms}, md5={post_md5}",
395        new_content.len()
396    );
397    if let Some(bp) = backup_path {
398        out.push_str(&format!("\nbackup: {bp}"));
399    }
400    // A single op needs no ledger: the header above already names the one edit,
401    // and this is the overwhelmingly common receipt — spending tokens to repeat
402    // it there would work against the tool's own purpose.
403    if params.ops.len() > 1 {
404        out.push('\n');
405        out.push_str(&render_op_ledger(&params.ops));
406    }
407    if params.evidence {
408        let diff = build_diff_evidence(old_content, new_content, &short, params.diff_max_lines);
409        out.push_str("\n\nevidence (diff, redacted, bounded):\n```diff\n");
410        out.push_str(&diff);
411        out.push_str("\n```");
412        let balance = brace_balance(new_content);
413        if balance == 0 {
414            out.push_str("\nbrace-balance: ok (matched)");
415        } else {
416            out.push_str(&format!(
417                "\n⚠ brace-balance: {} unmatched '{{' — verify file integrity",
418                balance.abs()
419            ));
420        }
421    }
422    out
423}
424
425/// Per-op ledger for a batch receipt (#1767): a count line plus one line per
426/// op, in the order the caller sent them.
427///
428/// The receipt used to state only a total — `10 anchored edits` — so a caller
429/// who needed to know *which* ops landed where had to read the evidence diff.
430/// That diff is the bounded, droppable part of the receipt and the first thing
431/// a turn-budget truncation removes (the default budget is 4096 tokens and a
432/// ten-op diff overruns it), which left the caller running `grep` against the
433/// file to find out what had happened. The ledger costs a few tokens per op,
434/// sits ahead of the diff, and therefore survives any cut that keeps the
435/// header at all.
436///
437/// `applied` is always `n/n`: a batch is atomic, so a receipt exists only when
438/// every op landed. Stating it is the point — the reader should not have to
439/// infer completeness from the absence of an error.
440fn render_op_ledger(ops: &[AnchorOp]) -> String {
441    let mut out = format!("ops: {n}/{n} applied", n = ops.len());
442    for (index, op) in ops.iter().enumerate() {
443        let (kind, span, produced) = match op {
444            AnchorOp::SetLine { line, new_text, .. } => {
445                ("set_line", line.to_string(), produced_lines(new_text))
446            }
447            AnchorOp::ReplaceLines {
448                start_line,
449                end_line,
450                new_text,
451                ..
452            } => (
453                "replace_lines",
454                format!("{start_line}-{end_line}"),
455                produced_lines(new_text),
456            ),
457            AnchorOp::InsertAfter { line, new_text, .. } => {
458                ("insert_after", line.to_string(), produced_lines(new_text))
459            }
460            AnchorOp::Delete {
461                start_line,
462                end_line,
463                ..
464            } => ("delete", format!("{start_line}-{end_line}"), 0),
465            AnchorOp::Create { new_text } => ("create", "-".to_string(), produced_lines(new_text)),
466        };
467        let line_word = if produced == 1 { "line" } else { "lines" };
468        out.push_str(&format!(
469            "\n  {}. {kind} {span} → {produced} {line_word}",
470            index + 1
471        ));
472    }
473    out
474}
475
476/// Lines a `new_text` payload contributes. Empty text deletes (the readseek
477/// convention the op variants document), which is zero lines — not one.
478fn produced_lines(new_text: &str) -> usize {
479    if new_text.is_empty() {
480        0
481    } else {
482        new_text.lines().count()
483    }
484}
485
486/// Counts unmatched `{` vs `}` in the full post-edit content. Returns the
487/// difference: positive = excess `{`, negative = excess `}`, 0 = balanced.
488fn brace_balance(content: &str) -> i64 {
489    content.chars().fold(0i64, |acc, c| match c {
490        '{' => acc + 1,
491        '}' => acc - 1,
492        _ => acc,
493    })
494}