Skip to main content

trusty_code/tools/fs/edit_format/
mod.rs

1//! Per-model edit-format selection for the `edit` tool (#2068, P1B-1).
2//!
3//! Why: Aider's A/B data (cited in #2068) shows edit-application success rate
4//! varies a lot by model family for a given wire format: exact-match
5//! SEARCH/REPLACE is the cheapest (fewest tokens) but some models struggle to
6//! reproduce `old_string` byte-for-byte; unified-diff is more forgiving of
7//! minor context drift but costs more tokens to emit; whole-file replacement
8//! is the most robust (no precision needed at all) but the most expensive.
9//! Picking a fixed global order wastes retries on models that reliably fail
10//! their first attempt. [`format_order_for`] centralises a static per-model
11//! preference matrix (Phase 1 — "simple matrix in agent config", full
12//! success-rate learning loop deferred to Phase 2) so the tool can offer
13//! formats in the order most likely to succeed for the calling model,
14//! mirroring the `strategy_order_for` matrix in
15//! `llm::tool_call_extractor` (#1023).
16//! What: [`EditFormat`] names the three supported wire formats; [`EditPayload`]
17//! bundles the format-specific arguments recovered from the LLM's tool call;
18//! [`format_order_for`] returns the per-model fallback order; [`select_and_apply`]
19//! tries the caller-supplied payloads in that order against the current file
20//! content and returns the first one that applies cleanly. [`select_and_apply_for_mode`]
21//! (#2073) is the `HarnessMode`-aware entry point that reconciles this
22//! per-model matrix with vision spec §5.9's Parity/DailyDriver split:
23//! `HarnessMode::DailyDriver` keeps this per-model matrix with full
24//! fallback, unchanged; `HarnessMode::Parity` is STRICT unified-diff only,
25//! with NO fallback to SEARCH/REPLACE or whole-file (owner decision,
26//! 2026-07-07 — see [`apply_parity_diff_only`]'s docs for the
27//! benchmark-fairness rationale).
28//!
29//! ## Per-model format matrix
30//!
31//! | Model family (slug substring) | Fallback order |
32//! |---|---|
33//! | `claude-`, `gpt-`, `gemini-` (flagship, native tool-calling) | SEARCH/REPLACE → unified-diff → whole-file |
34//! | `qwen`, `deepseek` | unified-diff → SEARCH/REPLACE → whole-file |
35//! | everything else (`gemma`, small/unknown models) | whole-file → SEARCH/REPLACE → unified-diff |
36//!
37//! Rationale: flagship models reliably reproduce exact substrings, so the
38//! cheapest format leads. Qwen/DeepSeek's published chat templates and code
39//! training corpora lean heavily on diff-formatted code, so diff application
40//! out-performs exact match for that family (per the Aider leaderboard data
41//! referenced in #2068). Weaker/unknown models frequently botch both
42//! precision-dependent formats, so the most forgiving format (whole-file)
43//! leads for the catch-all bucket. This table is the `HarnessMode::DailyDriver`
44//! behaviour (#2073, §5.9): production, per-model-optimised edit-format
45//! selection with full fallback. `HarnessMode::Parity` does NOT use this
46//! table at all — see [`apply_parity_diff_only`] for its strict,
47//! no-fallback unified-diff-only behaviour.
48//! Test: `tests::format_order_*`, `tests::select_and_apply_*`.
49
50mod diff;
51
52use std::path::Path;
53
54use super::FsError;
55use crate::mode::HarnessMode;
56
57pub(crate) use diff::apply_unified_diff;
58
59/// The three supported edit wire formats.
60///
61/// Why: Callers (the tool's `execute`, tests, and future telemetry) need a
62/// concrete, comparable value naming which format was attempted/succeeded.
63/// What: Mirrors the three formats in #2068's scope.
64/// Test: `tests::display_matches_wire_name`.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum EditFormat {
67    /// Exact-unique string replacement (the pre-#2068 sole format).
68    SearchReplace,
69    /// A unified-diff hunk (or hunks) applied against the file's current content.
70    UnifiedDiff,
71    /// Full-file content replacement.
72    WholeFile,
73}
74
75impl EditFormat {
76    /// The wire/config name used in the matrix table and tool-result messages.
77    fn as_str(self) -> &'static str {
78        match self {
79            EditFormat::SearchReplace => "search_replace",
80            EditFormat::UnifiedDiff => "unified_diff",
81            EditFormat::WholeFile => "whole_file",
82        }
83    }
84}
85
86impl std::fmt::Display for EditFormat {
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        f.write_str(self.as_str())
89    }
90}
91
92/// One candidate edit, in the shape the LLM actually supplied it.
93///
94/// Why: A single tool call may carry more than one representation of the same
95/// edit (e.g. a model hedges with both `old_string`/`new_string` and a `diff`);
96/// [`select_and_apply`] needs a typed payload per format to try in preference
97/// order.
98/// What: Each variant carries exactly the arguments its format needs.
99/// Test: Constructed directly in `edit.rs::execute` from the parsed tool-call
100/// arguments; exercised via `tests::select_and_apply_*`.
101#[derive(Debug, Clone, PartialEq)]
102pub enum EditPayload {
103    /// `old_string` must appear exactly once in the file; replaced with `new_string`.
104    SearchReplace {
105        old_string: String,
106        new_string: String,
107    },
108    /// A unified-diff hunk set to apply against the file's current content.
109    UnifiedDiff { diff: String },
110    /// The complete new content of the file.
111    WholeFile { content: String },
112}
113
114impl EditPayload {
115    /// The [`EditFormat`] this payload represents.
116    fn format(&self) -> EditFormat {
117        match self {
118            EditPayload::SearchReplace { .. } => EditFormat::SearchReplace,
119            EditPayload::UnifiedDiff { .. } => EditFormat::UnifiedDiff,
120            EditPayload::WholeFile { .. } => EditFormat::WholeFile,
121        }
122    }
123}
124
125/// Per-model fallback order for edit-format application, when multiple
126/// candidate payloads are available.
127///
128/// Why: Centralises the matrix documented in the module table above.
129/// What: Returns the three formats in priority order for `model_slug`.
130/// Matching is case-insensitive and substring-based, mirroring
131/// `llm::tool_call_extractor::strategy_order_for`.
132/// Test: `tests::format_order_prefers_search_replace_for_flagship_models`,
133/// `tests::format_order_prefers_unified_diff_for_qwen_and_deepseek`,
134/// `tests::format_order_prefers_whole_file_for_catch_all`.
135pub fn format_order_for(model_slug: &str) -> [EditFormat; 3] {
136    let lower = model_slug.to_ascii_lowercase();
137    if lower.contains("claude-") || lower.contains("gpt-") || lower.contains("gemini-") {
138        [
139            EditFormat::SearchReplace,
140            EditFormat::UnifiedDiff,
141            EditFormat::WholeFile,
142        ]
143    } else if lower.contains("qwen") || lower.contains("deepseek") {
144        [
145            EditFormat::UnifiedDiff,
146            EditFormat::SearchReplace,
147            EditFormat::WholeFile,
148        ]
149    } else {
150        [
151            EditFormat::WholeFile,
152            EditFormat::SearchReplace,
153            EditFormat::UnifiedDiff,
154        ]
155    }
156}
157
158/// Apply an exact-unique string replacement against in-memory `content`.
159///
160/// Why: Shared by [`select_and_apply`]; kept free of file IO so it is testable
161/// without a tempdir.
162/// What: Returns the updated content on success. Errors on 0 or >1 matches,
163/// mirroring the pre-#2068 `EditTool` contract exactly.
164/// Test: `tests::select_and_apply_search_replace_unique_match`,
165/// `tests::select_and_apply_search_replace_zero_and_ambiguous`.
166fn apply_search_replace(
167    content: &str,
168    old_string: &str,
169    new_string: &str,
170    path: &Path,
171) -> Result<String, FsError> {
172    let count = content.matches(old_string).count();
173    match count {
174        0 => Err(FsError::EditNotFound {
175            path: path.to_path_buf(),
176        }),
177        1 => Ok(content.replacen(old_string, new_string, 1)),
178        n => Err(FsError::EditAmbiguous {
179            path: path.to_path_buf(),
180            count: n,
181        }),
182    }
183}
184
185/// Apply one payload against `content`, dispatching on its format.
186fn apply_payload(payload: &EditPayload, content: &str, path: &Path) -> Result<String, FsError> {
187    match payload {
188        EditPayload::SearchReplace {
189            old_string,
190            new_string,
191        } => apply_search_replace(content, old_string, new_string, path),
192        EditPayload::UnifiedDiff { diff } => apply_unified_diff(content, diff, path),
193        EditPayload::WholeFile { content: new } => Ok(new.clone()),
194    }
195}
196
197/// Try `payloads` against `content` in `model_slug`'s preferred format order,
198/// returning the first one that applies cleanly.
199///
200/// Why: This is the fallback-retry loop #2068 asks for: SEARCH/REPLACE first
201/// (for models that prefer it), falling back to unified-diff, then whole-file,
202/// all within a single tool call when the model supplied more than one
203/// representation of the same edit.
204/// What: Iterates [`format_order_for`], and for each preferred format tries
205/// the first payload of that format present in `payloads`; returns
206/// `(updated_content, format_used)` on the first success. If no payload
207/// matches any format (empty `payloads`), or every present payload fails to
208/// apply, returns the last encountered `FsError`.
209/// Test: `tests::select_and_apply_*`.
210pub fn select_and_apply(
211    model_slug: &str,
212    content: &str,
213    path: &Path,
214    payloads: &[EditPayload],
215) -> Result<(String, EditFormat), FsError> {
216    apply_in_order(format_order_for(model_slug), content, path, payloads)
217}
218
219/// `HarnessMode`-aware fallback order for edit-format application (#2073,
220/// §5.9's reconciliation table).
221///
222/// Why: §5.9's table lists Parity's edit-format column as "unified-diff
223/// only", in contrast to DailyDriver's "per-model optimized". An earlier
224/// revision of this function returned a fixed-but-still-falling-back order
225/// (`[UnifiedDiff, SearchReplace, WholeFile]`) for Parity; the owner
226/// tightened that decision (2026-07-07): Parity/Benchmark mode exists to
227/// measure MODELS unforgivingly, and silently rescuing a model that fails
228/// at diff-editing via a SearchReplace/WholeFile fallback defeats that
229/// purpose (M3's model bake-off depends on the stricter reading). Parity is
230/// therefore STRICT unified-diff only — see [`select_and_apply_for_mode`],
231/// which is what actually enforces this (NOT this function — see below).
232/// What: Kept for API-shape parity with [`format_order_for`] and existing
233/// callers that introspect "what would be preferred", but for
234/// `HarnessMode::Parity` this returns `[UnifiedDiff, UnifiedDiff,
235/// UnifiedDiff]` — not a real preference order, since Parity has none —
236/// purely to keep the fixed 3-element return type; `model_slug` is ignored.
237/// `select_and_apply_for_mode`'s `Parity` arm does NOT consult this
238/// function's return value at all; it dispatches through the dedicated,
239/// no-fallback [`apply_parity_diff_only`] instead, so there is exactly ONE
240/// place Parity's strictness is enforced. `HarnessMode::DailyDriver`
241/// delegates to [`format_order_for`] unchanged (the existing per-model
242/// matrix, #2068) and IS still consulted by `select_and_apply_for_mode`.
243/// Test: `tests::format_order_for_mode_parity_is_unified_diff_only`,
244/// `tests::format_order_for_mode_daily_driver_matches_legacy_order`.
245pub fn format_order_for_mode(mode: HarnessMode, model_slug: &str) -> [EditFormat; 3] {
246    match mode {
247        HarnessMode::Parity => [EditFormat::UnifiedDiff; 3],
248        HarnessMode::DailyDriver => format_order_for(model_slug),
249    }
250}
251
252/// `HarnessMode`-aware edit-format dispatch (#2073).
253///
254/// Why: The single call site (`EditTool::edit_inner`) that needs to pick
255/// between DailyDriver's per-model fallback chain and Parity's strict,
256/// no-fallback unified-diff requirement.
257/// What: `HarnessMode::DailyDriver` applies [`format_order_for`] (ignoring
258/// `format_order_for_mode`'s Parity-shaped return entirely for this arm —
259/// it calls the per-model matrix directly) via the shared [`apply_in_order`]
260/// loop, unchanged from pre-#2073 behaviour. `HarnessMode::Parity` ignores
261/// `model_slug` and delegates to [`apply_parity_diff_only`], which accepts
262/// ONLY a supplied `diff` payload — a present `old_string`/`new_string` or
263/// `content` payload is never attempted, even if the diff fails to apply.
264/// Test: `tests::select_and_apply_for_mode_parity_applies_a_valid_diff`,
265/// `tests::select_and_apply_for_mode_parity_errors_without_a_diff_payload`,
266/// `tests::select_and_apply_for_mode_parity_does_not_fall_back_on_diff_failure`,
267/// `tests::select_and_apply_for_mode_daily_driver_still_falls_back_per_model`.
268pub fn select_and_apply_for_mode(
269    mode: HarnessMode,
270    model_slug: &str,
271    content: &str,
272    path: &Path,
273    payloads: &[EditPayload],
274) -> Result<(String, EditFormat), FsError> {
275    match mode {
276        HarnessMode::Parity => apply_parity_diff_only(content, path, payloads),
277        HarnessMode::DailyDriver => {
278            apply_in_order(format_order_for(model_slug), content, path, payloads)
279        }
280    }
281}
282
283/// Strict, no-fallback unified-diff application for `HarnessMode::Parity`
284/// (#2073, owner-tightened 2026-07-07 per vision spec §5.9's literal
285/// "unified-diff only" reading and the benchmark-fairness rationale).
286///
287/// Why: Parity/Benchmark mode exists to measure MODELS, unforgivingly — a
288/// model that cannot produce a valid unified diff must be scored as FAILING
289/// at the edit, not silently rescued by falling back to SEARCH/REPLACE or
290/// whole-file replacement. M3's model bake-off depends on this: a fallback
291/// would let a model "pass" an edit it did not actually demonstrate
292/// diff-editing competence at.
293/// What: Requires a present `EditPayload::UnifiedDiff` in `payloads`; any
294/// other payload present (`SearchReplace`, `WholeFile`) is ignored entirely
295/// and never attempted. Returns [`FsError::ParityDiffRequired`] when no diff
296/// payload was supplied at all. When a diff payload IS present, propagates
297/// `apply_unified_diff`'s own error verbatim on failure (bad hunk header,
298/// context mismatch, …) — NO fallback to another format is attempted even
299/// then. Both outcomes are ordinary recoverable `FsError`s (never a panic),
300/// so the model sees a clear message and can retry with a corrected diff,
301/// scored as a failed attempt in the interim.
302/// Test: `tests::select_and_apply_for_mode_parity_applies_a_valid_diff`,
303/// `tests::select_and_apply_for_mode_parity_errors_without_a_diff_payload`,
304/// `tests::select_and_apply_for_mode_parity_does_not_fall_back_on_diff_failure`.
305fn apply_parity_diff_only(
306    content: &str,
307    path: &Path,
308    payloads: &[EditPayload],
309) -> Result<(String, EditFormat), FsError> {
310    let diff_payload = payloads
311        .iter()
312        .find(|p| p.format() == EditFormat::UnifiedDiff);
313
314    let Some(EditPayload::UnifiedDiff { diff }) = diff_payload else {
315        return Err(FsError::ParityDiffRequired {
316            path: path.to_path_buf(),
317        });
318    };
319
320    apply_unified_diff(content, diff, path).map(|updated| (updated, EditFormat::UnifiedDiff))
321}
322
323/// Shared apply loop behind both [`select_and_apply`] and
324/// [`select_and_apply_for_mode`].
325///
326/// Why: Both public entry points differ only in how they compute the
327/// preference order; centralising the loop keeps that the ONLY difference.
328/// What: Tries each format in `order`, applying the first present payload
329/// that succeeds; returns the last error if none apply, or `EditNotFound` if
330/// `payloads` never contained any of `order`'s formats.
331/// Test: Exercised transitively by every `select_and_apply*` test.
332fn apply_in_order(
333    order: [EditFormat; 3],
334    content: &str,
335    path: &Path,
336    payloads: &[EditPayload],
337) -> Result<(String, EditFormat), FsError> {
338    let mut last_err: Option<FsError> = None;
339
340    for format in order {
341        let Some(payload) = payloads.iter().find(|p| p.format() == format) else {
342            continue;
343        };
344        match apply_payload(payload, content, path) {
345            Ok(updated) => return Ok((updated, format)),
346            Err(e) => last_err = Some(e),
347        }
348    }
349
350    Err(last_err.unwrap_or_else(|| FsError::EditNotFound {
351        path: path.to_path_buf(),
352    }))
353}
354
355// ── Tests ─────────────────────────────────────────────────────────────────────
356
357#[cfg(test)]
358mod tests {
359    use std::path::Path;
360
361    use super::*;
362
363    /// `Display` renders the wire-format name used in tool-result messages.
364    #[test]
365    fn display_matches_wire_name() {
366        assert_eq!(EditFormat::SearchReplace.to_string(), "search_replace");
367        assert_eq!(EditFormat::UnifiedDiff.to_string(), "unified_diff");
368        assert_eq!(EditFormat::WholeFile.to_string(), "whole_file");
369    }
370
371    /// Flagship native-tool-calling families prefer SEARCH/REPLACE first.
372    #[test]
373    fn format_order_prefers_search_replace_for_flagship_models() {
374        for slug in [
375            "anthropic/claude-opus-4-5",
376            "openai/gpt-4o",
377            "google/gemini-2.5-pro",
378        ] {
379            assert_eq!(
380                format_order_for(slug),
381                [
382                    EditFormat::SearchReplace,
383                    EditFormat::UnifiedDiff,
384                    EditFormat::WholeFile
385                ],
386                "unexpected order for {slug}"
387            );
388        }
389    }
390
391    /// Qwen/DeepSeek prefer unified-diff first.
392    #[test]
393    fn format_order_prefers_unified_diff_for_qwen_and_deepseek() {
394        for slug in ["qwen/qwen-2.5-72b-instruct", "deepseek/deepseek-chat"] {
395            assert_eq!(
396                format_order_for(slug),
397                [
398                    EditFormat::UnifiedDiff,
399                    EditFormat::SearchReplace,
400                    EditFormat::WholeFile
401                ],
402                "unexpected order for {slug}"
403            );
404        }
405    }
406
407    /// The catch-all bucket (gemma, unknown, empty slug) prefers whole-file first.
408    #[test]
409    fn format_order_prefers_whole_file_for_catch_all() {
410        for slug in ["google/gemma-2-9b-it", "some/unknown-model", ""] {
411            assert_eq!(
412                format_order_for(slug),
413                [
414                    EditFormat::WholeFile,
415                    EditFormat::SearchReplace,
416                    EditFormat::UnifiedDiff
417                ],
418                "unexpected order for {slug}"
419            );
420        }
421    }
422
423    /// A single `SearchReplace` payload applies regardless of model order.
424    #[test]
425    fn select_and_apply_search_replace_unique_match() {
426        let payloads = [EditPayload::SearchReplace {
427            old_string: "foo".into(),
428            new_string: "bar".into(),
429        }];
430        // Even under the whole-file-first catch-all order, the only payload
431        // present (SearchReplace) must still be the one applied.
432        let (updated, format) =
433            select_and_apply("unknown-model", "foo baz", Path::new("f.py"), &payloads)
434                .expect("unique match must apply");
435        assert_eq!(updated, "bar baz");
436        assert_eq!(format, EditFormat::SearchReplace);
437    }
438
439    /// Zero and ambiguous matches surface the same errors as the legacy tool.
440    #[test]
441    fn select_and_apply_search_replace_zero_and_ambiguous() {
442        let zero = [EditPayload::SearchReplace {
443            old_string: "missing".into(),
444            new_string: "x".into(),
445        }];
446        let err = select_and_apply("claude-opus", "content", Path::new("f.py"), &zero)
447            .expect_err("zero matches must error");
448        assert!(matches!(err, FsError::EditNotFound { .. }));
449
450        let ambiguous = [EditPayload::SearchReplace {
451            old_string: "dup".into(),
452            new_string: "x".into(),
453        }];
454        let err = select_and_apply("claude-opus", "dup dup", Path::new("f.py"), &ambiguous)
455            .expect_err("ambiguous matches must error");
456        assert!(matches!(err, FsError::EditAmbiguous { count: 2, .. }));
457    }
458
459    /// A `WholeFile` payload always applies, replacing the entire content.
460    #[test]
461    fn select_and_apply_whole_file_replaces_everything() {
462        let payloads = [EditPayload::WholeFile {
463            content: "brand new content\n".into(),
464        }];
465        let (updated, format) =
466            select_and_apply("claude-opus", "old content\n", Path::new("f.py"), &payloads)
467                .expect("whole-file must always apply");
468        assert_eq!(updated, "brand new content\n");
469        assert_eq!(format, EditFormat::WholeFile);
470    }
471
472    /// When the top-preference payload fails to apply, `select_and_apply`
473    /// falls back to the next preferred format present in `payloads`.
474    #[test]
475    fn select_and_apply_falls_back_on_failure() {
476        // Flagship order is SearchReplace -> UnifiedDiff -> WholeFile. Give a
477        // SearchReplace payload that cannot match, plus a WholeFile payload
478        // that always can; expect the fallback to WholeFile.
479        let payloads = [
480            EditPayload::SearchReplace {
481                old_string: "not-present".into(),
482                new_string: "x".into(),
483            },
484            EditPayload::WholeFile {
485                content: "fallback content\n".into(),
486            },
487        ];
488        let (updated, format) = select_and_apply(
489            "anthropic/claude-opus-4-5",
490            "orig\n",
491            Path::new("f.py"),
492            &payloads,
493        )
494        .expect("must fall back to whole-file");
495        assert_eq!(updated, "fallback content\n");
496        assert_eq!(format, EditFormat::WholeFile);
497    }
498
499    /// Empty `payloads` is a clear error, not a panic.
500    #[test]
501    fn select_and_apply_empty_payloads_errors() {
502        let err = select_and_apply("claude-opus", "content", Path::new("f.py"), &[])
503            .expect_err("no payloads must error");
504        assert!(matches!(err, FsError::EditNotFound { .. }));
505    }
506
507    /// `HarnessMode::Parity` returns `[UnifiedDiff, UnifiedDiff, UnifiedDiff]`
508    /// regardless of `model_slug` (#2073, tightened 2026-07-07) — reflects
509    /// that Parity has no real fallback order at all; `model_slug` is
510    /// ignored entirely.
511    #[test]
512    fn format_order_for_mode_parity_is_unified_diff_only() {
513        let expected = [
514            EditFormat::UnifiedDiff,
515            EditFormat::UnifiedDiff,
516            EditFormat::UnifiedDiff,
517        ];
518        for slug in [
519            "anthropic/claude-opus-4-5",
520            "qwen/qwen-2.5-72b-instruct",
521            "google/gemma-2-9b-it",
522            "",
523        ] {
524            assert_eq!(
525                format_order_for_mode(HarnessMode::Parity, slug),
526                expected,
527                "Parity must report unified-diff-only for {slug}"
528            );
529        }
530    }
531
532    /// `HarnessMode::DailyDriver` delegates verbatim to the pre-#2073
533    /// per-model matrix (#2068) — no behavioural change for the production
534    /// default.
535    #[test]
536    fn format_order_for_mode_daily_driver_matches_legacy_order() {
537        for slug in [
538            "anthropic/claude-opus-4-5",
539            "qwen/qwen-2.5-72b-instruct",
540            "google/gemma-2-9b-it",
541        ] {
542            assert_eq!(
543                format_order_for_mode(HarnessMode::DailyDriver, slug),
544                format_order_for(slug),
545                "DailyDriver order must match the legacy per-model matrix for {slug}"
546            );
547        }
548    }
549
550    /// A valid `diff` payload applies cleanly under Parity, even alongside a
551    /// SEARCH/REPLACE payload that would otherwise win under a flagship
552    /// model's DailyDriver order — Parity must use ONLY the diff, never even
553    /// consider the other payload (#2073, tightened 2026-07-07).
554    #[test]
555    fn select_and_apply_for_mode_parity_applies_a_valid_diff() {
556        let payloads = [
557            EditPayload::SearchReplace {
558                old_string: "line2".into(),
559                new_string: "replaced".into(),
560            },
561            EditPayload::UnifiedDiff {
562                diff: "@@ -2,1 +2,1 @@\n-line2\n+line2-diffed\n".into(),
563            },
564        ];
565        let (updated, format) = select_and_apply_for_mode(
566            HarnessMode::Parity,
567            "anthropic/claude-opus-4-5",
568            "line1\nline2\n",
569            Path::new("f.py"),
570            &payloads,
571        )
572        .expect("unified diff must apply");
573        assert_eq!(format, EditFormat::UnifiedDiff);
574        assert_eq!(updated, "line1\nline2-diffed\n");
575    }
576
577    /// Parity with NO diff payload supplied — only SEARCH/REPLACE or
578    /// whole-file — must return a recoverable `FsError::ParityDiffRequired`,
579    /// NOT silently fall back and succeed (#2073, tightened 2026-07-07: the
580    /// owner's benchmark-fairness decision — a model that never emitted a
581    /// diff must be scored as failing the edit).
582    #[test]
583    fn select_and_apply_for_mode_parity_errors_without_a_diff_payload() {
584        let payloads = [EditPayload::WholeFile {
585            content: "brand new\n".into(),
586        }];
587        let err = select_and_apply_for_mode(
588            HarnessMode::Parity,
589            "anthropic/claude-opus-4-5",
590            "old\n",
591            Path::new("f.py"),
592            &payloads,
593        )
594        .expect_err("Parity must reject a run with no diff payload");
595        assert!(
596            matches!(err, FsError::ParityDiffRequired { .. }),
597            "expected ParityDiffRequired, got {err:?}"
598        );
599        assert!(
600            err.to_string()
601                .contains("Parity mode requires a unified-diff edit"),
602            "error message must make the Parity requirement clear: {err}"
603        );
604    }
605
606    /// Parity with a PRESENT but inapplicable diff (bad hunk/context
607    /// mismatch), plus a whole-file payload that WOULD otherwise succeed,
608    /// must still fail — no fallback to the whole-file payload is attempted
609    /// even when the diff itself is the one that failed (#2073, tightened
610    /// 2026-07-07).
611    #[test]
612    fn select_and_apply_for_mode_parity_does_not_fall_back_on_diff_failure() {
613        let payloads = [
614            EditPayload::UnifiedDiff {
615                diff: "@@ -99,1 +99,1 @@\n-nonexistent-line\n+replacement\n".into(),
616            },
617            EditPayload::WholeFile {
618                content: "would-have-worked\n".into(),
619            },
620        ];
621        let err = select_and_apply_for_mode(
622            HarnessMode::Parity,
623            "anthropic/claude-opus-4-5",
624            "line1\nline2\n",
625            Path::new("f.py"),
626            &payloads,
627        )
628        .expect_err("an inapplicable diff must error, not fall back to whole-file");
629        assert!(
630            matches!(
631                err,
632                FsError::DiffContextMismatch { .. } | FsError::DiffHunkHeader { .. }
633            ),
634            "expected a diff-application error (not a fallback success), got {err:?}"
635        );
636    }
637
638    /// `HarnessMode::DailyDriver` still falls back per-model exactly as
639    /// before #2073 tightened Parity — guards against accidentally
640    /// tightening the wrong mode.
641    #[test]
642    fn select_and_apply_for_mode_daily_driver_still_falls_back_per_model() {
643        let payloads = [
644            EditPayload::SearchReplace {
645                old_string: "not-present".into(),
646                new_string: "x".into(),
647            },
648            EditPayload::WholeFile {
649                content: "fallback content\n".into(),
650            },
651        ];
652        // Flagship order is SearchReplace -> UnifiedDiff -> WholeFile; the
653        // non-matching SearchReplace payload must fall through to WholeFile.
654        let (updated, format) = select_and_apply_for_mode(
655            HarnessMode::DailyDriver,
656            "anthropic/claude-opus-4-5",
657            "orig\n",
658            Path::new("f.py"),
659            &payloads,
660        )
661        .expect("DailyDriver must still fall back to whole-file");
662        assert_eq!(format, EditFormat::WholeFile);
663        assert_eq!(updated, "fallback content\n");
664    }
665}