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