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