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 const NO_CHANGE_PREFIX: &str = "No change:";
191
192pub fn run_io(params: &EditParams, last_mode: &str) -> (String, CacheEffect) {
198 let file_path = ¶ms.path;
199
200 if params.create {
201 return handle_create(file_path, ¶ms.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 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 if content.contains(¶ms.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 = ¶ms.old_string;
250 let new_str = ¶ms.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(¶ms.old_string),
262 new_tokens: count_tokens(¶ms.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(¶ms.old_string),
279 new_tokens: count_tokens(¶ms.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(¶ms.old_string),
295 new_tokens: count_tokens(¶ms.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(¶ms.old_string),
316 new_tokens: count_tokens(¶ms.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
358fn 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 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
408fn 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 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 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(¶ms.path), lines_added, lines_removed);
535
536 if let Ok(mut bt) = crate::core::bounce_tracker::global().lock() {
537 bt.record_edit(¶ms.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(¬ice);
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 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 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
701fn 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}