1use std::path::{Path, PathBuf};
2
3use crate::core::cache::SessionCache;
4use crate::core::tokens::count_tokens;
5use 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
14pub 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 pub expected_md5: Option<String>,
23 pub expected_size: Option<u64>,
24 pub expected_mtime_ms: Option<u64>,
25 pub backup: bool,
27 pub backup_path: Option<String>,
28 pub evidence: bool,
30 pub diff_max_lines: usize,
31 pub allow_lossy_utf8: bool,
33}
34
35struct ReplaceArgs<'a> {
36 content: &'a str,
37 old_str: &'a str,
38 new_str: &'a str,
39 occurrences: usize,
40 replace_all: bool,
41 old_tokens: usize,
42 new_tokens: usize,
43}
44
45fn verify_expected_preimage(pre: &FilePreimage, params: &EditParams) -> Result<(), String> {
46 if let Some(expected) = params.expected_size
47 && expected != pre.fp.size
48 {
49 return Err(format!(
50 "ERROR: preimage mismatch for {}: expected_size={}, actual_size={}",
51 params.path, expected, pre.fp.size
52 ));
53 }
54 if let Some(expected) = params.expected_mtime_ms
55 && expected != pre.fp.mtime_ms
56 {
57 return Err(format!(
58 "ERROR: preimage mismatch for {}: expected_mtime_ms={}, actual_mtime_ms={}",
59 params.path, expected, pre.fp.mtime_ms
60 ));
61 }
62 if let Some(expected) = params.expected_md5.as_deref()
63 && expected != pre.fp.md5
64 {
65 return Err(format!(
66 "ERROR: preimage mismatch for {}: expected_md5={}, actual_md5={}",
67 params.path, expected, pre.fp.md5
68 ));
69 }
70 Ok(())
71}
72
73pub(crate) fn build_diff_evidence(old: &str, new: &str, label: &str, max_lines: usize) -> String {
76 let diff = similar::TextDiff::from_lines(old, new)
77 .unified_diff()
78 .context_radius(3)
79 .header(label, label)
80 .to_string();
81 let diff = crate::core::redaction::redact_text(&diff);
86
87 let mut out = String::new();
88 for (i, line) in diff.lines().enumerate() {
89 if i >= max_lines {
90 out.push_str(&format!("\n... diff truncated (max_lines={max_lines})"));
91 break;
92 }
93 out.push_str(line);
94 out.push('\n');
95 }
96 out.trim_end_matches('\n').to_string()
97}
98
99pub enum CacheEffect {
106 None,
108 Invalidate,
110 StoreFull(String),
113}
114
115pub fn handle(cache: &mut SessionCache, params: &EditParams) -> String {
120 let last_mode = cache
121 .get(¶ms.path)
122 .map(|e| e.last_mode.clone())
123 .unwrap_or_default();
124 let (text, effect) = run_io(params, &last_mode);
125 record_outcome(params, &last_mode, &text, &effect);
126 apply_cache_effect(cache, ¶ms.path, effect);
127 text
128}
129
130pub fn record_outcome(params: &EditParams, last_mode: &str, text: &str, effect: &CacheEffect) {
137 if params.create {
138 return;
139 }
140 let success = matches!(effect, CacheEffect::Invalidate);
141 let not_found_failure = matches!(effect, CacheEffect::StoreFull(_))
142 || (matches!(effect, CacheEffect::None)
143 && text.starts_with("ERROR: old_string not found")
144 && !text.contains("already"));
145 if success {
146 if let Some(project_root) = crate::server::derive_project_root_from_cwd() {
147 crate::core::solution_auto_capture::capture_edit_decisions(
148 &project_root,
149 ¶ms.path,
150 ¶ms.old_string,
151 ¶ms.new_string,
152 );
153 }
154 }
155
156 if success || not_found_failure {
157 crate::core::edit_quality::record_edit_outcome(¶ms.path, last_mode, success);
158 }
159 if success {
163 crate::core::edit_metering::record_str_replace_success(
164 count_tokens(¶ms.old_string) as u64
165 );
166 } else if not_found_failure {
167 crate::core::edit_metering::record_str_replace_miss();
168 }
169}
170
171pub fn apply_cache_effect(cache: &mut SessionCache, path: &str, effect: CacheEffect) {
173 match effect {
174 CacheEffect::None => {}
175 CacheEffect::Invalidate => {
176 cache.invalidate(path);
177 }
178 CacheEffect::StoreFull(content) => {
179 cache.store(path, &content);
180 cache.mark_full_delivered(path);
181 }
182 }
183}
184
185pub fn run_io(params: &EditParams, last_mode: &str) -> (String, CacheEffect) {
191 let file_path = ¶ms.path;
192
193 if params.create {
194 return handle_create(file_path, ¶ms.new_string, params);
195 }
196
197 let cap = crate::core::limits::max_read_bytes();
198 let path = Path::new(file_path);
199 let pre = match read_preimage(path, cap, params.allow_lossy_utf8) {
200 Ok(p) => p,
201 Err(e) => {
202 if !path.exists() {
205 let hint = crate::tools::edit_recovery::moved_or_deleted_hint(path);
206 return (format!("{e}{hint}"), CacheEffect::None);
207 }
208 return (e, CacheEffect::None);
209 }
210 };
211 if let Err(e) = verify_expected_preimage(&pre, params) {
212 return (e, CacheEffect::None);
213 }
214 let content = &pre.text;
215
216 if params.old_string.is_empty() {
217 return (
218 "ERROR: old_string must not be empty (use create=true to create a new file)".into(),
219 CacheEffect::None,
220 );
221 }
222
223 if params.old_string == params.new_string {
224 return (
225 "ERROR: old_string and new_string are identical — nothing to change.".into(),
226 CacheEffect::None,
227 );
228 }
229
230 let uses_crlf = pre.uses_crlf;
231 let old_str = ¶ms.old_string;
232 let new_str = ¶ms.new_string;
233
234 let occurrences = content.matches(old_str).count();
235
236 if occurrences > 0 {
237 let args = ReplaceArgs {
238 content,
239 old_str,
240 new_str,
241 occurrences,
242 replace_all: params.replace_all,
243 old_tokens: count_tokens(¶ms.old_string),
244 new_tokens: count_tokens(¶ms.new_string),
245 };
246 return do_replace(path, &pre, params, cap, &args);
247 }
248
249 if uses_crlf && !old_str.contains('\r') {
250 let old_crlf = old_str.replace('\n', "\r\n");
251 let occ = content.matches(&old_crlf).count();
252 if occ > 0 {
253 let new_crlf = new_str.replace('\n', "\r\n");
254 let args = ReplaceArgs {
255 content,
256 old_str: &old_crlf,
257 new_str: &new_crlf,
258 occurrences: occ,
259 replace_all: params.replace_all,
260 old_tokens: count_tokens(¶ms.old_string),
261 new_tokens: count_tokens(¶ms.new_string),
262 };
263 return do_replace(path, &pre, params, cap, &args);
264 }
265 } else if !uses_crlf && old_str.contains("\r\n") {
266 let old_lf = old_str.replace("\r\n", "\n");
267 let occ = content.matches(&old_lf).count();
268 if occ > 0 {
269 let new_lf = new_str.replace("\r\n", "\n");
270 let args = ReplaceArgs {
271 content,
272 old_str: &old_lf,
273 new_str: &new_lf,
274 occurrences: occ,
275 replace_all: params.replace_all,
276 old_tokens: count_tokens(¶ms.old_string),
277 new_tokens: count_tokens(¶ms.new_string),
278 };
279 return do_replace(path, &pre, params, cap, &args);
280 }
281 }
282
283 let normalized_content = trim_trailing_per_line(content);
284 let normalized_old = trim_trailing_per_line(old_str);
285 if !normalized_old.is_empty() && normalized_content.contains(&normalized_old) {
286 let line_sep = if uses_crlf { "\r\n" } else { "\n" };
287 let adapted_new = adapt_new_string_to_line_sep(new_str, line_sep);
288 let adapted_old = find_original_span(content, &normalized_old);
289 if let Some(original_match) = adapted_old {
290 let occ = content.matches(&original_match).count();
291 let args = ReplaceArgs {
292 content,
293 old_str: &original_match,
294 new_str: &adapted_new,
295 occurrences: occ,
296 replace_all: params.replace_all,
297 old_tokens: count_tokens(¶ms.old_string),
298 new_tokens: count_tokens(¶ms.new_string),
299 };
300 return do_replace(path, &pre, params, cap, &args);
301 }
302 }
303
304 if content.contains(new_str) {
305 return (
306 format!(
307 "ERROR: old_string not found in {file_path}, but new_string already exists in the file. \
308 The edit was likely already applied (by a previous tool call or another agent)."
309 ),
310 CacheEffect::None,
311 );
312 }
313
314 let preview = if old_str.len() > 80 {
315 format!("{}...", &old_str[..old_str.floor_char_boundary(77)])
316 } else {
317 old_str.clone()
318 };
319 let hint = if uses_crlf {
320 " (file uses CRLF line endings)"
321 } else {
322 ""
323 };
324
325 let closest_hint = find_closest_line_hint(content, old_str);
326 let cross_file = crate::tools::edit_recovery::cross_file_hint(path, old_str);
327
328 let (escalation, effect) = auto_escalate_reread(last_mode, file_path);
329
330 (
331 format!(
332 "ERROR: old_string not found in {file_path}{hint}. \
333 Make sure it matches exactly (including whitespace/indentation).\n\
334 Searched for: {preview}{closest_hint}{cross_file}{escalation}"
335 ),
336 effect,
337 )
338}
339
340fn find_closest_line_hint(content: &str, old_str: &str) -> String {
343 let first_line = old_str.lines().next().unwrap_or("").trim();
344 if first_line.len() < 4 {
345 return String::new();
346 }
347
348 let mut best_line: Option<(usize, &str)> = None;
349
350 for (i, line) in content.lines().enumerate() {
351 if line.contains(first_line) {
352 best_line = Some((i + 1, line));
353 break;
354 }
355 }
356
357 if best_line.is_none() {
359 let keyword = first_line
360 .split(|c: char| !c.is_alphanumeric() && c != '_')
361 .find(|w| w.len() >= 4);
362
363 if let Some(keyword) = keyword {
364 for (i, line) in content.lines().enumerate() {
365 if line.contains(keyword) {
366 best_line = Some((i + 1, line));
367 break;
368 }
369 }
370 }
371 }
372
373 match best_line {
374 Some((line_num, line_content)) => {
375 let trimmed = line_content.trim();
376 let preview = if trimmed.len() > 100 {
377 format!("{}...", &trimmed[..trimmed.floor_char_boundary(97)])
378 } else {
379 trimmed.to_string()
380 };
381 format!(
382 "\nClosest match at line {line_num}: `{preview}`\n\
383 Hint: check indentation/whitespace differences."
384 )
385 }
386 None => String::new(),
387 }
388}
389
390fn auto_escalate_reread(last_mode: &str, path: &str) -> (String, CacheEffect) {
395 if last_mode.is_empty() || last_mode == "full" {
396 return (String::new(), CacheEffect::None);
397 }
398
399 let Ok(fresh_content) = std::fs::read_to_string(path) else {
400 return (String::new(), CacheEffect::None);
401 };
402
403 let line_count = fresh_content.lines().count();
404 const MAX_LINES: usize = 300;
405
406 let content_preview = if line_count <= MAX_LINES {
407 fresh_content.clone()
408 } else {
409 let lines: Vec<&str> = fresh_content.lines().collect();
410 let head = &lines[..MAX_LINES / 2];
411 let tail = &lines[line_count - MAX_LINES / 2..];
412 let omitted = line_count - MAX_LINES;
413 format!(
414 "{}\n[... {omitted} lines omitted ...]\n{}",
415 head.join("\n"),
416 tail.join("\n")
417 )
418 };
419
420 (
421 format!(
422 "\n\n[auto-escalation] Last read used mode=\"{last_mode}\". \
423 Full content ({line_count}L) below — retry edit with exact text from here:\n\n{content_preview}"
424 ),
425 CacheEffect::StoreFull(fresh_content),
426 )
427}
428
429fn do_replace(
430 path: &Path,
431 pre: &FilePreimage,
432 params: &EditParams,
433 cap: usize,
434 args: &ReplaceArgs<'_>,
435) -> (String, CacheEffect) {
436 if args.occurrences > 1 && !args.replace_all {
437 return (
438 format!(
439 "ERROR: old_string found {} times in {}. \
440 Use replace_all=true to replace all, or provide more context to make old_string unique.",
441 args.occurrences,
442 path.display()
443 ),
444 CacheEffect::None,
445 );
446 }
447
448 let new_content = if args.replace_all {
449 args.content.replace(args.old_str, args.new_str)
450 } else {
451 args.content.replacen(args.old_str, args.new_str, 1)
452 };
453
454 let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
456 let health_notice =
457 match crate::core::code_health::gate::evaluate(args.content, &new_content, ext) {
458 crate::core::code_health::gate::GateOutcome::Block(reason) => {
459 return (
460 format!("ERROR: code-health gate: {reason}"),
461 CacheEffect::None,
462 );
463 }
464 crate::core::code_health::gate::GateOutcome::Allow(notice) => notice,
465 };
466
467 if let Err(e) = ensure_preimage_still_matches(path, &pre.fp, cap) {
471 return (e, CacheEffect::None);
472 }
473
474 let backup_path = if params.backup {
475 let bp = params
476 .backup_path
477 .as_deref()
478 .map(PathBuf::from)
479 .or_else(|| default_backup_path(path));
480 let Some(bp) = bp else {
481 return (
482 format!("ERROR: cannot compute backup path for {}", path.display()),
483 CacheEffect::None,
484 );
485 };
486 if let Err(e) = write_atomic_bytes_with_permissions(&bp, &pre.bytes, Some(&pre.permissions))
487 {
488 return (
489 format!("ERROR: cannot create backup {}: {e}", bp.display()),
490 CacheEffect::None,
491 );
492 }
493 Some(bp.to_string_lossy().to_string())
494 } else {
495 None
496 };
497
498 if let Err(e) =
499 write_atomic_bytes_with_permissions(path, new_content.as_bytes(), Some(&pre.permissions))
500 {
501 return (e, CacheEffect::None);
502 }
503
504 let replacements = if args.replace_all {
505 args.occurrences
506 } else {
507 1
508 };
509 let replacements = u64::try_from(replacements).unwrap_or(u64::MAX);
510 let lines_added = u64::try_from(args.new_str.lines().count())
511 .unwrap_or(u64::MAX)
512 .saturating_mul(replacements);
513 let lines_removed = u64::try_from(args.old_str.lines().count())
514 .unwrap_or(u64::MAX)
515 .saturating_mul(replacements);
516 crate::core::edit_metering::record_loc_change(Some(¶ms.path), lines_added, lines_removed);
517
518 if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
519 bt.record_edit(¶ms.path);
520 }
521
522 let old_lines = args.content.lines().count();
523 let new_lines = new_content.lines().count();
524 let line_delta = new_lines as i64 - old_lines as i64;
525 let delta_str = if line_delta > 0 {
526 format!("+{line_delta}")
527 } else {
528 format!("{line_delta}")
529 };
530
531 let old_tokens = args.old_tokens;
532 let new_tokens = args.new_tokens;
533
534 let replaced_str = if args.replace_all && args.occurrences > 1 {
535 format!("{} replacements", args.occurrences)
536 } else {
537 "1 replacement".into()
538 };
539
540 let short = path.file_name().map_or_else(
541 || path.to_string_lossy().to_string(),
542 |f| f.to_string_lossy().to_string(),
543 );
544
545 let post_mtime_ms = std::fs::metadata(path)
546 .ok()
547 .and_then(|m| m.modified().ok())
548 .map_or(0, system_time_to_millis);
549 let post_fp = FileFingerprint {
550 size: new_content.len() as u64,
551 mtime_ms: post_mtime_ms,
552 md5: crate::core::hasher::hash_hex(new_content.as_bytes()),
553 };
554
555 let mut out = format!(
556 "✓ {short}: {replaced_str}, {delta_str} lines ({old_tokens}→{new_tokens} tok)\n\
557preimage: bytes={}, mtime_ms={}, md5={}\n\
558postimage: bytes={}, mtime_ms={}, md5={}",
559 pre.fp.size, pre.fp.mtime_ms, pre.fp.md5, post_fp.size, post_fp.mtime_ms, post_fp.md5
560 );
561 if let Some(bp) = backup_path {
562 out.push_str(&format!("\nbackup: {bp}"));
563 }
564 if params.evidence {
565 let diff = build_diff_evidence(args.content, &new_content, &short, params.diff_max_lines);
566 out.push_str("\n\nevidence (diff, redacted, bounded):\n```diff\n");
567 out.push_str(&diff);
568 out.push_str("\n```");
569 }
570 if let Some(notice) = health_notice {
571 out.push_str("\n\n");
572 out.push_str(¬ice);
573 }
574 (out, CacheEffect::Invalidate)
575}
576
577fn handle_create(file_path: &str, content: &str, params: &EditParams) -> (String, CacheEffect) {
578 let path = Path::new(file_path);
579 let cap = crate::core::limits::max_read_bytes();
580
581 if let Err(e) = crate::core::pathjail::enforce_writable(path) {
585 return (format!("ERROR: {e}"), CacheEffect::None);
586 }
587
588 let mut preimage: Option<FilePreimage> = None;
589 if path.exists() {
590 let pre = match read_preimage(path, cap, params.allow_lossy_utf8) {
591 Ok(p) => p,
592 Err(e) => return (e, CacheEffect::None),
593 };
594 if let Err(e) = verify_expected_preimage(&pre, params) {
595 return (e, CacheEffect::None);
596 }
597 if let Err(e) = ensure_preimage_still_matches(path, &pre.fp, cap) {
601 return (e, CacheEffect::None);
602 }
603 preimage = Some(pre);
604 }
605
606 if let Some(parent) = path.parent()
607 && !parent.exists()
608 && let Err(e) = std::fs::create_dir_all(parent)
609 {
610 return (
611 format!("ERROR: cannot create directory {}: {e}", parent.display()),
612 CacheEffect::None,
613 );
614 }
615
616 let backup_path = if params.backup {
617 if let Some(pre) = &preimage {
618 let bp = params
619 .backup_path
620 .as_deref()
621 .map(PathBuf::from)
622 .or_else(|| default_backup_path(path));
623 let Some(bp) = bp else {
624 return (
625 format!("ERROR: cannot compute backup path for {}", path.display()),
626 CacheEffect::None,
627 );
628 };
629 if let Err(e) =
630 write_atomic_bytes_with_permissions(&bp, &pre.bytes, Some(&pre.permissions))
631 {
632 return (
633 format!("ERROR: cannot create backup {}: {e}", bp.display()),
634 CacheEffect::None,
635 );
636 }
637 Some(bp.to_string_lossy().to_string())
638 } else {
639 None
640 }
641 } else {
642 None
643 };
644
645 let perms = preimage.as_ref().map(|p| &p.permissions);
646 if let Err(e) = write_atomic_bytes_with_permissions(path, content.as_bytes(), perms) {
647 return (e, CacheEffect::None);
648 }
649
650 let lines_added = u64::try_from(content.lines().count()).unwrap_or(u64::MAX);
651 let lines_removed = preimage.as_ref().map_or(0, |pre| {
652 u64::try_from(pre.text.lines().count()).unwrap_or(u64::MAX)
653 });
654 crate::core::edit_metering::record_loc_change(Some(file_path), lines_added, lines_removed);
655
656 let lines = content.lines().count();
657 let tokens = count_tokens(content);
658 let short = path.file_name().map_or_else(
659 || path.to_string_lossy().to_string(),
660 |f| f.to_string_lossy().to_string(),
661 );
662
663 let mut out = format!("✓ created {short}: {lines} lines, {tokens} tok");
664 if let Some(bp) = backup_path {
665 out.push_str(&format!("\nbackup: {bp}"));
666 }
667 (out, CacheEffect::Invalidate)
668}
669
670fn trim_trailing_per_line(s: &str) -> String {
671 s.lines().map(str::trim_end).collect::<Vec<_>>().join("\n")
672}
673
674fn adapt_new_string_to_line_sep(s: &str, sep: &str) -> String {
675 let normalized = s.replace("\r\n", "\n");
676 if sep == "\r\n" {
677 normalized.replace('\n', "\r\n")
678 } else {
679 normalized
680 }
681}
682
683fn find_original_span(content: &str, normalized_needle: &str) -> Option<String> {
686 let needle_lines: Vec<&str> = normalized_needle.lines().collect();
687 if needle_lines.is_empty() {
688 return None;
689 }
690
691 let content_lines: Vec<&str> = content.lines().collect();
692
693 'outer: for start in 0..content_lines.len() {
694 if start + needle_lines.len() > content_lines.len() {
695 break;
696 }
697 for (i, nl) in needle_lines.iter().enumerate() {
698 if content_lines[start + i].trim_end() != *nl {
699 continue 'outer;
700 }
701 }
702 let sep = if content.contains("\r\n") {
703 "\r\n"
704 } else {
705 "\n"
706 };
707 return Some(content_lines[start..start + needle_lines.len()].join(sep));
708 }
709 None
710}
711
712pub fn captured_solution_decision_kinds(old_content: &str, new_content: &str) -> Vec<&'static str> {
713 let mut kinds = Vec::new();
714
715 if new_content.contains("use std::") && !old_content.contains("use std::") {
716 kinds.push("stdlib");
717 }
718
719 if new_content.contains("// lean-ctx:") && !old_content.contains("// lean-ctx:") {
720 kinds.push("debt");
721 }
722
723 let old_deps = old_content
724 .lines()
725 .filter(|line| line.contains("[dependencies]") || line.contains("= \""))
726 .count();
727 let new_deps = new_content
728 .lines()
729 .filter(|line| line.contains("[dependencies]") || line.contains("= \""))
730 .count();
731 if new_deps < old_deps {
732 kinds.push("native");
733 }
734
735 let old_lines = old_content.lines().count();
736 let new_lines = new_content.lines().count();
737 if old_lines > 5 && new_lines < old_lines / 2 {
738 kinds.push("oneline");
739 }
740
741 kinds
742}
743
744#[cfg(test)]
745mod solution_auto_capture_tests {
746 use super::captured_solution_decision_kinds;
747
748 #[test]
749 fn classifies_decisions_from_completed_edit_content() {
750 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";
751 let new = "use crate::core::Config;\nuse std::collections::HashMap;\n[dependencies]\n// lean-ctx: replace legacy dependency\nfn concise() {}\n";
752
753 assert_eq!(
754 captured_solution_decision_kinds(old, new),
755 ["stdlib", "debt", "native"]
756 );
757 }
758}