Skip to main content

lean_ctx/tools/ctx_edit/
implementation.rs

1use std::path::{Path, PathBuf};
2
3use crate::core::cache::SessionCache;
4use crate::core::tokens::count_tokens;
5// Shared TOCTOU-safe read→verify→atomic-write primitives (epic #1008): the same
6// audited boundary `ctx_patch` (anchored editing) builds on, so a fix protects
7// both tools. `verify_expected_preimage` stays here — it is `ctx_edit`-specific
8// (keyed on `EditParams`).
9use crate::tools::edit_io::{
10    FileFingerprint, FilePreimage, default_backup_path, ensure_preimage_still_matches,
11    read_preimage, system_time_to_millis, write_atomic_bytes_with_permissions,
12};
13
14/// Parameters for a file edit operation: path, old/new strings, and flags.
15pub struct EditParams {
16    pub path: String,
17    pub old_string: String,
18    pub new_string: String,
19    pub replace_all: bool,
20    pub create: bool,
21    /// Optional preimage guards. If provided, ctx_edit fails if the current file preimage differs.
22    ///
23    /// The content guard is BLAKE3, named for what it is (#1592); the wire
24    /// parameter `expected_md5` stays accepted as an alias for existing callers.
25    pub expected_blake3: Option<String>,
26    pub expected_size: Option<u64>,
27    pub expected_mtime_ms: Option<u64>,
28    /// Optional backup before writing.
29    pub backup: bool,
30    pub backup_path: Option<String>,
31    /// Emit bounded diff evidence (redacted) by default.
32    pub evidence: bool,
33    pub diff_max_lines: usize,
34    /// Reject invalid UTF-8 by default; allow lossy reads only when explicitly enabled.
35    pub allow_lossy_utf8: bool,
36}
37
38struct ReplaceArgs<'a> {
39    content: &'a str,
40    old_str: &'a str,
41    new_str: &'a str,
42    occurrences: usize,
43    replace_all: bool,
44    old_tokens: usize,
45    new_tokens: usize,
46}
47
48fn verify_expected_preimage(pre: &FilePreimage, params: &EditParams) -> Result<(), String> {
49    if let Some(expected) = params.expected_size
50        && expected != pre.fp.size
51    {
52        return Err(format!(
53            "ERROR: preimage mismatch for {}: expected_size={}, actual_size={}",
54            params.path, expected, pre.fp.size
55        ));
56    }
57    if let Some(expected) = params.expected_mtime_ms
58        && expected != pre.fp.mtime_ms
59    {
60        return Err(format!(
61            "ERROR: preimage mismatch for {}: expected_mtime_ms={}, actual_mtime_ms={}",
62            params.path, expected, pre.fp.mtime_ms
63        ));
64    }
65    if let Some(expected) = params.expected_blake3.as_deref()
66        && expected != pre.fp.blake3
67    {
68        return Err(format!(
69            "ERROR: preimage mismatch for {}: expected_blake3={}, actual_blake3={}",
70            params.path, expected, pre.fp.blake3
71        ));
72    }
73    Ok(())
74}
75
76/// Bounded, secret-redacted unified diff for edit evidence. `pub(crate)` so the
77/// anchored editor (`ctx_patch`) reuses the identical evidence format (#1008).
78pub(crate) fn build_diff_evidence(old: &str, new: &str, label: &str, max_lines: usize) -> String {
79    let diff = similar::TextDiff::from_lines(old, new)
80        .unified_diff()
81        .context_radius(3)
82        .header(label, label)
83        .to_string();
84    // Single source of truth for secret masking — `core::redaction` carries the
85    // GH #430 non-secret-literal guard (type annotations, `undefined`, …) and
86    // does not leak the value of generic long secrets like this duplicate once
87    // did. Keeping a second regex set here only invites drift.
88    let diff = crate::core::redaction::redact_text(&diff);
89
90    let mut out = String::new();
91    for (i, line) in diff.lines().enumerate() {
92        if i >= max_lines {
93            out.push_str(&format!("\n... diff truncated (max_lines={max_lines})"));
94            break;
95        }
96        out.push_str(line);
97        out.push('\n');
98    }
99    out.trim_end_matches('\n').to_string()
100}
101
102/// A cache mutation that an edit needs *after* its disk I/O completes.
103///
104/// Decoupling the cache mutation from the I/O lets the MCP layer perform the
105/// (slow) file read/replace/write while holding only a cheap per-file lock, then
106/// touch the shared cache for a sub-millisecond instant — instead of holding the
107/// global cache write-lock across all disk I/O (the root cause of issue #320).
108pub enum CacheEffect {
109    /// No cache change required (e.g. the edit failed before writing).
110    None,
111    /// The file on disk changed; drop the stale cache entry.
112    Invalidate,
113    /// Auto-escalation re-read full content that should be stored and marked
114    /// as fully delivered.
115    StoreFull(String),
116}
117
118/// Performs a string replacement edit on a file with CRLF/LF and whitespace
119/// tolerance. Thin wrapper that runs the I/O and applies the resulting cache
120/// effect to `cache` in one shot (used by tests and any in-process caller that
121/// already holds the cache exclusively).
122pub fn handle(cache: &mut SessionCache, params: &EditParams) -> String {
123    let last_mode = cache
124        .get(&params.path)
125        .map(|e| e.last_mode.clone())
126        .unwrap_or_default();
127    let (text, effect) = run_io(params, &last_mode);
128    record_outcome(params, &last_mode, &text, &effect);
129    apply_cache_effect(cache, &params.path, effect);
130    text
131}
132
133/// Quality loop (#494): classify the edit result and feed it into
134/// `crate::core::edit_quality`. Only two outcomes carry a compression
135/// signal: a clean replacement (success) and an `old_string` miss
136/// (failure — the body the agent quoted wasn't what's on disk). Parameter
137/// mistakes (empty/identical strings, preimage mismatch, missing file) and
138/// already-applied edits say nothing about the read mode and are skipped.
139pub fn record_outcome(params: &EditParams, last_mode: &str, text: &str, effect: &CacheEffect) {
140    if params.create {
141        return;
142    }
143    let success = matches!(effect, CacheEffect::Invalidate);
144    let not_found_failure = matches!(effect, CacheEffect::StoreFull(_))
145        || (matches!(effect, CacheEffect::None)
146            && text.starts_with("ERROR: old_string not found")
147            && !text.contains("already"));
148    if success {
149        if let Some(project_root) = crate::server::derive_project_root_from_cwd() {
150            crate::core::solution_auto_capture::capture_edit_decisions(
151                &project_root,
152                &params.path,
153                &params.old_string,
154                &params.new_string,
155            );
156        }
157    }
158
159    if success || not_found_failure {
160        crate::core::edit_quality::record_edit_outcome(&params.path, last_mode, success);
161    }
162    // Edit-efficiency channel (#1008): the str_replace baseline — output tokens
163    // actually paid reproducing `old_string`, and blind-retry round-trips.
164    // Separate from the read-gain ledger, never printed in tool output (#498).
165    if success {
166        crate::core::edit_metering::record_str_replace_success(
167            count_tokens(&params.old_string) as u64
168        );
169    } else if not_found_failure {
170        crate::core::edit_metering::record_str_replace_miss();
171    }
172}
173
174/// Applies a deferred [`CacheEffect`] to the session cache.
175pub fn apply_cache_effect(cache: &mut SessionCache, path: &str, effect: CacheEffect) {
176    match effect {
177        CacheEffect::None => {}
178        CacheEffect::Invalidate => {
179            cache.invalidate(path);
180        }
181        CacheEffect::StoreFull(content) => {
182            cache.store(path, &content);
183            cache.mark_full_delivered(path);
184        }
185    }
186}
187
188/// Prefix of the result for an edit whose end state already holds: nothing is
189/// written, and the call is a success, not an error.
190pub const NO_CHANGE_PREFIX: &str = "No change:";
191
192/// Performs the full edit on disk **without** touching the session cache, and
193/// reports back the [`CacheEffect`] the caller should apply afterwards.
194///
195/// `last_mode` is the cache's recorded read mode for the path (used only to
196/// decide whether to auto-escalate on a not-found match); pass `""` when unknown.
197pub fn run_io(params: &EditParams, last_mode: &str) -> (String, CacheEffect) {
198    let file_path = &params.path;
199
200    if params.create {
201        return handle_create(file_path, &params.new_string, params);
202    }
203
204    let cap = crate::core::limits::max_read_bytes();
205    let path = Path::new(file_path);
206    let pre = match read_preimage(path, cap, params.allow_lossy_utf8) {
207        Ok(p) => p,
208        Err(e) => {
209            // File missing? Tell the agent whether it moved or the path is
210            // wrong, instead of a bare "cannot open" (#331 point 3).
211            if !path.exists() {
212                let hint = crate::tools::edit_recovery::moved_or_deleted_hint(path);
213                return (format!("{e}{hint}"), CacheEffect::None);
214            }
215            return (e, CacheEffect::None);
216        }
217    };
218    if let Err(e) = verify_expected_preimage(&pre, params) {
219        return (e, CacheEffect::None);
220    }
221    let content = &pre.text;
222
223    if params.old_string.is_empty() {
224        return (
225            "ERROR: old_string must not be empty (use create=true to create a new file)".into(),
226            CacheEffect::None,
227        );
228    }
229
230    if params.old_string == params.new_string {
231        // The requested end state already holds: report a no-op, not a
232        // failure the agent would retry. Text that is absent stays an error.
233        if content.contains(&params.old_string) {
234            return (
235                format!(
236                    "{NO_CHANGE_PREFIX} {file_path} already contains this text \
237                     (old_string equals new_string)."
238                ),
239                CacheEffect::None,
240            );
241        }
242        return (
243            "ERROR: old_string and new_string are identical — nothing to change.".into(),
244            CacheEffect::None,
245        );
246    }
247
248    let uses_crlf = pre.uses_crlf;
249    let old_str = &params.old_string;
250    let new_str = &params.new_string;
251
252    let occurrences = content.matches(old_str).count();
253
254    if occurrences > 0 {
255        let args = ReplaceArgs {
256            content,
257            old_str,
258            new_str,
259            occurrences,
260            replace_all: params.replace_all,
261            old_tokens: count_tokens(&params.old_string),
262            new_tokens: count_tokens(&params.new_string),
263        };
264        return do_replace(path, &pre, params, cap, &args);
265    }
266
267    if uses_crlf && !old_str.contains('\r') {
268        let old_crlf = old_str.replace('\n', "\r\n");
269        let occ = content.matches(&old_crlf).count();
270        if occ > 0 {
271            let new_crlf = new_str.replace('\n', "\r\n");
272            let args = ReplaceArgs {
273                content,
274                old_str: &old_crlf,
275                new_str: &new_crlf,
276                occurrences: occ,
277                replace_all: params.replace_all,
278                old_tokens: count_tokens(&params.old_string),
279                new_tokens: count_tokens(&params.new_string),
280            };
281            return do_replace(path, &pre, params, cap, &args);
282        }
283    } else if !uses_crlf && old_str.contains("\r\n") {
284        let old_lf = old_str.replace("\r\n", "\n");
285        let occ = content.matches(&old_lf).count();
286        if occ > 0 {
287            let new_lf = new_str.replace("\r\n", "\n");
288            let args = ReplaceArgs {
289                content,
290                old_str: &old_lf,
291                new_str: &new_lf,
292                occurrences: occ,
293                replace_all: params.replace_all,
294                old_tokens: count_tokens(&params.old_string),
295                new_tokens: count_tokens(&params.new_string),
296            };
297            return do_replace(path, &pre, params, cap, &args);
298        }
299    }
300
301    let normalized_content = trim_trailing_per_line(content);
302    let normalized_old = trim_trailing_per_line(old_str);
303    if !normalized_old.is_empty() && normalized_content.contains(&normalized_old) {
304        let line_sep = if uses_crlf { "\r\n" } else { "\n" };
305        let adapted_new = adapt_new_string_to_line_sep(new_str, line_sep);
306        let adapted_old = find_original_span(content, &normalized_old);
307        if let Some(original_match) = adapted_old {
308            let occ = content.matches(&original_match).count();
309            let args = ReplaceArgs {
310                content,
311                old_str: &original_match,
312                new_str: &adapted_new,
313                occurrences: occ,
314                replace_all: params.replace_all,
315                old_tokens: count_tokens(&params.old_string),
316                new_tokens: count_tokens(&params.new_string),
317            };
318            return do_replace(path, &pre, params, cap, &args);
319        }
320    }
321
322    // Same block at a uniformly different indentation, in exactly one place.
323    if let Some(found) = super::reindent::find(content, old_str, new_str) {
324        let line_sep = if uses_crlf { "\r\n" } else { "\n" };
325        let replacement = adapt_new_string_to_line_sep(&found.replacement, line_sep);
326        let args = ReplaceArgs {
327            content,
328            old_str: &found.span,
329            new_str: &replacement,
330            occurrences: content.matches(found.span.as_str()).count(),
331            replace_all: params.replace_all,
332            old_tokens: count_tokens(&params.old_string),
333            new_tokens: count_tokens(&params.new_string),
334        };
335        let (out, effect) = do_replace(path, &pre, params, cap, &args);
336        if out.starts_with("ERROR") {
337            return (out, effect);
338        }
339        return (
340            format!(
341                "note: old_string matched with different indentation — applied at the \
342                 file's indentation.\n{out}"
343            ),
344            effect,
345        );
346    }
347
348    // new_string often overlaps unchanged context, so its presence does not
349    // prove the edit landed (#2143): report it as a fact, keep the diagnosis.
350    let present_note = if content.contains(new_str) {
351        "\nnew_string exists in the file, but that does not establish the edit was \
352         already applied. Re-read the target region."
353    } else {
354        ""
355    };
356
357    let preview = if old_str.len() > 80 {
358        format!("{}...", &old_str[..old_str.floor_char_boundary(77)])
359    } else {
360        old_str.clone()
361    };
362    let hint = if uses_crlf {
363        " (file uses CRLF line endings)"
364    } else {
365        ""
366    };
367
368    // Everything this failure quotes from the file is model-visible, so it is
369    // taken from the admitted reading, never from the original bytes the edit
370    // itself works on. A withheld source yields no quote and no cache store.
371    let admitted = crate::tools::ctx_read::read_file_lossy_admitted_for_cli(file_path).ok();
372    let closest_hint = admitted
373        .as_ref()
374        .map(|source| find_closest_line_hint(&source.text, old_str))
375        .unwrap_or_default();
376    let cross_file = crate::tools::edit_recovery::cross_file_hint(path, old_str);
377
378    let (escalation, effect) = auto_escalate_reread(last_mode, admitted);
379
380    (
381        format!(
382            "ERROR: old_string not found in {file_path}{hint}. \
383             Make sure it matches exactly (including whitespace/indentation).\n\
384             Searched for: {preview}{present_note}{closest_hint}{cross_file}{escalation}"
385        ),
386        effect,
387    )
388}
389
390/// Finds the closest matching line in the file content to help the agent
391/// understand what went wrong. Returns a hint string or empty if no useful match.
392fn find_closest_line_hint(content: &str, old_str: &str) -> String {
393    let first_line = old_str.lines().next().unwrap_or("").trim();
394    if first_line.len() < 4 {
395        return String::new();
396    }
397
398    let mut best_line: Option<(usize, &str)> = None;
399
400    for (i, line) in content.lines().enumerate() {
401        if line.contains(first_line) {
402            best_line = Some((i + 1, line));
403            break;
404        }
405    }
406
407    // Try matching with significant identifiers from old_string's first line
408    if best_line.is_none() {
409        let keyword = first_line
410            .split(|c: char| !c.is_alphanumeric() && c != '_')
411            .find(|w| w.len() >= 4);
412
413        if let Some(keyword) = keyword {
414            for (i, line) in content.lines().enumerate() {
415                if line.contains(keyword) {
416                    best_line = Some((i + 1, line));
417                    break;
418                }
419            }
420        }
421    }
422
423    match best_line {
424        Some((line_num, line_content)) => {
425            let trimmed = line_content.trim();
426            let preview = if trimmed.len() > 100 {
427                format!("{}...", &trimmed[..trimmed.floor_char_boundary(97)])
428            } else {
429                trimmed.to_string()
430            };
431            format!(
432                "\nClosest match at line {line_num}: `{preview}`\n\
433                 Hint: check indentation/whitespace differences."
434            )
435        }
436        None => String::new(),
437    }
438}
439
440/// Auto-escalation: when old_string is not found and the file was previously read
441/// in a compressed mode, re-read in full and return the content so the agent
442/// can immediately retry with the correct old_string. Returns the text to append
443/// plus the [`CacheEffect`] the caller should apply (store full content).
444///
445/// `admitted` is the Gateway-admitted reading of the file; `None` (withheld or
446/// unreadable) escalates nothing. Restricted text is shown as admitted but
447/// never handed to the cache (E3).
448fn auto_escalate_reread(
449    last_mode: &str,
450    admitted: Option<crate::core::context_admission::SourceAdmission>,
451) -> (String, CacheEffect) {
452    if last_mode.is_empty() || last_mode == "full" {
453        return (String::new(), CacheEffect::None);
454    }
455
456    let Some(admitted) = admitted else {
457        return (String::new(), CacheEffect::None);
458    };
459    let storable = admitted.storable;
460    let fresh_content = admitted.text;
461
462    let line_count = fresh_content.lines().count();
463    const MAX_LINES: usize = 300;
464
465    let content_preview = if line_count <= MAX_LINES {
466        fresh_content.clone()
467    } else {
468        let lines: Vec<&str> = fresh_content.lines().collect();
469        let head = &lines[..MAX_LINES / 2];
470        let tail = &lines[line_count - MAX_LINES / 2..];
471        let omitted = line_count - MAX_LINES;
472        format!(
473            "{}\n[... {omitted} lines omitted ...]\n{}",
474            head.join("\n"),
475            tail.join("\n")
476        )
477    };
478
479    (
480        format!(
481            "\n\n[auto-escalation] Last read used mode=\"{last_mode}\". \
482             Full content ({line_count}L) below — retry edit with exact text from here:\n\n{content_preview}"
483        ),
484        if storable {
485            CacheEffect::StoreFull(fresh_content)
486        } else {
487            CacheEffect::None
488        },
489    )
490}
491
492fn do_replace(
493    path: &Path,
494    pre: &FilePreimage,
495    params: &EditParams,
496    cap: usize,
497    args: &ReplaceArgs<'_>,
498) -> (String, CacheEffect) {
499    if args.occurrences > 1 && !args.replace_all {
500        return (
501            format!(
502                "ERROR: old_string found {} times in {}. \
503                 Use replace_all=true to replace all, or provide more context to make old_string unique.",
504                args.occurrences,
505                path.display()
506            ),
507            CacheEffect::None,
508        );
509    }
510
511    let new_content = if args.replace_all {
512        args.content.replace(args.old_str, args.new_str)
513    } else {
514        args.content.replacen(args.old_str, args.new_str, 1)
515    };
516
517    // Code-health gate: warn on (or block) cognitive-complexity drift before write.
518    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
519    let health_notice =
520        match crate::core::code_health::gate::evaluate(args.content, &new_content, ext) {
521            crate::core::code_health::gate::GateOutcome::Block(reason) => {
522                return (
523                    format!("ERROR: code-health gate: {reason}"),
524                    CacheEffect::None,
525                );
526            }
527            crate::core::code_health::gate::GateOutcome::Allow(notice) => notice,
528        };
529
530    // #960: a point-in-time check, not a held lock — see
531    // ensure_preimage_still_matches' doc for the residual window between
532    // this check and the write below.
533    if let Err(e) = ensure_preimage_still_matches(path, &pre.fp, cap) {
534        return (e, CacheEffect::None);
535    }
536
537    let backup_path = if params.backup {
538        let bp = params
539            .backup_path
540            .as_deref()
541            .map(PathBuf::from)
542            .or_else(|| default_backup_path(path));
543        let Some(bp) = bp else {
544            return (
545                format!("ERROR: cannot compute backup path for {}", path.display()),
546                CacheEffect::None,
547            );
548        };
549        if let Err(e) = write_atomic_bytes_with_permissions(&bp, &pre.bytes, Some(&pre.permissions))
550        {
551            return (
552                format!("ERROR: cannot create backup {}: {e}", bp.display()),
553                CacheEffect::None,
554            );
555        }
556        Some(bp.to_string_lossy().to_string())
557    } else {
558        None
559    };
560
561    if let Err(e) =
562        write_atomic_bytes_with_permissions(path, new_content.as_bytes(), Some(&pre.permissions))
563    {
564        return (e, CacheEffect::None);
565    }
566
567    let replacements = if args.replace_all {
568        args.occurrences
569    } else {
570        1
571    };
572    let replacements = u64::try_from(replacements).unwrap_or(u64::MAX);
573    let lines_added = u64::try_from(args.new_str.lines().count())
574        .unwrap_or(u64::MAX)
575        .saturating_mul(replacements);
576    let lines_removed = u64::try_from(args.old_str.lines().count())
577        .unwrap_or(u64::MAX)
578        .saturating_mul(replacements);
579    crate::core::edit_metering::record_loc_change(Some(&params.path), lines_added, lines_removed);
580
581    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
582        bt.record_edit(&params.path);
583    }
584
585    let old_lines = args.content.lines().count();
586    let new_lines = new_content.lines().count();
587    let line_delta = new_lines as i64 - old_lines as i64;
588    let delta_str = if line_delta > 0 {
589        format!("+{line_delta}")
590    } else {
591        format!("{line_delta}")
592    };
593
594    let old_tokens = args.old_tokens;
595    let new_tokens = args.new_tokens;
596
597    let replaced_str = if args.replace_all && args.occurrences > 1 {
598        format!("{} replacements", args.occurrences)
599    } else {
600        "1 replacement".into()
601    };
602
603    let short = path.file_name().map_or_else(
604        || path.to_string_lossy().to_string(),
605        |f| f.to_string_lossy().to_string(),
606    );
607
608    let post_mtime_ms = std::fs::metadata(path)
609        .ok()
610        .and_then(|m| m.modified().ok())
611        .map_or(0, system_time_to_millis);
612    let post_fp = FileFingerprint {
613        size: new_content.len() as u64,
614        mtime_ms: post_mtime_ms,
615        blake3: crate::core::hasher::hash_hex(new_content.as_bytes()),
616    };
617
618    let mut out = format!(
619        "✓ {short}: {replaced_str}, {delta_str} lines ({old_tokens}→{new_tokens} tok)\n\
620preimage: bytes={}, mtime_ms={}, blake3={}\n\
621postimage: bytes={}, mtime_ms={}, blake3={}",
622        pre.fp.size, pre.fp.mtime_ms, pre.fp.blake3, post_fp.size, post_fp.mtime_ms, post_fp.blake3
623    );
624    if let Some(bp) = backup_path {
625        out.push_str(&format!("\nbackup: {bp}"));
626    }
627    if params.evidence {
628        let diff = build_diff_evidence(args.content, &new_content, &short, params.diff_max_lines);
629        out.push_str("\n\nevidence (diff, redacted, bounded):\n```diff\n");
630        out.push_str(&diff);
631        out.push_str("\n```");
632    }
633    if let Some(notice) = health_notice {
634        out.push_str("\n\n");
635        out.push_str(&notice);
636    }
637    (out, CacheEffect::Invalidate)
638}
639
640fn handle_create(file_path: &str, content: &str, params: &EditParams) -> (String, CacheEffect) {
641    let path = Path::new(file_path);
642    let cap = crate::core::limits::max_read_bytes();
643
644    // Deny before the standalone create_dir_all below can materialise a
645    // directory inside a read-only root (#475). The atomic writer guards the
646    // file write too, but this stops an empty-dir side effect first.
647    if let Err(e) = crate::core::pathjail::enforce_writable(path) {
648        return (format!("ERROR: {e}"), CacheEffect::None);
649    }
650
651    let mut preimage: Option<FilePreimage> = None;
652    if path.exists() {
653        let pre = match read_preimage(path, cap, params.allow_lossy_utf8) {
654            Ok(p) => p,
655            Err(e) => return (e, CacheEffect::None),
656        };
657        if let Err(e) = verify_expected_preimage(&pre, params) {
658            return (e, CacheEffect::None);
659        }
660        // #960: a point-in-time check, not a held lock — see
661        // ensure_preimage_still_matches' doc for the residual window between
662        // this check and the write below.
663        if let Err(e) = ensure_preimage_still_matches(path, &pre.fp, cap) {
664            return (e, CacheEffect::None);
665        }
666        preimage = Some(pre);
667    }
668
669    if let Some(parent) = path.parent()
670        && !parent.exists()
671        && let Err(e) = std::fs::create_dir_all(parent)
672    {
673        return (
674            format!("ERROR: cannot create directory {}: {e}", parent.display()),
675            CacheEffect::None,
676        );
677    }
678
679    let backup_path = if params.backup {
680        if let Some(pre) = &preimage {
681            let bp = params
682                .backup_path
683                .as_deref()
684                .map(PathBuf::from)
685                .or_else(|| default_backup_path(path));
686            let Some(bp) = bp else {
687                return (
688                    format!("ERROR: cannot compute backup path for {}", path.display()),
689                    CacheEffect::None,
690                );
691            };
692            if let Err(e) =
693                write_atomic_bytes_with_permissions(&bp, &pre.bytes, Some(&pre.permissions))
694            {
695                return (
696                    format!("ERROR: cannot create backup {}: {e}", bp.display()),
697                    CacheEffect::None,
698                );
699            }
700            Some(bp.to_string_lossy().to_string())
701        } else {
702            None
703        }
704    } else {
705        None
706    };
707
708    let perms = preimage.as_ref().map(|p| &p.permissions);
709    if let Err(e) = write_atomic_bytes_with_permissions(path, content.as_bytes(), perms) {
710        return (e, CacheEffect::None);
711    }
712
713    let lines_added = u64::try_from(content.lines().count()).unwrap_or(u64::MAX);
714    let lines_removed = preimage.as_ref().map_or(0, |pre| {
715        u64::try_from(pre.text.lines().count()).unwrap_or(u64::MAX)
716    });
717    crate::core::edit_metering::record_loc_change(Some(file_path), lines_added, lines_removed);
718
719    let lines = content.lines().count();
720    let tokens = count_tokens(content);
721    let short = path.file_name().map_or_else(
722        || path.to_string_lossy().to_string(),
723        |f| f.to_string_lossy().to_string(),
724    );
725
726    let mut out = format!("✓ created {short}: {lines} lines, {tokens} tok");
727    if let Some(bp) = backup_path {
728        out.push_str(&format!("\nbackup: {bp}"));
729    }
730    (out, CacheEffect::Invalidate)
731}
732
733fn trim_trailing_per_line(s: &str) -> String {
734    s.lines().map(str::trim_end).collect::<Vec<_>>().join("\n")
735}
736
737fn adapt_new_string_to_line_sep(s: &str, sep: &str) -> String {
738    let normalized = s.replace("\r\n", "\n");
739    if sep == "\r\n" {
740        normalized.replace('\n', "\r\n")
741    } else {
742        normalized
743    }
744}
745
746/// Find the original (un-trimmed) span in `content` that matches `normalized_needle`
747/// after trailing-whitespace trimming per line.
748fn find_original_span(content: &str, normalized_needle: &str) -> Option<String> {
749    let needle_lines: Vec<&str> = normalized_needle.lines().collect();
750    if needle_lines.is_empty() {
751        return None;
752    }
753
754    let content_lines: Vec<&str> = content.lines().collect();
755
756    'outer: for start in 0..content_lines.len() {
757        if start + needle_lines.len() > content_lines.len() {
758            break;
759        }
760        for (i, nl) in needle_lines.iter().enumerate() {
761            if content_lines[start + i].trim_end() != *nl {
762                continue 'outer;
763            }
764        }
765        let sep = if content.contains("\r\n") {
766            "\r\n"
767        } else {
768            "\n"
769        };
770        return Some(content_lines[start..start + needle_lines.len()].join(sep));
771    }
772    None
773}
774
775pub fn captured_solution_decision_kinds(old_content: &str, new_content: &str) -> Vec<&'static str> {
776    let mut kinds = Vec::new();
777
778    if new_content.contains("use std::") && !old_content.contains("use std::") {
779        kinds.push("stdlib");
780    }
781
782    if new_content.contains("// lean-ctx:") && !old_content.contains("// lean-ctx:") {
783        kinds.push("debt");
784    }
785
786    let old_deps = old_content
787        .lines()
788        .filter(|line| line.contains("[dependencies]") || line.contains("= \""))
789        .count();
790    let new_deps = new_content
791        .lines()
792        .filter(|line| line.contains("[dependencies]") || line.contains("= \""))
793        .count();
794    if new_deps < old_deps {
795        kinds.push("native");
796    }
797
798    let old_lines = old_content.lines().count();
799    let new_lines = new_content.lines().count();
800    if old_lines > 5 && new_lines < old_lines / 2 {
801        kinds.push("oneline");
802    }
803
804    kinds
805}
806
807#[cfg(test)]
808mod solution_auto_capture_tests {
809    use super::captured_solution_decision_kinds;
810
811    #[test]
812    fn classifies_decisions_from_completed_edit_content() {
813        let old = "use crate::core::Config;\n[dependencies]\nlegacy = \"1\"\nfn verbose() {\n    first();\n    second();\n    third();\n    fourth();\n    fifth();\n    sixth();\n}\n";
814        let new = "use crate::core::Config;\nuse std::collections::HashMap;\n[dependencies]\n// lean-ctx: replace legacy dependency\nfn concise() {}\n";
815
816        assert_eq!(
817            captured_solution_decision_kinds(old, new),
818            ["stdlib", "debt", "native"]
819        );
820    }
821}