trusty-code 0.5.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
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
//! Per-model edit-format selection for the `edit` tool (#2068, P1B-1).
//!
//! Why: Aider's A/B data (cited in #2068) shows edit-application success rate
//! varies a lot by model family for a given wire format: exact-match
//! SEARCH/REPLACE is the cheapest (fewest tokens) but some models struggle to
//! reproduce `old_string` byte-for-byte; unified-diff is more forgiving of
//! minor context drift but costs more tokens to emit; whole-file replacement
//! is the most robust (no precision needed at all) but the most expensive.
//! Picking a fixed global order wastes retries on models that reliably fail
//! their first attempt. [`format_order_for`] centralises a static per-model
//! preference matrix (Phase 1 — "simple matrix in agent config", full
//! success-rate learning loop deferred to Phase 2) so the tool can offer
//! formats in the order most likely to succeed for the calling model,
//! mirroring the `strategy_order_for` matrix in
//! `llm::tool_call_extractor` (#1023).
//! What: [`EditFormat`] names the three supported wire formats; [`EditPayload`]
//! bundles the format-specific arguments recovered from the LLM's tool call;
//! [`format_order_for`] returns the per-model fallback order; [`select_and_apply`]
//! tries the caller-supplied payloads in that order against the current file
//! content and returns the first one that applies cleanly. [`select_and_apply_for_mode`]
//! (#2073) is the `HarnessMode`-aware entry point that reconciles this
//! per-model matrix with vision spec §5.9's Parity/DailyDriver split:
//! `HarnessMode::DailyDriver` keeps this per-model matrix with full
//! fallback, unchanged; `HarnessMode::Parity` is STRICT unified-diff only,
//! with NO fallback to SEARCH/REPLACE or whole-file (owner decision,
//! 2026-07-07 — see [`apply_parity_diff_only`]'s docs for the
//! benchmark-fairness rationale).
//!
//! ## Per-model format matrix
//!
//! | Model family (slug substring) | Fallback order |
//! |---|---|
//! | `claude-`, `gpt-`, `gemini-` (flagship, native tool-calling) | SEARCH/REPLACE → unified-diff → whole-file |
//! | `qwen`, `deepseek` | unified-diff → SEARCH/REPLACE → whole-file |
//! | everything else (`gemma`, small/unknown models) | whole-file → SEARCH/REPLACE → unified-diff |
//!
//! Rationale: flagship models reliably reproduce exact substrings, so the
//! cheapest format leads. Qwen/DeepSeek's published chat templates and code
//! training corpora lean heavily on diff-formatted code, so diff application
//! out-performs exact match for that family (per the Aider leaderboard data
//! referenced in #2068). Weaker/unknown models frequently botch both
//! precision-dependent formats, so the most forgiving format (whole-file)
//! leads for the catch-all bucket. This table is the `HarnessMode::DailyDriver`
//! behaviour (#2073, §5.9): production, per-model-optimised edit-format
//! selection with full fallback. `HarnessMode::Parity` does NOT use this
//! table at all — see [`apply_parity_diff_only`] for its strict,
//! no-fallback unified-diff-only behaviour.
//! Test: `tests::format_order_*`, `tests::select_and_apply_*`.

mod diff;

use std::path::Path;

use super::FsError;
use crate::mode::HarnessMode;

pub(crate) use diff::apply_unified_diff;

/// The three supported edit wire formats.
///
/// Why: Callers (the tool's `execute`, tests, and future telemetry) need a
/// concrete, comparable value naming which format was attempted/succeeded.
/// What: Mirrors the three formats in #2068's scope.
/// Test: `tests::display_matches_wire_name`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditFormat {
    /// Exact-unique string replacement (the pre-#2068 sole format).
    SearchReplace,
    /// A unified-diff hunk (or hunks) applied against the file's current content.
    UnifiedDiff,
    /// Full-file content replacement.
    WholeFile,
}

impl EditFormat {
    /// The wire/config name used in the matrix table and tool-result messages.
    fn as_str(self) -> &'static str {
        match self {
            EditFormat::SearchReplace => "search_replace",
            EditFormat::UnifiedDiff => "unified_diff",
            EditFormat::WholeFile => "whole_file",
        }
    }
}

impl std::fmt::Display for EditFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One candidate edit, in the shape the LLM actually supplied it.
///
/// Why: A single tool call may carry more than one representation of the same
/// edit (e.g. a model hedges with both `old_string`/`new_string` and a `diff`);
/// [`select_and_apply`] needs a typed payload per format to try in preference
/// order.
/// What: Each variant carries exactly the arguments its format needs.
/// Test: Constructed directly in `edit.rs::execute` from the parsed tool-call
/// arguments; exercised via `tests::select_and_apply_*`.
#[derive(Debug, Clone, PartialEq)]
pub enum EditPayload {
    /// `old_string` must appear exactly once in the file; replaced with `new_string`.
    SearchReplace {
        old_string: String,
        new_string: String,
    },
    /// A unified-diff hunk set to apply against the file's current content.
    UnifiedDiff { diff: String },
    /// The complete new content of the file.
    WholeFile { content: String },
}

impl EditPayload {
    /// The [`EditFormat`] this payload represents.
    fn format(&self) -> EditFormat {
        match self {
            EditPayload::SearchReplace { .. } => EditFormat::SearchReplace,
            EditPayload::UnifiedDiff { .. } => EditFormat::UnifiedDiff,
            EditPayload::WholeFile { .. } => EditFormat::WholeFile,
        }
    }
}

/// Per-model fallback order for edit-format application, when multiple
/// candidate payloads are available.
///
/// Why: Centralises the matrix documented in the module table above.
/// What: Returns the three formats in priority order for `model_slug`.
/// Matching is case-insensitive and substring-based, mirroring
/// `llm::tool_call_extractor::strategy_order_for`.
/// Test: `tests::format_order_prefers_search_replace_for_flagship_models`,
/// `tests::format_order_prefers_unified_diff_for_qwen_and_deepseek`,
/// `tests::format_order_prefers_whole_file_for_catch_all`.
pub fn format_order_for(model_slug: &str) -> [EditFormat; 3] {
    let lower = model_slug.to_ascii_lowercase();
    if lower.contains("claude-") || lower.contains("gpt-") || lower.contains("gemini-") {
        [
            EditFormat::SearchReplace,
            EditFormat::UnifiedDiff,
            EditFormat::WholeFile,
        ]
    } else if lower.contains("qwen") || lower.contains("deepseek") {
        [
            EditFormat::UnifiedDiff,
            EditFormat::SearchReplace,
            EditFormat::WholeFile,
        ]
    } else {
        [
            EditFormat::WholeFile,
            EditFormat::SearchReplace,
            EditFormat::UnifiedDiff,
        ]
    }
}

/// Apply an exact-unique string replacement against in-memory `content`.
///
/// Why: Shared by [`select_and_apply`]; kept free of file IO so it is testable
/// without a tempdir.
/// What: Returns the updated content on success. Errors on 0 or >1 matches,
/// mirroring the pre-#2068 `EditTool` contract exactly.
/// Test: `tests::select_and_apply_search_replace_unique_match`,
/// `tests::select_and_apply_search_replace_zero_and_ambiguous`.
fn apply_search_replace(
    content: &str,
    old_string: &str,
    new_string: &str,
    path: &Path,
) -> Result<String, FsError> {
    let count = content.matches(old_string).count();
    match count {
        0 => Err(FsError::EditNotFound {
            path: path.to_path_buf(),
        }),
        1 => Ok(content.replacen(old_string, new_string, 1)),
        n => Err(FsError::EditAmbiguous {
            path: path.to_path_buf(),
            count: n,
        }),
    }
}

/// Apply one payload against `content`, dispatching on its format.
fn apply_payload(payload: &EditPayload, content: &str, path: &Path) -> Result<String, FsError> {
    match payload {
        EditPayload::SearchReplace {
            old_string,
            new_string,
        } => apply_search_replace(content, old_string, new_string, path),
        EditPayload::UnifiedDiff { diff } => apply_unified_diff(content, diff, path),
        EditPayload::WholeFile { content: new } => Ok(new.clone()),
    }
}

/// Try `payloads` against `content` in `model_slug`'s preferred format order,
/// returning the first one that applies cleanly.
///
/// Why: This is the fallback-retry loop #2068 asks for: SEARCH/REPLACE first
/// (for models that prefer it), falling back to unified-diff, then whole-file,
/// all within a single tool call when the model supplied more than one
/// representation of the same edit.
/// What: Iterates [`format_order_for`], and for each preferred format tries
/// the first payload of that format present in `payloads`; returns
/// `(updated_content, format_used)` on the first success. If no payload
/// matches any format (empty `payloads`), or every present payload fails to
/// apply, returns the last encountered `FsError`.
/// Test: `tests::select_and_apply_*`.
pub fn select_and_apply(
    model_slug: &str,
    content: &str,
    path: &Path,
    payloads: &[EditPayload],
) -> Result<(String, EditFormat), FsError> {
    apply_in_order(format_order_for(model_slug), content, path, payloads)
}

/// `HarnessMode`-aware fallback order for edit-format application (#2073,
/// §5.9's reconciliation table).
///
/// Why: §5.9's table lists Parity's edit-format column as "unified-diff
/// only", in contrast to DailyDriver's "per-model optimized". An earlier
/// revision of this function returned a fixed-but-still-falling-back order
/// (`[UnifiedDiff, SearchReplace, WholeFile]`) for Parity; the owner
/// tightened that decision (2026-07-07): Parity/Benchmark mode exists to
/// measure MODELS unforgivingly, and silently rescuing a model that fails
/// at diff-editing via a SearchReplace/WholeFile fallback defeats that
/// purpose (M3's model bake-off depends on the stricter reading). Parity is
/// therefore STRICT unified-diff only — see [`select_and_apply_for_mode`],
/// which is what actually enforces this (NOT this function — see below).
/// What: Kept for API-shape parity with [`format_order_for`] and existing
/// callers that introspect "what would be preferred", but for
/// `HarnessMode::Parity` this returns `[UnifiedDiff, UnifiedDiff,
/// UnifiedDiff]` — not a real preference order, since Parity has none —
/// purely to keep the fixed 3-element return type; `model_slug` is ignored.
/// `select_and_apply_for_mode`'s `Parity` arm does NOT consult this
/// function's return value at all; it dispatches through the dedicated,
/// no-fallback [`apply_parity_diff_only`] instead, so there is exactly ONE
/// place Parity's strictness is enforced. `HarnessMode::DailyDriver`
/// delegates to [`format_order_for`] unchanged (the existing per-model
/// matrix, #2068) and IS still consulted by `select_and_apply_for_mode`.
/// Test: `tests::format_order_for_mode_parity_is_unified_diff_only`,
/// `tests::format_order_for_mode_daily_driver_matches_legacy_order`.
pub fn format_order_for_mode(mode: HarnessMode, model_slug: &str) -> [EditFormat; 3] {
    match mode {
        HarnessMode::Parity => [EditFormat::UnifiedDiff; 3],
        HarnessMode::DailyDriver => format_order_for(model_slug),
    }
}

/// `HarnessMode`-aware edit-format dispatch (#2073).
///
/// Why: The single call site (`EditTool::edit_inner`) that needs to pick
/// between DailyDriver's per-model fallback chain and Parity's strict,
/// no-fallback unified-diff requirement.
/// What: `HarnessMode::DailyDriver` applies [`format_order_for`] (ignoring
/// `format_order_for_mode`'s Parity-shaped return entirely for this arm —
/// it calls the per-model matrix directly) via the shared [`apply_in_order`]
/// loop, unchanged from pre-#2073 behaviour. `HarnessMode::Parity` ignores
/// `model_slug` and delegates to [`apply_parity_diff_only`], which accepts
/// ONLY a supplied `diff` payload — a present `old_string`/`new_string` or
/// `content` payload is never attempted, even if the diff fails to apply.
/// Test: `tests::select_and_apply_for_mode_parity_applies_a_valid_diff`,
/// `tests::select_and_apply_for_mode_parity_errors_without_a_diff_payload`,
/// `tests::select_and_apply_for_mode_parity_does_not_fall_back_on_diff_failure`,
/// `tests::select_and_apply_for_mode_daily_driver_still_falls_back_per_model`.
pub fn select_and_apply_for_mode(
    mode: HarnessMode,
    model_slug: &str,
    content: &str,
    path: &Path,
    payloads: &[EditPayload],
) -> Result<(String, EditFormat), FsError> {
    match mode {
        HarnessMode::Parity => apply_parity_diff_only(content, path, payloads),
        HarnessMode::DailyDriver => {
            apply_in_order(format_order_for(model_slug), content, path, payloads)
        }
    }
}

/// Strict, no-fallback unified-diff application for `HarnessMode::Parity`
/// (#2073, owner-tightened 2026-07-07 per vision spec §5.9's literal
/// "unified-diff only" reading and the benchmark-fairness rationale).
///
/// Why: Parity/Benchmark mode exists to measure MODELS, unforgivingly — a
/// model that cannot produce a valid unified diff must be scored as FAILING
/// at the edit, not silently rescued by falling back to SEARCH/REPLACE or
/// whole-file replacement. M3's model bake-off depends on this: a fallback
/// would let a model "pass" an edit it did not actually demonstrate
/// diff-editing competence at.
/// What: Requires a present `EditPayload::UnifiedDiff` in `payloads`; any
/// other payload present (`SearchReplace`, `WholeFile`) is ignored entirely
/// and never attempted. Returns [`FsError::ParityDiffRequired`] when no diff
/// payload was supplied at all. When a diff payload IS present, propagates
/// `apply_unified_diff`'s own error verbatim on failure (bad hunk header,
/// context mismatch, …) — NO fallback to another format is attempted even
/// then. Both outcomes are ordinary recoverable `FsError`s (never a panic),
/// so the model sees a clear message and can retry with a corrected diff,
/// scored as a failed attempt in the interim.
/// Test: `tests::select_and_apply_for_mode_parity_applies_a_valid_diff`,
/// `tests::select_and_apply_for_mode_parity_errors_without_a_diff_payload`,
/// `tests::select_and_apply_for_mode_parity_does_not_fall_back_on_diff_failure`.
fn apply_parity_diff_only(
    content: &str,
    path: &Path,
    payloads: &[EditPayload],
) -> Result<(String, EditFormat), FsError> {
    let diff_payload = payloads
        .iter()
        .find(|p| p.format() == EditFormat::UnifiedDiff);

    let Some(EditPayload::UnifiedDiff { diff }) = diff_payload else {
        return Err(FsError::ParityDiffRequired {
            path: path.to_path_buf(),
        });
    };

    apply_unified_diff(content, diff, path).map(|updated| (updated, EditFormat::UnifiedDiff))
}

/// Shared apply loop behind both [`select_and_apply`] and
/// [`select_and_apply_for_mode`].
///
/// Why: Both public entry points differ only in how they compute the
/// preference order; centralising the loop keeps that the ONLY difference.
/// What: Tries each format in `order`, applying the first present payload
/// that succeeds; returns the last error if none apply, or `EditNotFound` if
/// `payloads` never contained any of `order`'s formats.
/// Test: Exercised transitively by every `select_and_apply*` test.
fn apply_in_order(
    order: [EditFormat; 3],
    content: &str,
    path: &Path,
    payloads: &[EditPayload],
) -> Result<(String, EditFormat), FsError> {
    let mut last_err: Option<FsError> = None;

    for format in order {
        let Some(payload) = payloads.iter().find(|p| p.format() == format) else {
            continue;
        };
        match apply_payload(payload, content, path) {
            Ok(updated) => return Ok((updated, format)),
            Err(e) => last_err = Some(e),
        }
    }

    Err(last_err.unwrap_or_else(|| FsError::EditNotFound {
        path: path.to_path_buf(),
    }))
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::*;

    /// `Display` renders the wire-format name used in tool-result messages.
    #[test]
    fn display_matches_wire_name() {
        assert_eq!(EditFormat::SearchReplace.to_string(), "search_replace");
        assert_eq!(EditFormat::UnifiedDiff.to_string(), "unified_diff");
        assert_eq!(EditFormat::WholeFile.to_string(), "whole_file");
    }

    /// Flagship native-tool-calling families prefer SEARCH/REPLACE first.
    #[test]
    fn format_order_prefers_search_replace_for_flagship_models() {
        for slug in [
            "anthropic/claude-opus-4-5",
            "openai/gpt-4o",
            "google/gemini-2.5-pro",
        ] {
            assert_eq!(
                format_order_for(slug),
                [
                    EditFormat::SearchReplace,
                    EditFormat::UnifiedDiff,
                    EditFormat::WholeFile
                ],
                "unexpected order for {slug}"
            );
        }
    }

    /// Qwen/DeepSeek prefer unified-diff first.
    #[test]
    fn format_order_prefers_unified_diff_for_qwen_and_deepseek() {
        for slug in ["qwen/qwen-2.5-72b-instruct", "deepseek/deepseek-chat"] {
            assert_eq!(
                format_order_for(slug),
                [
                    EditFormat::UnifiedDiff,
                    EditFormat::SearchReplace,
                    EditFormat::WholeFile
                ],
                "unexpected order for {slug}"
            );
        }
    }

    /// The catch-all bucket (gemma, unknown, empty slug) prefers whole-file first.
    #[test]
    fn format_order_prefers_whole_file_for_catch_all() {
        for slug in ["google/gemma-2-9b-it", "some/unknown-model", ""] {
            assert_eq!(
                format_order_for(slug),
                [
                    EditFormat::WholeFile,
                    EditFormat::SearchReplace,
                    EditFormat::UnifiedDiff
                ],
                "unexpected order for {slug}"
            );
        }
    }

    /// A single `SearchReplace` payload applies regardless of model order.
    #[test]
    fn select_and_apply_search_replace_unique_match() {
        let payloads = [EditPayload::SearchReplace {
            old_string: "foo".into(),
            new_string: "bar".into(),
        }];
        // Even under the whole-file-first catch-all order, the only payload
        // present (SearchReplace) must still be the one applied.
        let (updated, format) =
            select_and_apply("unknown-model", "foo baz", Path::new("f.py"), &payloads)
                .expect("unique match must apply");
        assert_eq!(updated, "bar baz");
        assert_eq!(format, EditFormat::SearchReplace);
    }

    /// Zero and ambiguous matches surface the same errors as the legacy tool.
    #[test]
    fn select_and_apply_search_replace_zero_and_ambiguous() {
        let zero = [EditPayload::SearchReplace {
            old_string: "missing".into(),
            new_string: "x".into(),
        }];
        let err = select_and_apply("claude-opus", "content", Path::new("f.py"), &zero)
            .expect_err("zero matches must error");
        assert!(matches!(err, FsError::EditNotFound { .. }));

        let ambiguous = [EditPayload::SearchReplace {
            old_string: "dup".into(),
            new_string: "x".into(),
        }];
        let err = select_and_apply("claude-opus", "dup dup", Path::new("f.py"), &ambiguous)
            .expect_err("ambiguous matches must error");
        assert!(matches!(err, FsError::EditAmbiguous { count: 2, .. }));
    }

    /// A `WholeFile` payload always applies, replacing the entire content.
    #[test]
    fn select_and_apply_whole_file_replaces_everything() {
        let payloads = [EditPayload::WholeFile {
            content: "brand new content\n".into(),
        }];
        let (updated, format) =
            select_and_apply("claude-opus", "old content\n", Path::new("f.py"), &payloads)
                .expect("whole-file must always apply");
        assert_eq!(updated, "brand new content\n");
        assert_eq!(format, EditFormat::WholeFile);
    }

    /// When the top-preference payload fails to apply, `select_and_apply`
    /// falls back to the next preferred format present in `payloads`.
    #[test]
    fn select_and_apply_falls_back_on_failure() {
        // Flagship order is SearchReplace -> UnifiedDiff -> WholeFile. Give a
        // SearchReplace payload that cannot match, plus a WholeFile payload
        // that always can; expect the fallback to WholeFile.
        let payloads = [
            EditPayload::SearchReplace {
                old_string: "not-present".into(),
                new_string: "x".into(),
            },
            EditPayload::WholeFile {
                content: "fallback content\n".into(),
            },
        ];
        let (updated, format) = select_and_apply(
            "anthropic/claude-opus-4-5",
            "orig\n",
            Path::new("f.py"),
            &payloads,
        )
        .expect("must fall back to whole-file");
        assert_eq!(updated, "fallback content\n");
        assert_eq!(format, EditFormat::WholeFile);
    }

    /// Empty `payloads` is a clear error, not a panic.
    #[test]
    fn select_and_apply_empty_payloads_errors() {
        let err = select_and_apply("claude-opus", "content", Path::new("f.py"), &[])
            .expect_err("no payloads must error");
        assert!(matches!(err, FsError::EditNotFound { .. }));
    }

    /// `HarnessMode::Parity` returns `[UnifiedDiff, UnifiedDiff, UnifiedDiff]`
    /// regardless of `model_slug` (#2073, tightened 2026-07-07) — reflects
    /// that Parity has no real fallback order at all; `model_slug` is
    /// ignored entirely.
    #[test]
    fn format_order_for_mode_parity_is_unified_diff_only() {
        let expected = [
            EditFormat::UnifiedDiff,
            EditFormat::UnifiedDiff,
            EditFormat::UnifiedDiff,
        ];
        for slug in [
            "anthropic/claude-opus-4-5",
            "qwen/qwen-2.5-72b-instruct",
            "google/gemma-2-9b-it",
            "",
        ] {
            assert_eq!(
                format_order_for_mode(HarnessMode::Parity, slug),
                expected,
                "Parity must report unified-diff-only for {slug}"
            );
        }
    }

    /// `HarnessMode::DailyDriver` delegates verbatim to the pre-#2073
    /// per-model matrix (#2068) — no behavioural change for the production
    /// default.
    #[test]
    fn format_order_for_mode_daily_driver_matches_legacy_order() {
        for slug in [
            "anthropic/claude-opus-4-5",
            "qwen/qwen-2.5-72b-instruct",
            "google/gemma-2-9b-it",
        ] {
            assert_eq!(
                format_order_for_mode(HarnessMode::DailyDriver, slug),
                format_order_for(slug),
                "DailyDriver order must match the legacy per-model matrix for {slug}"
            );
        }
    }

    /// A valid `diff` payload applies cleanly under Parity, even alongside a
    /// SEARCH/REPLACE payload that would otherwise win under a flagship
    /// model's DailyDriver order — Parity must use ONLY the diff, never even
    /// consider the other payload (#2073, tightened 2026-07-07).
    #[test]
    fn select_and_apply_for_mode_parity_applies_a_valid_diff() {
        let payloads = [
            EditPayload::SearchReplace {
                old_string: "line2".into(),
                new_string: "replaced".into(),
            },
            EditPayload::UnifiedDiff {
                diff: "@@ -2,1 +2,1 @@\n-line2\n+line2-diffed\n".into(),
            },
        ];
        let (updated, format) = select_and_apply_for_mode(
            HarnessMode::Parity,
            "anthropic/claude-opus-4-5",
            "line1\nline2\n",
            Path::new("f.py"),
            &payloads,
        )
        .expect("unified diff must apply");
        assert_eq!(format, EditFormat::UnifiedDiff);
        assert_eq!(updated, "line1\nline2-diffed\n");
    }

    /// Parity with NO diff payload supplied — only SEARCH/REPLACE or
    /// whole-file — must return a recoverable `FsError::ParityDiffRequired`,
    /// NOT silently fall back and succeed (#2073, tightened 2026-07-07: the
    /// owner's benchmark-fairness decision — a model that never emitted a
    /// diff must be scored as failing the edit).
    #[test]
    fn select_and_apply_for_mode_parity_errors_without_a_diff_payload() {
        let payloads = [EditPayload::WholeFile {
            content: "brand new\n".into(),
        }];
        let err = select_and_apply_for_mode(
            HarnessMode::Parity,
            "anthropic/claude-opus-4-5",
            "old\n",
            Path::new("f.py"),
            &payloads,
        )
        .expect_err("Parity must reject a run with no diff payload");
        assert!(
            matches!(err, FsError::ParityDiffRequired { .. }),
            "expected ParityDiffRequired, got {err:?}"
        );
        assert!(
            err.to_string()
                .contains("Parity mode requires a unified-diff edit"),
            "error message must make the Parity requirement clear: {err}"
        );
    }

    /// Parity with a PRESENT but inapplicable diff (bad hunk/context
    /// mismatch), plus a whole-file payload that WOULD otherwise succeed,
    /// must still fail — no fallback to the whole-file payload is attempted
    /// even when the diff itself is the one that failed (#2073, tightened
    /// 2026-07-07).
    #[test]
    fn select_and_apply_for_mode_parity_does_not_fall_back_on_diff_failure() {
        let payloads = [
            EditPayload::UnifiedDiff {
                diff: "@@ -99,1 +99,1 @@\n-nonexistent-line\n+replacement\n".into(),
            },
            EditPayload::WholeFile {
                content: "would-have-worked\n".into(),
            },
        ];
        let err = select_and_apply_for_mode(
            HarnessMode::Parity,
            "anthropic/claude-opus-4-5",
            "line1\nline2\n",
            Path::new("f.py"),
            &payloads,
        )
        .expect_err("an inapplicable diff must error, not fall back to whole-file");
        assert!(
            matches!(
                err,
                FsError::DiffContextMismatch { .. } | FsError::DiffHunkHeader { .. }
            ),
            "expected a diff-application error (not a fallback success), got {err:?}"
        );
    }

    /// `HarnessMode::DailyDriver` still falls back per-model exactly as
    /// before #2073 tightened Parity — guards against accidentally
    /// tightening the wrong mode.
    #[test]
    fn select_and_apply_for_mode_daily_driver_still_falls_back_per_model() {
        let payloads = [
            EditPayload::SearchReplace {
                old_string: "not-present".into(),
                new_string: "x".into(),
            },
            EditPayload::WholeFile {
                content: "fallback content\n".into(),
            },
        ];
        // Flagship order is SearchReplace -> UnifiedDiff -> WholeFile; the
        // non-matching SearchReplace payload must fall through to WholeFile.
        let (updated, format) = select_and_apply_for_mode(
            HarnessMode::DailyDriver,
            "anthropic/claude-opus-4-5",
            "orig\n",
            Path::new("f.py"),
            &payloads,
        )
        .expect("DailyDriver must still fall back to whole-file");
        assert_eq!(format, EditFormat::WholeFile);
        assert_eq!(updated, "fallback content\n");
    }
}