Repository navigation
Expand file tree
/
Copy pathfallback.rs
More file actions
2293 lines (2124 loc) · 86.3 KB
/
Copy pathfallback.rs
File metadata and controls
2293 lines (2124 loc) · 86.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Multi-strategy fallback chain for edit resolution.
//!
//! When a primary edit operation fails (e.g., target text not found), this
//! module provides progressively looser matching strategies before giving up.
//!
//! The fallback chain:
//! 1. **Exact match** (primary, handled by the caller)
//! 2. **Anchor-based matching** (structural landmarks around the edit target)
//! 3. **Similarity scoring** (Jaro-Winkler on surrounding lines)
//! 4. **Structured error** (diagnosis with suggestions)
//!
//! # Examples
//!
//! Suggest similar targets when a search misses:
//!
//! ```rust
//! use patchloom::fallback::{EditError, EditErrorKind, find_similar_targets};
//!
//! let content = "fn process_request() {}\nfn process_response() {}\n";
//! let similar = find_similar_targets(content, "process_requst", 3);
//! assert!(similar.iter().any(|s| s.contains("process_request")));
//! ```
//!
//! Run the full fallback chain (exact, anchor, similarity, structured error):
//!
//! ```rust
//! use patchloom::fallback::{resolve_with_fallback, MatchStrategy};
//!
//! let content = "fn setup() {}\nfn proccess_data(x: i32) {}\nfn cleanup() {}\n";
//! let result = resolve_with_fallback(
//! content,
//! "fn process_data(x: i32) {}",
//! Some("fn setup() {}"),
//! Some("fn cleanup() {}"),
//!).expect("anchor match should succeed");
//! assert_eq!(result.strategy, MatchStrategy::Anchor);
//! assert!(result.matched_text.contains("proccess_data"));
//! ```
//!
//! Validate an edit before applying it:
//!
//! ```rust
//! use patchloom::fallback::validate_edit;
//!
//! let json = r#"{"key": "value"}"#;
//! let result = validate_edit(json, "value", "new_value", Some("config.json"));
//! assert!(result.valid);
//! ```
//!
//! Validate with `--nth` semantics (only replace the Nth occurrence):
//!
//! ```rust
//! use patchloom::fallback::validate_edit_nth;
//!
//! let json = r#"{"a": "val", "b": "val"}"#;
//! let result = validate_edit_nth(json, "val", "new", Some("data.json"), Some(1));
//! assert!(result.valid);
//! ```
//!
//! size-waiver: accepted single-domain bulk (policy #1408). Multi-strategy edit recovery chain is one conceptual unit; do not split for LOC alone.
use serde::{Deserialize, Serialize};
/// Structured error type for edit operations with actionable diagnosis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EditError {
/// What kind of error occurred.
pub kind: EditErrorKind,
/// Human-readable error message.
pub message: String,
/// A suggestion for how to fix the issue (if available).
pub suggestion: Option<String>,
/// Similar targets found in the file (for "did you mean?" hints).
pub similar_targets: Vec<String>,
}
impl std::fmt::Display for EditError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.kind, self.message)?;
if let Some(ref suggestion) = self.suggestion {
write!(f, " (suggestion: {suggestion})")?;
}
if !self.similar_targets.is_empty() {
write!(f, " [similar: {}]", self.similar_targets.join(", "))?;
}
Ok(())
}
}
impl std::error::Error for EditError {}
/// Classification of edit errors.
///
/// Marked `non_exhaustive` so new honesty kinds (for example [`Self::TypeError`])
/// can land in minor releases without breaking external exhaustive matches.
///
/// **Append-only variants:** new kinds must be added **after** the last existing
/// variant. Inserting in the middle shifts discriminants of later variants and
/// fails `cargo-semver-checks` (`enum_no_repr_variant_discriminant_changed`),
/// which blocks patch releases (see #1950 order fix for #1951).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum EditErrorKind {
/// The edit target matched multiple locations in the file.
AmbiguousTarget,
/// The edit target was not found in the file.
NoMatch,
/// The edit would produce invalid syntax.
SyntaxInvalid,
/// Another edit already modified this region (for batch operations).
ConflictingEdit,
/// The file could not be parsed.
ParseError,
/// Path rejected by workspace PathGuard (#1492).
GuardRejected,
/// Invalid arguments or options for the edit.
InvalidInput,
/// Wrong value type for a doc selector (multi-document YAML bare key,
/// navigate into array as object, etc.). CLI JSON uses `error_kind:
/// "type_error"`. Distinct from [`Self::InvalidInput`] so hosts can
/// recover with `0.key` / `[0].key` without scraping English (#1883).
TypeError,
/// I/O or other operational failure.
OperationFailed,
/// Post-write format/lint hook failed (`format_failed` / #1663).
/// Distinct from generic [`Self::OperationFailed`] so hosts can branch
/// without scraping English.
FormatFailed,
/// Create/rename destination already exists without force.
/// CLI JSON uses `error_kind: "already_exists"`. Distinct from
/// [`Self::InvalidInput`] (empty path, directory target) and content SoftSkip
/// ([`Self::Binary`] / [`Self::InvalidEncoding`]) so hosts can hint
/// `overwrite`/`force` without scraping English (#1947 / #1963).
/// Appended after [`Self::FormatFailed`] so 0.18.0 discriminants stay stable.
AlreadyExists,
/// Path not found (`std::io::ErrorKind::NotFound`). CLI JSON uses
/// `error_kind: "not_found"`. Distinct from generic [`Self::OperationFailed`]
/// so hosts can treat missing paths separately from other I/O failures.
NotFound,
/// Patch/apply produced merge conflict markers. CLI JSON uses
/// `error_kind: "conflicts"`. Distinct from [`Self::ConflictingEdit`]
/// (batch region overlap) and generic [`Self::OperationFailed`].
Conflicts,
/// Check/preview reported pending changes, or soft assert-count mismatch
/// (`error_kind: "changes_detected"`, exit 2). Distinct from
/// [`Self::OperationFailed`] so hosts can mirror CLI exit-2 semantics
/// without scraping English.
ChangesDetected,
/// Target contains NUL in the binary probe window (not agent-editable text).
/// CLI JSON uses `error_kind: "binary"`. Distinct from [`Self::InvalidInput`]
/// (empty path, directory target, empty pattern) so hosts can recover
/// overwrite/delete/rename without treating all invalid input as binary (#1963).
/// Appended after [`Self::ChangesDetected`] so 0.18/0.19 discriminants stay stable.
Binary,
/// Target is not valid UTF-8 (and not binary by NUL probe). CLI JSON uses
/// `error_kind: "invalid_encoding"`. Distinct from [`Self::Binary`] and
/// [`Self::InvalidInput`] (#1963).
InvalidEncoding,
/// Fuzzy match span is over-wide vs `old` under [`crate::api::FuzzySpanPolicy`]
/// (or the host refused via `ReplaceOptions::refuse_suspicious_fuzzy`).
/// CLI/library JSON uses `error_kind: "fuzzy_span_suspicious"` (#2005).
/// Appended after [`Self::InvalidEncoding`] so 0.20/0.21 discriminants stay
/// stable.
FuzzySpanSuspicious,
/// Tree-sitter parse hit the per-file deadline (`error_kind: "parse_timeout"`).
/// Distinct from [`Self::ParseError`] so hosts can retry or skip without
/// treating a timeout as a missing grammar (#2406). Append-only after
/// [`Self::FuzzySpanSuspicious`].
ParseTimeout,
}
impl std::fmt::Display for EditErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EditErrorKind::AmbiguousTarget => write!(f, "ambiguous_target"),
EditErrorKind::NoMatch => write!(f, "no_match"),
EditErrorKind::SyntaxInvalid => write!(f, "syntax_invalid"),
EditErrorKind::ConflictingEdit => write!(f, "conflicting_edit"),
EditErrorKind::ParseError => write!(f, "parse_error"),
EditErrorKind::GuardRejected => write!(f, "guard_rejected"),
EditErrorKind::InvalidInput => write!(f, "invalid_input"),
EditErrorKind::TypeError => write!(f, "type_error"),
EditErrorKind::OperationFailed => write!(f, "operation_failed"),
EditErrorKind::FormatFailed => write!(f, "format_failed"),
EditErrorKind::AlreadyExists => write!(f, "already_exists"),
EditErrorKind::NotFound => write!(f, "not_found"),
EditErrorKind::Conflicts => write!(f, "conflicts"),
EditErrorKind::ChangesDetected => write!(f, "changes_detected"),
EditErrorKind::Binary => write!(f, "binary"),
EditErrorKind::InvalidEncoding => write!(f, "invalid_encoding"),
EditErrorKind::FuzzySpanSuspicious => write!(f, "fuzzy_span_suspicious"),
EditErrorKind::ParseTimeout => write!(f, "parse_timeout"),
}
}
}
impl EditError {
/// Build a structured edit error.
pub fn new(kind: EditErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
suggestion: None,
similar_targets: Vec::new(),
}
}
/// PathGuard rejection as an `anyhow` error (`edit_error_kind` → [`EditErrorKind::GuardRejected`]).
///
/// Prefer this over [`crate::exit::InvalidInputError`] for guard failures so
/// library hosts and CLI JSON can branch on `guard_rejected` without scraping
/// English (#1935 / engine PathGuard paths).
pub fn guard_rejected(detail: impl std::fmt::Display) -> anyhow::Error {
Self::new(
EditErrorKind::GuardRejected,
format!("path rejected by workspace guard: {detail}"),
)
.into()
}
/// Attach similar-target suggestions (did-you-mean).
pub fn with_similar(mut self, similar: Vec<String>) -> Self {
self.similar_targets = similar;
self
}
/// Attach a single suggestion string.
pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
self.suggestion = Some(suggestion.into());
self
}
}
/// Downcast an `anyhow` error chain to [`EditErrorKind`] when present.
///
/// Peels both [`EditError`] and the CLI/tx typed errors in [`crate::exit`]
/// (`InvalidInputError`, `NoMatchError`, …) so library hosts can branch on
/// kind without caring which construction path produced the failure.
///
/// Hosts that do **not** depend on `anyhow` should use [`classify_error`]
/// on a `dyn Error` instead (#1659).
pub fn edit_error_kind(err: &anyhow::Error) -> Option<EditErrorKind> {
for cause in err.chain() {
if let Some(kind) = classify_error(cause) {
return Some(kind);
}
}
None
}
/// Downcast an `anyhow` error chain to [`EditError`] when present.
pub fn edit_error_ref(err: &anyhow::Error) -> Option<&EditError> {
for cause in err.chain() {
if let Some(e) = classify_error_ref(cause) {
return Some(e);
}
}
None
}
/// Classify a bare `dyn Error` (no `anyhow` required) into [`EditErrorKind`].
///
/// Walks `source()` and peels [`EditError`] plus the CLI/tx typed errors
/// (`NoMatchError`, `InvalidInputError`, `AmbiguousError`, …). Use this from
/// non-anyhow agent hosts that store `Box<dyn Error>` or `Arc<dyn Error>`.
///
/// ```rust
/// use patchloom::fallback::{classify_error, EditError, EditErrorKind};
///
/// let err: Box<dyn std::error::Error + Send + Sync> =
/// Box::new(EditError::new(EditErrorKind::NoMatch, "no matches for \"x\""));
/// assert_eq!(classify_error(err.as_ref()), Some(EditErrorKind::NoMatch));
/// ```
///
/// See #1659.
pub fn classify_error(err: &(dyn std::error::Error + 'static)) -> Option<EditErrorKind> {
let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err);
while let Some(e) = current {
if let Some(edit) = e.downcast_ref::<EditError>() {
return Some(edit.kind);
}
if e.downcast_ref::<crate::exit::NoMatchError>().is_some() {
return Some(EditErrorKind::NoMatch);
}
if e.downcast_ref::<crate::exit::AmbiguousError>().is_some() {
return Some(EditErrorKind::AmbiguousTarget);
}
if e.downcast_ref::<crate::exit::InvalidInputError>().is_some()
|| e.downcast_ref::<crate::exit::InvalidInputHintError>()
.is_some()
{
return Some(EditErrorKind::InvalidInput);
}
if e.downcast_ref::<crate::exit::AlreadyExistsError>()
.is_some()
{
return Some(EditErrorKind::AlreadyExists);
}
if e.downcast_ref::<crate::exit::TypeErrorError>().is_some() {
return Some(EditErrorKind::TypeError);
}
if e.downcast_ref::<crate::exit::ParseErrorError>().is_some() {
return Some(EditErrorKind::ParseError);
}
if e.downcast_ref::<crate::exit::ParseTimeoutError>().is_some() {
return Some(EditErrorKind::ParseTimeout);
}
if e.downcast_ref::<crate::exit::FormatFailedError>().is_some() {
return Some(EditErrorKind::FormatFailed);
}
if e.downcast_ref::<crate::exit::ConflictsError>().is_some() {
return Some(EditErrorKind::Conflicts);
}
if e.downcast_ref::<crate::exit::ChangesDetectedError>()
.is_some()
{
return Some(EditErrorKind::ChangesDetected);
}
if e.downcast_ref::<crate::exit::BinaryError>().is_some() {
return Some(EditErrorKind::Binary);
}
if e.downcast_ref::<crate::exit::InvalidEncodingError>()
.is_some()
{
return Some(EditErrorKind::InvalidEncoding);
}
if e.downcast_ref::<std::io::Error>()
.is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
{
return Some(EditErrorKind::NotFound);
}
current = e.source();
}
None
}
/// Same stable kind string CLI JSON uses (`already_exists`, `guard_rejected`, …).
///
/// Library hosts that mirror agent JSON envelopes should use this instead of
/// re-implementing [`crate::exit::classify_typed_error`] or scraping Display
/// (#1948). Returns `None` when the chain has no recognized typed kind.
///
/// Prefer this over matching only [`edit_error_kind`] when you need CLI-stable
/// strings (for example `no_matches` vs Display `no_match`).
#[must_use]
pub fn error_kind_str(err: &anyhow::Error) -> Option<&'static str> {
crate::exit::classify_typed_error(err).map(|(kind, _)| kind)
}
/// Whether the error peels as dest-exists create/rename conflict.
///
/// True for both [`crate::exit::AlreadyExistsError`] and
/// [`EditError`] with [`EditErrorKind::AlreadyExists`], so the bool matches
/// what hosts get from [`edit_error_kind`] (#1947).
#[must_use]
pub fn is_already_exists(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::AlreadyExists)
}
/// Whether the error peels as missing path I/O ([`EditErrorKind::NotFound`]).
///
/// Matches IO `NotFound` (including through `anyhow::Context`) and
/// [`EditError`] with [`EditErrorKind::NotFound`]. Prefer this over scraping
/// Display for host recovery when a path is simply absent.
#[must_use]
pub fn is_not_found(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::NotFound)
}
/// Whether the error peels as patch/apply merge conflict markers
/// ([`EditErrorKind::Conflicts`]). Distinct from batch
/// [`EditErrorKind::ConflictingEdit`].
#[must_use]
pub fn is_conflicts(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::Conflicts)
}
/// Whether the error peels as check/preview pending changes or soft
/// assert-count mismatch ([`EditErrorKind::ChangesDetected`], CLI exit 2).
#[must_use]
pub fn is_changes_detected(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::ChangesDetected)
}
/// Whether the error peels as multi-doc / wrong-root type mismatch
/// ([`EditErrorKind::TypeError`]). Distinct from [`EditErrorKind::InvalidInput`].
#[must_use]
pub fn is_type_error(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::TypeError)
}
/// Whether the error peels as post-write format/lint failure
/// ([`EditErrorKind::FormatFailed`]). Files may already be written.
#[must_use]
pub fn is_format_failed(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::FormatFailed)
}
/// Whether the error peels as PathGuard / `--contain` rejection
/// ([`EditErrorKind::GuardRejected`]).
#[must_use]
pub fn is_guard_rejected(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::GuardRejected)
}
/// Whether the error peels as invalid arguments / sole binary / bad options
/// ([`EditErrorKind::InvalidInput`]).
#[must_use]
pub fn is_invalid_input(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::InvalidInput)
}
/// Whether the error peels as soft no-match ([`EditErrorKind::NoMatch`]).
/// CLI JSON kind is `no_matches` via [`error_kind_str`].
#[must_use]
pub fn is_no_match(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::NoMatch)
}
/// Whether the error peels as multi-match / unique-mode ambiguity
/// ([`EditErrorKind::AmbiguousTarget`]). Distinct from soft [`is_no_match`].
///
/// Hosts with `unique: true` / `require_change` multi-hit recovery should prefer
/// this over scraping Display.
#[must_use]
pub fn is_ambiguous(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::AmbiguousTarget)
}
/// Whether the error peels as binary/NUL content ([`EditErrorKind::Binary`]).
///
/// Distinct from [`is_invalid_input`] (argument mistakes) and
/// [`is_invalid_encoding`] (non-UTF-8 text without NUL). Hosts that recover
/// overwrite of non-text priors should branch on this (or [`is_invalid_encoding`])
/// rather than all of `InvalidInput` (#1963).
#[must_use]
pub fn is_binary(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::Binary)
}
/// Whether the error peels as invalid UTF-8 content
/// ([`EditErrorKind::InvalidEncoding`]). Distinct from [`is_binary`] and
/// [`is_invalid_input`] (#1963).
#[must_use]
pub fn is_invalid_encoding(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::InvalidEncoding)
}
/// Whether the error peels as over-wide fuzzy span refuse
/// ([`EditErrorKind::FuzzySpanSuspicious`]) from
/// `ReplaceOptions::refuse_suspicious_fuzzy` / `for_agent` (#2005).
#[must_use]
pub fn is_fuzzy_span_suspicious(err: &anyhow::Error) -> bool {
edit_error_kind(err) == Some(EditErrorKind::FuzzySpanSuspicious)
}
/// One-shot peel of a library/CLI error for host tool envelopes (#1964).
///
/// Combines [`error_kind_str`], [`edit_error_ref`], and agent-facing message
/// so embedders do not reimplement `edit_error_kind` + `error_kind_str` +
/// Display formatting. Returns `None` when the chain has no recognized kind.
#[derive(Debug, Clone)]
pub struct PeeledError {
/// CLI-stable kind string (`already_exists`, `binary`, …).
pub kind_str: &'static str,
/// Agent-facing message (same as CLI JSON `error` when possible).
pub message: String,
/// Optional suggestion from [`EditError`].
pub suggestion: Option<String>,
/// Similar targets from [`EditError`] (did-you-mean).
pub similar_targets: Vec<String>,
}
/// Peel kind string + message + optional suggestion from an error chain (#1964).
#[must_use]
pub fn peel_error(err: &anyhow::Error) -> Option<PeeledError> {
let kind_str = error_kind_str(err)?;
let (suggestion, similar_targets) = match edit_error_ref(err) {
Some(e) => (e.suggestion.clone(), e.similar_targets.clone()),
None => (None, Vec::new()),
};
Some(PeeledError {
kind_str,
message: crate::exit::agent_error_message(err),
suggestion,
similar_targets,
})
}
/// Downcast a bare `dyn Error` chain to [`EditError`] when present (#1659).
///
/// Prefer this when you need `similar_targets` / `suggestion` without
/// depending on `anyhow`.
pub fn classify_error_ref<'a>(err: &'a (dyn std::error::Error + 'static)) -> Option<&'a EditError> {
let mut current: Option<&'a (dyn std::error::Error + 'static)> = Some(err);
while let Some(e) = current {
if let Some(edit) = e.downcast_ref::<EditError>() {
return Some(edit);
}
current = e.source();
}
None
}
/// Result of `validate_edit()`: whether the edit would produce valid output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationResult {
/// Whether the edit produces valid output.
pub valid: bool,
/// Syntax errors found (if invalid).
pub errors: Vec<String>,
/// Suspicious but technically valid issues.
pub warnings: Vec<String>,
}
/// Validate whether a replacement would produce valid output, without applying.
///
/// Performs the replacement in memory and checks basic structural validity
/// of the resulting content (JSON, YAML, TOML validation for structured files).
///
/// When `nth` is `Some(n)`, only the Nth (1-based) occurrence is replaced,
/// matching the behavior of the replace command's `--nth` flag. When `None`,
/// all occurrences are replaced.
pub fn validate_edit(
content: &str,
from: &str,
to: &str,
file_path: Option<&str>,
) -> ValidationResult {
validate_edit_nth(content, from, to, file_path, None)
}
/// Like [`validate_edit`] but with an explicit `nth` occurrence parameter.
pub fn validate_edit_nth(
content: &str,
from: &str,
to: &str,
file_path: Option<&str>,
nth: Option<usize>,
) -> ValidationResult {
if from.is_empty() {
return ValidationResult {
valid: false,
errors: vec!["empty search pattern".into()],
warnings: vec![],
};
}
if !content.contains(from) {
return ValidationResult {
valid: false,
errors: vec![format!(
"pattern '{}' not found in content",
truncate_str(from, 60)
)],
warnings: vec![],
};
}
let new_content = match nth {
Some(0) => {
return ValidationResult {
valid: false,
errors: vec!["nth must be >= 1 (1-based indexing)".into()],
warnings: vec![],
};
}
Some(n) => {
// Replace only the Nth (1-based) occurrence.
let mut count = 0usize;
let mut result = String::with_capacity(content.len());
let mut remaining = content;
while let Some(pos) = remaining.find(from) {
count += 1;
if count == n {
result.push_str(&remaining[..pos]);
result.push_str(to);
result.push_str(&remaining[pos + from.len()..]);
break;
}
result.push_str(&remaining[..pos + from.len()]);
remaining = &remaining[pos + from.len()..];
}
if count < n {
return ValidationResult {
valid: false,
errors: vec![format!(
"occurrence {n} not found (only {count} occurrence{} exist{})",
if count == 1 { "" } else { "s" },
if count == 1 { "s" } else { "" },
)],
warnings: vec![],
};
}
result
}
None => content.replace(from, to),
};
let mut errors = Vec::new();
let mut warnings = Vec::new();
// If we can detect the file format, validate the result.
if let Some(path) = file_path
&& let Ok(fmt) = crate::ops::doc::detect_format(path)
{
let parse_err = match fmt {
crate::ops::doc::FileFormat::Json => {
crate::ops::doc::parse_doc(&new_content, &crate::ops::doc::FileFormat::Json)
.err()
.map(|e| format!("result would be invalid JSON: {e}"))
}
crate::ops::doc::FileFormat::Yaml => {
serde_yaml_ng::from_str::<serde_json::Value>(&new_content)
.err()
.map(|e| format!("result would be invalid YAML: {e}"))
}
crate::ops::doc::FileFormat::Toml => {
toml_edit::de::from_str::<serde_json::Value>(&new_content)
.err()
.map(|e| format!("result would be invalid TOML: {e}"))
}
crate::ops::doc::FileFormat::Env
| crate::ops::doc::FileFormat::Ini
| crate::ops::doc::FileFormat::Properties => {
crate::ops::doc::parse_doc(&new_content, &fmt)
.err()
.map(|e| format!("result would be invalid document: {e}"))
}
};
if let Some(msg) = parse_err {
errors.push(msg);
}
}
// Warn if the replacement creates unbalanced brackets/braces.
let open_parens =
new_content.matches('(').count() as i64 - new_content.matches(')').count() as i64;
let open_braces =
new_content.matches('{').count() as i64 - new_content.matches('}').count() as i64;
let open_brackets =
new_content.matches('[').count() as i64 - new_content.matches(']').count() as i64;
if open_parens != 0 {
warnings.push(format!("unbalanced parentheses (delta: {open_parens})"));
}
if open_braces != 0 {
warnings.push(format!("unbalanced braces (delta: {open_braces})"));
}
if open_brackets != 0 {
warnings.push(format!("unbalanced brackets (delta: {open_brackets})"));
}
ValidationResult {
valid: errors.is_empty(),
errors,
warnings,
}
}
/// Minimum Jaro-Winkler score for a did-you-mean candidate.
///
/// Kept in line with anchor matching (0.85). The previous 0.7 floor
/// admitted noise like `nold` for long unrelated patterns when scanning
/// large trees (fixrealloop stress, 2026-07-23).
const SIMILAR_TARGET_MIN_SCORE: f64 = 0.85;
/// Whether `candidate` is a plausible typo of `target` by length.
///
/// Jaro-Winkler can score short tokens above the floor against long
/// strings (shared characters / prefixes). Reject extreme length skew
/// so agents do not chase nonsense suggestions.
fn similar_target_length_plausible(candidate: &str, target: &str) -> bool {
let (ca, ta) = (candidate.len(), target.len());
if ca == 0 || ta == 0 {
return false;
}
let (shorter, longer) = if ca < ta { (ca, ta) } else { (ta, ca) };
// Allow ~2x length difference, or a small absolute gap for short ids.
shorter.saturating_mul(2) >= longer || longer - shorter <= 3
}
/// Rank whole-string candidates by Jaro-Winkler similarity.
///
/// Unlike [`find_similar_targets`], this does not tokenize `candidates`.
/// Use it for object keys and other already-atomic strings (hyphenated
/// names stay intact).
pub(crate) fn find_similar_among<'a, I>(
candidates: I,
target: &str,
max_results: usize,
) -> Vec<String>
where
I: IntoIterator<Item = &'a str>,
{
if target.is_empty() || max_results == 0 {
return vec![];
}
let mut scored: Vec<(String, f64)> = Vec::new();
let mut seen = std::collections::HashSet::new();
for candidate in candidates {
if candidate.is_empty() || candidate == target || !seen.insert(candidate) {
continue;
}
if !similar_target_length_plausible(candidate, target) {
continue;
}
let score = strsim::jaro_winkler(candidate, target);
if score > SIMILAR_TARGET_MIN_SCORE {
scored.push((candidate.to_string(), score));
}
}
scored.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
scored.truncate(max_results);
scored.into_iter().map(|(s, _)| s).collect()
}
/// Find similar text targets in file content using Jaro-Winkler similarity.
///
/// Extracts identifiers and substrings from the content and returns the top
/// `max_results` matches sorted by similarity score (descending).
pub fn find_similar_targets(content: &str, target: &str, max_results: usize) -> Vec<String> {
if target.is_empty() || content.is_empty() {
return vec![];
}
// Dedup before materializing: HashSet<&str> over borrowed slices so
// repeated identifiers do not each allocate a String (#2292).
let mut seen = std::collections::HashSet::new();
let mut tokens: Vec<&str> = Vec::new();
for line in content.lines() {
for ident in extract_identifiers(line) {
if seen.insert(ident) {
tokens.push(ident);
}
}
}
// Also try matching against whole lines for multi-word patterns.
if target.contains(' ') || target.len() > 20 {
for line in content.lines() {
let trimmed = line.trim();
if !trimmed.is_empty() && seen.insert(trimmed) {
tokens.push(trimmed);
}
}
}
find_similar_among(tokens, target, max_results)
}
/// Try anchor-based matching: find the target text using surrounding context lines.
///
/// If `target` is not found exactly, looks for lines that share anchor text
/// (the lines immediately before and after the target in the original context)
/// and returns the matching region.
pub fn anchor_match(
content: &str,
target: &str,
before_context: Option<&str>,
after_context: Option<&str>,
) -> Option<AnchorMatchResult> {
if target.is_empty() {
return None;
}
// If exact match exists, return it directly.
if let Some(pos) = content.find(target) {
return Some(AnchorMatchResult {
matched_text: target.to_string(),
start_offset: pos,
strategy: MatchStrategy::Exact,
score: None,
});
}
// Try anchor-based matching using before/after context.
let lines: Vec<&str> = content.lines().collect();
let target_lines: Vec<&str> = target.lines().collect();
// Compute byte offset of each line start for accurate slicing,
// avoiding CRLF vs LF mismatch (the old code used a global
// heuristic that broke on mixed or CRLF line endings).
let mut line_byte_starts: Vec<usize> = vec![0];
for (i, b) in content.bytes().enumerate() {
if b == b'\n' {
line_byte_starts.push(i + 1);
}
}
if target_lines.is_empty() {
return None;
}
let first_target = target_lines[0].trim();
let last_target = target_lines.last().map(|l| l.trim()).unwrap_or("");
// Anchor matching requires at least one piece of structural context
// (before_context or after_context). Without context, it would
// degenerate into the same Jaro-Winkler line scan that the
// similarity path already does, making the fallback chain redundant.
if before_context.is_none() && after_context.is_none() {
return None;
}
// Find candidate positions by matching the first line with anchors.
for (i, line) in lines.iter().enumerate() {
let trimmed = line.trim();
// Check if this line is similar to the first target line.
if strsim::jaro_winkler(trimmed, first_target) < 0.85 {
continue;
}
// For multi-line targets, also verify the last line of the
// candidate region is similar to the last target line.
if target_lines.len() > 1 {
let end_idx = i + target_lines.len();
if end_idx > lines.len() {
continue;
}
let candidate_last = lines[end_idx - 1].trim();
if strsim::jaro_winkler(candidate_last, last_target) < 0.85 {
continue;
}
}
// If we have before_context, verify the preceding line matches.
// For multi-line context, compare only the last line (the one
// immediately before the target region).
if let Some(before) = before_context {
if i == 0 {
continue;
}
let prev = lines[i - 1].trim();
let before_line = before.lines().last().unwrap_or(before).trim();
if strsim::jaro_winkler(prev, before_line) < 0.8 {
continue;
}
}
// If we have after_context, check the line after the candidate region.
// For multi-line context, compare only the first line (the one
// immediately after the target region).
if let Some(after) = after_context {
let end_idx = i + target_lines.len();
if end_idx >= lines.len() {
continue;
}
let next = lines[end_idx].trim();
let after_line = after.lines().next().unwrap_or(after).trim();
if strsim::jaro_winkler(next, after_line) < 0.8 {
continue;
}
}
// Found a match. Extract the matched region directly from the
// original content so line endings are preserved exactly.
let end_idx = (i + target_lines.len()).min(lines.len());
let start_offset = line_byte_starts[i];
let end_offset = if end_idx < line_byte_starts.len() {
line_byte_starts[end_idx]
} else {
content.len()
};
// Strip exactly one trailing line ending to match the format
// of exact-match results (which carry no trailing newline).
let slice = &content[start_offset..end_offset];
let matched_text = slice
.strip_suffix("\r\n")
.or_else(|| slice.strip_suffix('\n'))
.unwrap_or(slice)
.to_string();
return Some(AnchorMatchResult {
matched_text,
start_offset,
strategy: MatchStrategy::Anchor,
score: None,
});
}
None
}
/// Result of anchor-based matching.
#[derive(Debug, Clone)]
pub struct AnchorMatchResult {
/// The text that was matched.
pub matched_text: String,
/// Byte offset of the match start in the content.
pub start_offset: usize,
/// Which matching strategy succeeded.
pub strategy: MatchStrategy,
/// Similarity score when [`MatchStrategy::Similarity`] succeeded (#1662).
pub score: Option<f64>,
}
/// Which matching strategy found the result.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MatchStrategy {
/// Exact literal match.
Exact,
/// Anchor-based matching using surrounding context.
Anchor,
/// Similarity-based fuzzy matching.
Similarity,
}
impl std::fmt::Display for MatchStrategy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
MatchStrategy::Exact => write!(f, "exact"),
MatchStrategy::Anchor => write!(f, "anchor"),
MatchStrategy::Similarity => write!(f, "similarity"),
}
}
}
/// Run the full fallback chain: exact -> anchor -> similarity -> structured error.
///
/// Returns the first successful match or a structured error with diagnosis.
///
/// Stable 4-arg surface. Callers that already enforced a stricter exact path
/// (for example `--word-boundary`) should use [`resolve_with_fallback_skip_exact`]
/// so bare `find` does not re-accept a substring the primary path rejected.
pub fn resolve_with_fallback(
content: &str,
target: &str,
before_context: Option<&str>,
after_context: Option<&str>,
) -> Result<AnchorMatchResult, EditError> {
resolve_with_fallback_skip_exact(content, target, before_context, after_context, false)
}
/// Like [`resolve_with_fallback`], with control over the bare Exact tier.
///
/// When `skip_exact` is true, bare `find` Exact matching is skipped. Callers that
/// already ran a stricter exact path (for example `--word-boundary`) must set
/// this so fallback does not re-accept a substring that word boundaries rejected
/// (#1755). Similarity and anchor strategies still run (whole-token typo recovery).
pub fn resolve_with_fallback_skip_exact(
content: &str,
target: &str,
before_context: Option<&str>,
after_context: Option<&str>,
skip_exact: bool,
) -> Result<AnchorMatchResult, EditError> {
// Step 1: Exact match (unless caller already enforced a stricter exact path).
if !skip_exact && let Some(pos) = content.find(target) {
return Ok(AnchorMatchResult {
matched_text: target.to_string(),
start_offset: pos,
strategy: MatchStrategy::Exact,
score: None,
});
}
// Step 2: Anchor-based matching.
if let Some(result) = anchor_match(content, target, before_context, after_context) {
// anchor_match may still surface Exact via its own find; reject that when
// the caller asked to skip bare exact (word_boundary).
if !(skip_exact && result.strategy == MatchStrategy::Exact) {
return Ok(result);
}
}
// Step 3: Similarity-based matching (#1694).
//
// Single-token targets (identifiers / typos) must match **tokens**, not whole
// lines. Jaro-Winkler on a full source line vs a short identifier scores high
// because of shared prefixes, then the apply path replaces the entire line and
// deletes surrounding syntax (`const`, types, etc.).
let target_lines: Vec<&str> = target.lines().collect();
if target_lines.len() == 1 {
let target_trim = target.trim();
if is_token_like_target(target_trim) {
if let Some(hit) = best_token_similarity(content, target_trim) {
return Ok(hit);
}
// Do not fall through to whole-line similarity for token-like targets.
} else if let Some(hit) = best_line_similarity(content, target_trim) {
return Ok(hit);
}
}
// Step 4: Structured error with diagnosis.
let similar = find_similar_targets(content, target.lines().next().unwrap_or(target), 5);
let suggestion = if !similar.is_empty() {
Some(format!("did you mean: {}?", similar[0]))
} else {
None
};
Err(EditError {
kind: EditErrorKind::NoMatch,
message: format!("target not found: '{}'", truncate_str(target, 80)),
suggestion,
similar_targets: similar,