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    if content.contains(new_str) {
349        return (
350            format!(
351                "ERROR: old_string not found in {file_path}, but new_string already exists in the file. \
352                 The edit was likely already applied (by a previous tool call or another agent)."
353            ),
354            CacheEffect::None,
355        );
356    }
357
358    let preview = if old_str.len() > 80 {
359        format!("{}...", &old_str[..old_str.floor_char_boundary(77)])
360    } else {
361        old_str.clone()
362    };
363    let hint = if uses_crlf {
364        " (file uses CRLF line endings)"
365    } else {
366        ""
367    };
368
369    let closest_hint = find_closest_line_hint(content, old_str);
370    let cross_file = crate::tools::edit_recovery::cross_file_hint(path, old_str);
371
372    let (escalation, effect) = auto_escalate_reread(last_mode, file_path);
373
374    (
375        format!(
376            "ERROR: old_string not found in {file_path}{hint}. \
377             Make sure it matches exactly (including whitespace/indentation).\n\
378             Searched for: {preview}{closest_hint}{cross_file}{escalation}"
379        ),
380        effect,
381    )
382}
383
384/// Finds the closest matching line in the file content to help the agent
385/// understand what went wrong. Returns a hint string or empty if no useful match.
386fn find_closest_line_hint(content: &str, old_str: &str) -> String {
387    let first_line = old_str.lines().next().unwrap_or("").trim();
388    if first_line.len() < 4 {
389        return String::new();
390    }
391
392    let mut best_line: Option<(usize, &str)> = None;
393
394    for (i, line) in content.lines().enumerate() {
395        if line.contains(first_line) {
396            best_line = Some((i + 1, line));
397            break;
398        }
399    }
400
401    // Try matching with significant identifiers from old_string's first line
402    if best_line.is_none() {
403        let keyword = first_line
404            .split(|c: char| !c.is_alphanumeric() && c != '_')
405            .find(|w| w.len() >= 4);
406
407        if let Some(keyword) = keyword {
408            for (i, line) in content.lines().enumerate() {
409                if line.contains(keyword) {
410                    best_line = Some((i + 1, line));
411                    break;
412                }
413            }
414        }
415    }
416
417    match best_line {
418        Some((line_num, line_content)) => {
419            let trimmed = line_content.trim();
420            let preview = if trimmed.len() > 100 {
421                format!("{}...", &trimmed[..trimmed.floor_char_boundary(97)])
422            } else {
423                trimmed.to_string()
424            };
425            format!(
426                "\nClosest match at line {line_num}: `{preview}`\n\
427                 Hint: check indentation/whitespace differences."
428            )
429        }
430        None => String::new(),
431    }
432}
433
434/// Auto-escalation: when old_string is not found and the file was previously read
435/// in a compressed mode, re-read in full and return the content so the agent
436/// can immediately retry with the correct old_string. Returns the text to append
437/// plus the [`CacheEffect`] the caller should apply (store full content).
438fn auto_escalate_reread(last_mode: &str, path: &str) -> (String, CacheEffect) {
439    if last_mode.is_empty() || last_mode == "full" {
440        return (String::new(), CacheEffect::None);
441    }
442
443    let Ok(fresh_content) = std::fs::read_to_string(path) else {
444        return (String::new(), CacheEffect::None);
445    };
446
447    let line_count = fresh_content.lines().count();
448    const MAX_LINES: usize = 300;
449
450    let content_preview = if line_count <= MAX_LINES {
451        fresh_content.clone()
452    } else {
453        let lines: Vec<&str> = fresh_content.lines().collect();
454        let head = &lines[..MAX_LINES / 2];
455        let tail = &lines[line_count - MAX_LINES / 2..];
456        let omitted = line_count - MAX_LINES;
457        format!(
458            "{}\n[... {omitted} lines omitted ...]\n{}",
459            head.join("\n"),
460            tail.join("\n")
461        )
462    };
463
464    (
465        format!(
466            "\n\n[auto-escalation] Last read used mode=\"{last_mode}\". \
467             Full content ({line_count}L) below — retry edit with exact text from here:\n\n{content_preview}"
468        ),
469        CacheEffect::StoreFull(fresh_content),
470    )
471}
472
473fn do_replace(
474    path: &Path,
475    pre: &FilePreimage,
476    params: &EditParams,
477    cap: usize,
478    args: &ReplaceArgs<'_>,
479) -> (String, CacheEffect) {
480    if args.occurrences > 1 && !args.replace_all {
481        return (
482            format!(
483                "ERROR: old_string found {} times in {}. \
484                 Use replace_all=true to replace all, or provide more context to make old_string unique.",
485                args.occurrences,
486                path.display()
487            ),
488            CacheEffect::None,
489        );
490    }
491
492    let new_content = if args.replace_all {
493        args.content.replace(args.old_str, args.new_str)
494    } else {
495        args.content.replacen(args.old_str, args.new_str, 1)
496    };
497
498    // Code-health gate: warn on (or block) cognitive-complexity drift before write.
499    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
500    let health_notice =
501        match crate::core::code_health::gate::evaluate(args.content, &new_content, ext) {
502            crate::core::code_health::gate::GateOutcome::Block(reason) => {
503                return (
504                    format!("ERROR: code-health gate: {reason}"),
505                    CacheEffect::None,
506                );
507            }
508            crate::core::code_health::gate::GateOutcome::Allow(notice) => notice,
509        };
510
511    // #960: a point-in-time check, not a held lock — see
512    // ensure_preimage_still_matches' doc for the residual window between
513    // this check and the write below.
514    if let Err(e) = ensure_preimage_still_matches(path, &pre.fp, cap) {
515        return (e, CacheEffect::None);
516    }
517
518    let backup_path = if params.backup {
519        let bp = params
520            .backup_path
521            .as_deref()
522            .map(PathBuf::from)
523            .or_else(|| default_backup_path(path));
524        let Some(bp) = bp else {
525            return (
526                format!("ERROR: cannot compute backup path for {}", path.display()),
527                CacheEffect::None,
528            );
529        };
530        if let Err(e) = write_atomic_bytes_with_permissions(&bp, &pre.bytes, Some(&pre.permissions))
531        {
532            return (
533                format!("ERROR: cannot create backup {}: {e}", bp.display()),
534                CacheEffect::None,
535            );
536        }
537        Some(bp.to_string_lossy().to_string())
538    } else {
539        None
540    };
541
542    if let Err(e) =
543        write_atomic_bytes_with_permissions(path, new_content.as_bytes(), Some(&pre.permissions))
544    {
545        return (e, CacheEffect::None);
546    }
547
548    let replacements = if args.replace_all {
549        args.occurrences
550    } else {
551        1
552    };
553    let replacements = u64::try_from(replacements).unwrap_or(u64::MAX);
554    let lines_added = u64::try_from(args.new_str.lines().count())
555        .unwrap_or(u64::MAX)
556        .saturating_mul(replacements);
557    let lines_removed = u64::try_from(args.old_str.lines().count())
558        .unwrap_or(u64::MAX)
559        .saturating_mul(replacements);
560    crate::core::edit_metering::record_loc_change(Some(&params.path), lines_added, lines_removed);
561
562    if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
563        bt.record_edit(&params.path);
564    }
565
566    let old_lines = args.content.lines().count();
567    let new_lines = new_content.lines().count();
568    let line_delta = new_lines as i64 - old_lines as i64;
569    let delta_str = if line_delta > 0 {
570        format!("+{line_delta}")
571    } else {
572        format!("{line_delta}")
573    };
574
575    let old_tokens = args.old_tokens;
576    let new_tokens = args.new_tokens;
577
578    let replaced_str = if args.replace_all && args.occurrences > 1 {
579        format!("{} replacements", args.occurrences)
580    } else {
581        "1 replacement".into()
582    };
583
584    let short = path.file_name().map_or_else(
585        || path.to_string_lossy().to_string(),
586        |f| f.to_string_lossy().to_string(),
587    );
588
589    let post_mtime_ms = std::fs::metadata(path)
590        .ok()
591        .and_then(|m| m.modified().ok())
592        .map_or(0, system_time_to_millis);
593    let post_fp = FileFingerprint {
594        size: new_content.len() as u64,
595        mtime_ms: post_mtime_ms,
596        blake3: crate::core::hasher::hash_hex(new_content.as_bytes()),
597    };
598
599    let mut out = format!(
600        "✓ {short}: {replaced_str}, {delta_str} lines ({old_tokens}→{new_tokens} tok)\n\
601preimage: bytes={}, mtime_ms={}, blake3={}\n\
602postimage: bytes={}, mtime_ms={}, blake3={}",
603        pre.fp.size, pre.fp.mtime_ms, pre.fp.blake3, post_fp.size, post_fp.mtime_ms, post_fp.blake3
604    );
605    if let Some(bp) = backup_path {
606        out.push_str(&format!("\nbackup: {bp}"));
607    }
608    if params.evidence {
609        let diff = build_diff_evidence(args.content, &new_content, &short, params.diff_max_lines);
610        out.push_str("\n\nevidence (diff, redacted, bounded):\n```diff\n");
611        out.push_str(&diff);
612        out.push_str("\n```");
613    }
614    if let Some(notice) = health_notice {
615        out.push_str("\n\n");
616        out.push_str(&notice);
617    }
618    (out, CacheEffect::Invalidate)
619}
620
621fn handle_create(file_path: &str, content: &str, params: &EditParams) -> (String, CacheEffect) {
622    let path = Path::new(file_path);
623    let cap = crate::core::limits::max_read_bytes();
624
625    // Deny before the standalone create_dir_all below can materialise a
626    // directory inside a read-only root (#475). The atomic writer guards the
627    // file write too, but this stops an empty-dir side effect first.
628    if let Err(e) = crate::core::pathjail::enforce_writable(path) {
629        return (format!("ERROR: {e}"), CacheEffect::None);
630    }
631
632    let mut preimage: Option<FilePreimage> = None;
633    if path.exists() {
634        let pre = match read_preimage(path, cap, params.allow_lossy_utf8) {
635            Ok(p) => p,
636            Err(e) => return (e, CacheEffect::None),
637        };
638        if let Err(e) = verify_expected_preimage(&pre, params) {
639            return (e, CacheEffect::None);
640        }
641        // #960: a point-in-time check, not a held lock — see
642        // ensure_preimage_still_matches' doc for the residual window between
643        // this check and the write below.
644        if let Err(e) = ensure_preimage_still_matches(path, &pre.fp, cap) {
645            return (e, CacheEffect::None);
646        }
647        preimage = Some(pre);
648    }
649
650    if let Some(parent) = path.parent()
651        && !parent.exists()
652        && let Err(e) = std::fs::create_dir_all(parent)
653    {
654        return (
655            format!("ERROR: cannot create directory {}: {e}", parent.display()),
656            CacheEffect::None,
657        );
658    }
659
660    let backup_path = if params.backup {
661        if let Some(pre) = &preimage {
662            let bp = params
663                .backup_path
664                .as_deref()
665                .map(PathBuf::from)
666                .or_else(|| default_backup_path(path));
667            let Some(bp) = bp else {
668                return (
669                    format!("ERROR: cannot compute backup path for {}", path.display()),
670                    CacheEffect::None,
671                );
672            };
673            if let Err(e) =
674                write_atomic_bytes_with_permissions(&bp, &pre.bytes, Some(&pre.permissions))
675            {
676                return (
677                    format!("ERROR: cannot create backup {}: {e}", bp.display()),
678                    CacheEffect::None,
679                );
680            }
681            Some(bp.to_string_lossy().to_string())
682        } else {
683            None
684        }
685    } else {
686        None
687    };
688
689    let perms = preimage.as_ref().map(|p| &p.permissions);
690    if let Err(e) = write_atomic_bytes_with_permissions(path, content.as_bytes(), perms) {
691        return (e, CacheEffect::None);
692    }
693
694    let lines_added = u64::try_from(content.lines().count()).unwrap_or(u64::MAX);
695    let lines_removed = preimage.as_ref().map_or(0, |pre| {
696        u64::try_from(pre.text.lines().count()).unwrap_or(u64::MAX)
697    });
698    crate::core::edit_metering::record_loc_change(Some(file_path), lines_added, lines_removed);
699
700    let lines = content.lines().count();
701    let tokens = count_tokens(content);
702    let short = path.file_name().map_or_else(
703        || path.to_string_lossy().to_string(),
704        |f| f.to_string_lossy().to_string(),
705    );
706
707    let mut out = format!("✓ created {short}: {lines} lines, {tokens} tok");
708    if let Some(bp) = backup_path {
709        out.push_str(&format!("\nbackup: {bp}"));
710    }
711    (out, CacheEffect::Invalidate)
712}
713
714fn trim_trailing_per_line(s: &str) -> String {
715    s.lines().map(str::trim_end).collect::<Vec<_>>().join("\n")
716}
717
718fn adapt_new_string_to_line_sep(s: &str, sep: &str) -> String {
719    let normalized = s.replace("\r\n", "\n");
720    if sep == "\r\n" {
721        normalized.replace('\n', "\r\n")
722    } else {
723        normalized
724    }
725}
726
727/// Find the original (un-trimmed) span in `content` that matches `normalized_needle`
728/// after trailing-whitespace trimming per line.
729fn find_original_span(content: &str, normalized_needle: &str) -> Option<String> {
730    let needle_lines: Vec<&str> = normalized_needle.lines().collect();
731    if needle_lines.is_empty() {
732        return None;
733    }
734
735    let content_lines: Vec<&str> = content.lines().collect();
736
737    'outer: for start in 0..content_lines.len() {
738        if start + needle_lines.len() > content_lines.len() {
739            break;
740        }
741        for (i, nl) in needle_lines.iter().enumerate() {
742            if content_lines[start + i].trim_end() != *nl {
743                continue 'outer;
744            }
745        }
746        let sep = if content.contains("\r\n") {
747            "\r\n"
748        } else {
749            "\n"
750        };
751        return Some(content_lines[start..start + needle_lines.len()].join(sep));
752    }
753    None
754}
755
756pub fn captured_solution_decision_kinds(old_content: &str, new_content: &str) -> Vec<&'static str> {
757    let mut kinds = Vec::new();
758
759    if new_content.contains("use std::") && !old_content.contains("use std::") {
760        kinds.push("stdlib");
761    }
762
763    if new_content.contains("// lean-ctx:") && !old_content.contains("// lean-ctx:") {
764        kinds.push("debt");
765    }
766
767    let old_deps = old_content
768        .lines()
769        .filter(|line| line.contains("[dependencies]") || line.contains("= \""))
770        .count();
771    let new_deps = new_content
772        .lines()
773        .filter(|line| line.contains("[dependencies]") || line.contains("= \""))
774        .count();
775    if new_deps < old_deps {
776        kinds.push("native");
777    }
778
779    let old_lines = old_content.lines().count();
780    let new_lines = new_content.lines().count();
781    if old_lines > 5 && new_lines < old_lines / 2 {
782        kinds.push("oneline");
783    }
784
785    kinds
786}
787
788#[cfg(test)]
789mod solution_auto_capture_tests {
790    use super::captured_solution_decision_kinds;
791
792    #[test]
793    fn classifies_decisions_from_completed_edit_content() {
794        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";
795        let new = "use crate::core::Config;\nuse std::collections::HashMap;\n[dependencies]\n// lean-ctx: replace legacy dependency\nfn concise() {}\n";
796
797        assert_eq!(
798            captured_solution_decision_kinds(old, new),
799            ["stdlib", "debt", "native"]
800        );
801    }
802}