Skip to main content

trusty_code/tools/fs/
edit.rs

1//! `edit` tool — per-model edit-format selection (#2068).
2//!
3//! Why: Agents that iteratively refine code need a surgical replace-in-place
4//! primitive that is safer than re-writing the whole file from memory. Before
5//! #2068 the only supported wire format was exact-unique SEARCH/REPLACE,
6//! mirroring the Claude Code `Edit` tool contract. Aider's A/B data shows edit
7//! success rate varies by model family and format (see
8//! `tools::fs::edit_format`'s module docs for the matrix): some models
9//! reliably reproduce an exact substring, others do much better with a
10//! unified diff or a full-file rewrite. `EditTool` now accepts any of the
11//! three formats in one call and applies them in the calling model's
12//! preferred order via `edit_format::select_and_apply`.
13//! What: `EditTool` reads the file, builds an `EditPayload` for each format
14//! present in the tool-call arguments (`old_string`+`new_string`, `diff`, or
15//! `content`), and delegates to `edit_format::select_and_apply` to pick and
16//! apply the best-fit format, then writes the result back. All paths are
17//! scoped to the working directory. On success it also best-effort fires a
18//! mid-task incremental trusty-search index update for the edited path (issue:
19//! mid-task incremental re-indexing) so `search_code` reflects the edit within
20//! the same task.
21//! Test: See `#[cfg(test)]` below — covers each format, zero/ambiguous
22//! SEARCH/REPLACE errors, malformed-diff errors, and path traversal.
23
24use std::path::PathBuf;
25
26use async_trait::async_trait;
27use serde_json::{Value, json};
28
29use crate::mode::HarnessMode;
30use crate::tools::fs::edit_format::{
31    EditFormat, EditPayload, select_and_apply, select_and_apply_for_mode,
32};
33use crate::tools::fs::{FsError, scoped_path};
34use crate::tools::traits::{ToolExecutor, ToolResult};
35
36/// `ToolExecutor` that applies an edit using whichever wire format(s) the
37/// caller supplied, in the calling model's preferred order.
38///
39/// Why: Surgical in-place edits are the primary mutation primitive for coding
40/// agents. Supporting all three #2068 formats behind one tool keeps the
41/// registry/schema surface simple while letting the caller (or a future
42/// repair loop) hand the model whichever format it is more likely to succeed
43/// with.
44/// What: Implements `ToolExecutor` with `name = "edit"`. Reads the file,
45/// builds the present `EditPayload`s, calls `edit_format::select_and_apply`
46/// with `self.model_slug`, and writes the result back.
47/// Test: `cargo test -p trusty-code -- tools::fs::edit`.
48pub struct EditTool {
49    working_dir: PathBuf,
50    model_slug: Option<String>,
51    /// The resolved `HarnessMode` for this tool's owning run (#2073). `None`
52    /// (the default, and every pre-#2073 call site) preserves the exact
53    /// pre-#2073 behaviour: always the plain per-model order via
54    /// `edit_format::select_and_apply`. `Some(mode)` routes through
55    /// `edit_format::select_and_apply_for_mode`, whose `HarnessMode::Parity`
56    /// arm requires a `diff` payload and does NOT fall back to SEARCH/REPLACE
57    /// or whole-file (owner-tightened 2026-07-07, §5.9's edit-format
58    /// reconciliation read literally for benchmark fairness).
59    mode: Option<HarnessMode>,
60}
61
62impl EditTool {
63    /// Construct a new `EditTool` scoped to `working_dir`.
64    ///
65    /// Why: The working directory is the security boundary set at construction.
66    /// What: Stores `working_dir`. `model_slug` defaults to `None`, which
67    /// selects the catch-all format order (see `edit_format::format_order_for`);
68    /// this has no effect on a call that supplies only one format.
69    /// Test: `edit_replaces_unique_match`, et al.
70    pub fn new(working_dir: impl Into<PathBuf>) -> Self {
71        Self {
72            working_dir: working_dir.into(),
73            model_slug: None,
74            mode: None,
75        }
76    }
77
78    /// Set the model slug used to look up the per-model format fallback order.
79    ///
80    /// Why: The registry factory resolves the calling agent's model slug
81    /// (`provider::resolve_model`) once per delegation; threading it through
82    /// here lets `edit_format::select_and_apply` pick the best-fit format when
83    /// a tool call supplies more than one representation of the same edit.
84    /// What: Stores `slug` for use in `execute`.
85    /// Test: `edit_falls_back_to_whole_file_when_search_replace_fails`.
86    pub fn with_model_slug(mut self, slug: impl Into<String>) -> Self {
87        self.model_slug = Some(slug.into());
88        self
89    }
90
91    /// Set the resolved `HarnessMode` this tool's owning run uses (#2073).
92    ///
93    /// Why: `HarnessMode::Parity` must score a model's raw diff-editing
94    /// ability, unforgivingly — without this the tool always used the
95    /// per-model fallback matrix even in Parity, letting a model "pass" an
96    /// edit via SEARCH/REPLACE or whole-file without ever demonstrating a
97    /// valid diff (owner decision, 2026-07-07: this would defeat M3's model
98    /// bake-off). Every call site that does not opt in (`mode` stays `None`)
99    /// keeps the exact pre-#2073 behaviour.
100    /// What: Stores `mode` for use in `execute`/`edit_inner`.
101    /// Test: `edit_under_parity_mode_applies_a_valid_diff`,
102    /// `edit_under_parity_mode_errors_without_a_diff_payload`,
103    /// `edit_under_daily_driver_mode_matches_legacy_model_based_order`.
104    pub fn with_mode(mut self, mode: HarnessMode) -> Self {
105        self.mode = Some(mode);
106        self
107    }
108
109    /// Perform the edit: read the file, apply the best-fit payload, write back.
110    ///
111    /// Why: Centralises the IO so `execute` stays focused on argument parsing.
112    /// What: Returns the `EditFormat` that was actually applied. Errors
113    /// propagate from `scoped_path`, file IO, or the underlying
114    /// `edit_format::select_and_apply`/`select_and_apply_for_mode` call.
115    /// `self.mode` (#2073) picks which of the two: `None` (unset) preserves
116    /// the exact pre-#2073 plain per-model selection; `Some(mode)` routes
117    /// through the mode-aware variant, whose `Parity` arm accepts ONLY a
118    /// `diff` payload and returns a recoverable
119    /// `FsError::ParityDiffRequired` (never a panic) when none was supplied
120    /// or the diff fails to apply — no fallback to SEARCH/REPLACE or
121    /// whole-file, even then.
122    /// Test: All `EditTool` unit tests exercise this path.
123    fn edit_inner(
124        &self,
125        path: &std::path::Path,
126        payloads: &[EditPayload],
127    ) -> Result<EditFormat, FsError> {
128        let scoped = scoped_path(&self.working_dir, path)?;
129
130        let content = std::fs::read_to_string(&scoped).map_err(|e| {
131            if e.kind() == std::io::ErrorKind::NotFound {
132                FsError::NotFound(scoped.clone())
133            } else {
134                FsError::io(&scoped, e)
135            }
136        })?;
137
138        let model_slug = self.model_slug.as_deref().unwrap_or("");
139        let (updated, format) = match self.mode {
140            Some(mode) => select_and_apply_for_mode(mode, model_slug, &content, &scoped, payloads)?,
141            None => select_and_apply(model_slug, &content, &scoped, payloads)?,
142        };
143        std::fs::write(&scoped, updated).map_err(|e| FsError::io(&scoped, e))?;
144        Ok(format)
145    }
146}
147
148#[async_trait]
149impl ToolExecutor for EditTool {
150    fn name(&self) -> &str {
151        "edit"
152    }
153
154    /// OpenAI function-call schema for `edit`.
155    ///
156    /// Why: The LLM uses this schema to construct its tool call. `path` is the
157    /// only unconditionally required field (#2068); exactly one edit format's
158    /// fields must also be present, validated at execution time since JSON
159    /// Schema cannot express "one of these three field groups" cleanly here.
160    /// What: JSON object with `path` plus the three optional per-format field
161    /// groups: `old_string`+`new_string` (SEARCH/REPLACE), `diff`
162    /// (unified-diff), `content` (whole-file).
163    /// Test: `schema_requires_only_path`.
164    fn schema(&self) -> Value {
165        json!({
166            "type": "function",
167            "function": {
168                "name": "edit",
169                "description": "Edit a file using one of three formats: (1) SEARCH/REPLACE — provide old_string+new_string; old_string must appear exactly once in the file (cheapest, preferred when you can reproduce it exactly); (2) unified-diff — provide diff as one or more '@@ -l,s +l,s @@' hunks (use when context is easier to express as a diff than an exact substring); (3) whole-file — provide content as the file's complete new contents (most robust, most expensive; use as a last resort). Provide exactly one format's fields. The path must be inside the working directory.",
170                "parameters": {
171                    "type": "object",
172                    "properties": {
173                        "path": {
174                            "type": "string",
175                            "description": "Relative or absolute path to the file (must be inside the working directory)."
176                        },
177                        "old_string": {
178                            "type": "string",
179                            "description": "SEARCH/REPLACE format: the exact string to replace. Must appear exactly once in the file. Requires new_string."
180                        },
181                        "new_string": {
182                            "type": "string",
183                            "description": "SEARCH/REPLACE format: the replacement string. Requires old_string."
184                        },
185                        "diff": {
186                            "type": "string",
187                            "description": "Unified-diff format: one or more '@@ -l,s +l,s @@' hunks to apply against the file's current content."
188                        },
189                        "content": {
190                            "type": "string",
191                            "description": "Whole-file format: the complete new content of the file."
192                        }
193                    },
194                    "required": ["path"],
195                    "additionalProperties": false
196                }
197            }
198        })
199    }
200
201    /// Execute an `edit` tool call.
202    ///
203    /// Why: Applies whichever edit format(s) the caller supplied, in the
204    /// model's preferred order.
205    /// What: Builds an `EditPayload` for each format present in `args`
206    /// (`old_string`+`new_string`, `diff`, `content`), errors if none are
207    /// present or `old_string`/`new_string` are only partially supplied, then
208    /// calls `edit_inner` and converts the result into a `ToolResult`. On
209    /// success, best-effort fires a mid-task incremental trusty-search index
210    /// update (issue: mid-task incremental re-indexing) for the edited path so
211    /// `search_code` reflects the edit within the same task — this never
212    /// affects the returned `ToolResult`; see
213    /// [`trusty_common::search_index::index_files_best_effort`]'s fail-open
214    /// contract.
215    /// Test: `edit_replaces_unique_match`, `edit_errors_on_zero_matches`,
216    /// `edit_applies_unified_diff`, `edit_applies_whole_file`, etc.
217    async fn execute(&self, args: Value) -> ToolResult {
218        let Some(path_str) = args.get("path").and_then(Value::as_str) else {
219            return ToolResult::err("edit: missing required argument 'path'");
220        };
221
222        let mut payloads = Vec::new();
223        match (
224            args.get("old_string").and_then(Value::as_str),
225            args.get("new_string").and_then(Value::as_str),
226        ) {
227            (Some(old_string), Some(new_string)) => payloads.push(EditPayload::SearchReplace {
228                old_string: old_string.to_string(),
229                new_string: new_string.to_string(),
230            }),
231            (None, None) => {}
232            _ => {
233                return ToolResult::err(
234                    "edit: 'old_string' and 'new_string' must be provided together",
235                );
236            }
237        }
238        if let Some(diff) = args.get("diff").and_then(Value::as_str) {
239            payloads.push(EditPayload::UnifiedDiff {
240                diff: diff.to_string(),
241            });
242        }
243        if let Some(content) = args.get("content").and_then(Value::as_str) {
244            payloads.push(EditPayload::WholeFile {
245                content: content.to_string(),
246            });
247        }
248        if payloads.is_empty() {
249            return ToolResult::err(
250                "edit: must provide either 'old_string'+'new_string', 'diff', or 'content'",
251            );
252        }
253
254        match self.edit_inner(std::path::Path::new(path_str), &payloads) {
255            Ok(format) => {
256                trusty_common::search_index::index_files_best_effort(
257                    &self.working_dir,
258                    &[PathBuf::from(path_str)],
259                );
260                ToolResult::ok(format!("edited {path_str} ({format})"))
261            }
262            Err(e) => ToolResult::err(e.to_string()),
263        }
264    }
265}
266
267// ── Tests ─────────────────────────────────────────────────────────────────────
268
269#[cfg(test)]
270mod tests {
271    use std::fs;
272
273    use serde_json::json;
274
275    use super::*;
276    use crate::tools::traits::ToolExecutor;
277
278    fn make_tool(tmp: &tempfile::TempDir) -> EditTool {
279        EditTool::new(tmp.path())
280    }
281
282    /// `edit` replaces a unique match and the file is updated on disk.
283    ///
284    /// Why: Basic contract — edit a file, re-read it, assert the replacement.
285    /// What: Write `old`, execute `edit(old → new)`, read back and assert `new`.
286    /// Test: This test.
287    #[tokio::test]
288    async fn edit_replaces_unique_match() {
289        let tmp = tempfile::tempdir().expect("tempdir");
290        fs::write(tmp.path().join("code.py"), "def foo():\n    pass\n").expect("write");
291        let tool = make_tool(&tmp);
292        let result = tool
293            .execute(json!({
294                "path": "code.py",
295                "old_string": "    pass",
296                "new_string": "    return 42"
297            }))
298            .await;
299        assert!(!result.is_error(), "unexpected error: {}", result.content());
300        let updated = fs::read_to_string(tmp.path().join("code.py")).expect("read");
301        assert!(updated.contains("return 42"), "replacement must be applied");
302        assert!(!updated.contains("    pass"), "old string must be gone");
303    }
304
305    /// `edit` errors when `old_string` is not found in the file.
306    ///
307    /// Why: A zero-match edit would be a silent no-op; the agent must provide
308    /// a valid substring to avoid confusion about whether the edit succeeded.
309    /// What: `execute` with a non-existent `old_string` must return an error.
310    /// Test: This test.
311    #[tokio::test]
312    async fn edit_errors_on_zero_matches() {
313        let tmp = tempfile::tempdir().expect("tempdir");
314        fs::write(tmp.path().join("f.py"), "x = 1\n").expect("write");
315        let tool = make_tool(&tmp);
316        let result = tool
317            .execute(json!({
318                "path": "f.py",
319                "old_string": "not_in_file",
320                "new_string": "replacement"
321            }))
322            .await;
323        assert!(result.is_error());
324        assert!(
325            result.content().contains("not found"),
326            "unexpected message: {}",
327            result.content()
328        );
329    }
330
331    /// `edit` errors when `old_string` appears more than once.
332    ///
333    /// Why: An ambiguous replacement would modify the wrong occurrence; the
334    /// agent must provide more context.
335    /// What: Write a file with two identical lines, attempt `edit`; expect error.
336    /// Test: This test.
337    #[tokio::test]
338    async fn edit_errors_on_multiple_matches() {
339        let tmp = tempfile::tempdir().expect("tempdir");
340        fs::write(tmp.path().join("dup.py"), "x = 1\nx = 1\n").expect("write");
341        let tool = make_tool(&tmp);
342        let result = tool
343            .execute(json!({
344                "path": "dup.py",
345                "old_string": "x = 1",
346                "new_string": "x = 2"
347            }))
348            .await;
349        assert!(result.is_error());
350        assert!(
351            result.content().contains("ambiguous"),
352            "unexpected message: {}",
353            result.content()
354        );
355    }
356
357    /// `edit` rejects a path that escapes the working directory.
358    ///
359    /// Why: Path traversal must be blocked at the tool boundary.
360    /// What: `execute` with `path = "../../etc/passwd"` must return error.
361    /// Test: This test.
362    #[tokio::test]
363    async fn path_traversal_is_rejected() {
364        let tmp = tempfile::tempdir().expect("tempdir");
365        let tool = make_tool(&tmp);
366        let result = tool
367            .execute(json!({
368                "path": "../../etc/passwd",
369                "old_string": "root",
370                "new_string": "evil"
371            }))
372            .await;
373        assert!(result.is_error());
374        assert!(
375            result.content().contains("escapes"),
376            "unexpected message: {}",
377            result.content()
378        );
379    }
380
381    /// The schema requires only `path`; all three edit-format field groups are
382    /// optional at the schema level (validated at execution time instead).
383    ///
384    /// Why: #2068 lets a call supply SEARCH/REPLACE, unified-diff, or
385    /// whole-file fields — JSON Schema cannot cleanly express "exactly one of
386    /// these three field groups", so only the universally-required `path` is
387    /// listed, and every format's properties are documented but optional.
388    /// What: Parses `schema()` and checks `required == ["path"]`, and that all
389    /// five properties (`path`, `old_string`, `new_string`, `diff`, `content`)
390    /// are present.
391    /// Test: This test.
392    #[test]
393    fn schema_requires_only_path() {
394        let tmp = tempfile::tempdir().expect("tempdir");
395        let tool = make_tool(&tmp);
396        let schema = tool.schema();
397        let required = schema["function"]["parameters"]["required"]
398            .as_array()
399            .expect("required array");
400        let names: Vec<&str> = required.iter().filter_map(Value::as_str).collect();
401        assert_eq!(names, vec!["path"], "only 'path' must be required");
402
403        let properties = schema["function"]["parameters"]["properties"]
404            .as_object()
405            .expect("properties object");
406        for key in ["path", "old_string", "new_string", "diff", "content"] {
407            assert!(properties.contains_key(key), "missing property '{key}'");
408        }
409    }
410
411    /// `edit` applies a unified-diff payload when `diff` is supplied.
412    ///
413    /// Why: Guard the second #2068 format end-to-end through `execute`.
414    /// What: Write a two-line file, execute `edit` with a `diff` argument
415    /// replacing one line, and assert the file was patched.
416    /// Test: This test.
417    #[tokio::test]
418    async fn edit_applies_unified_diff() {
419        let tmp = tempfile::tempdir().expect("tempdir");
420        fs::write(tmp.path().join("f.py"), "line1\nline2\n").expect("write");
421        let tool = make_tool(&tmp);
422        let result = tool
423            .execute(json!({
424                "path": "f.py",
425                "diff": "@@ -2,1 +2,1 @@\n-line2\n+line2-changed\n"
426            }))
427            .await;
428        assert!(!result.is_error(), "unexpected error: {}", result.content());
429        assert!(result.content().contains("unified_diff"));
430        let updated = fs::read_to_string(tmp.path().join("f.py")).expect("read");
431        assert_eq!(updated, "line1\nline2-changed\n");
432    }
433
434    /// `edit` applies a whole-file payload when `content` is supplied.
435    ///
436    /// Why: Guard the third #2068 format (last-resort, most-robust) end-to-end.
437    /// What: Write a file, execute `edit` with a `content` argument, and
438    /// assert the file's entire content was replaced.
439    /// Test: This test.
440    #[tokio::test]
441    async fn edit_applies_whole_file() {
442        let tmp = tempfile::tempdir().expect("tempdir");
443        fs::write(tmp.path().join("f.py"), "old content\n").expect("write");
444        let tool = make_tool(&tmp);
445        let result = tool
446            .execute(json!({
447                "path": "f.py",
448                "content": "brand new file\n"
449            }))
450            .await;
451        assert!(!result.is_error(), "unexpected error: {}", result.content());
452        assert!(result.content().contains("whole_file"));
453        let updated = fs::read_to_string(tmp.path().join("f.py")).expect("read");
454        assert_eq!(updated, "brand new file\n");
455    }
456
457    /// `edit` errors when `old_string` is supplied without `new_string`.
458    ///
459    /// Why: A half-supplied SEARCH/REPLACE pair is an unambiguous caller
460    /// mistake and must be rejected before touching the filesystem.
461    /// What: `execute` with only `old_string` set must return a recoverable error.
462    /// Test: This test.
463    #[tokio::test]
464    async fn edit_errors_on_partial_search_replace_pair() {
465        let tmp = tempfile::tempdir().expect("tempdir");
466        fs::write(tmp.path().join("f.py"), "x = 1\n").expect("write");
467        let tool = make_tool(&tmp);
468        let result = tool
469            .execute(json!({"path": "f.py", "old_string": "x = 1"}))
470            .await;
471        assert!(result.is_error());
472        assert!(result.content().contains("together"));
473    }
474
475    /// `edit` errors when none of the three format field groups are supplied.
476    ///
477    /// Why: Nothing to apply is a caller mistake, not a silent no-op.
478    /// What: `execute` with only `path` must return a recoverable error.
479    /// Test: This test.
480    #[tokio::test]
481    async fn edit_errors_when_no_format_supplied() {
482        let tmp = tempfile::tempdir().expect("tempdir");
483        fs::write(tmp.path().join("f.py"), "x = 1\n").expect("write");
484        let tool = make_tool(&tmp);
485        let result = tool.execute(json!({"path": "f.py"})).await;
486        assert!(result.is_error());
487        assert!(result.content().contains("must provide"));
488    }
489
490    /// With a model slug set, a failing SEARCH/REPLACE payload falls back to a
491    /// concurrently-supplied whole-file payload within the same call.
492    ///
493    /// Why: This is the #2068 fallback-ordering acceptance criterion exercised
494    /// through the actual `ToolExecutor::execute` entry point, not just the
495    /// underlying `edit_format::select_and_apply` unit tests.
496    /// What: Give a flagship model slug (SEARCH/REPLACE-first order), a
497    /// non-matching `old_string`/`new_string` pair, and a `content` fallback;
498    /// assert the whole-file fallback was applied.
499    /// Test: This test.
500    #[tokio::test]
501    async fn edit_falls_back_to_whole_file_when_search_replace_fails() {
502        let tmp = tempfile::tempdir().expect("tempdir");
503        fs::write(tmp.path().join("f.py"), "original\n").expect("write");
504        let tool = EditTool::new(tmp.path()).with_model_slug("anthropic/claude-opus-4-5");
505        let result = tool
506            .execute(json!({
507                "path": "f.py",
508                "old_string": "not-present-in-file",
509                "new_string": "x",
510                "content": "fallback content\n"
511            }))
512            .await;
513        assert!(!result.is_error(), "unexpected error: {}", result.content());
514        assert!(result.content().contains("whole_file"));
515        let updated = fs::read_to_string(tmp.path().join("f.py")).expect("read");
516        assert_eq!(updated, "fallback content\n");
517    }
518
519    /// Under `HarnessMode::Parity`, a flagship model slug (which would prefer
520    /// SEARCH/REPLACE first under the plain per-model matrix) still applies
521    /// ONLY the unified-diff payload when both are supplied — the
522    /// SEARCH/REPLACE payload is never even attempted (#2073, tightened
523    /// 2026-07-07: Parity's edit-format is strict unified-diff only, not
524    /// merely model-independent).
525    #[tokio::test]
526    async fn edit_under_parity_mode_applies_a_valid_diff() {
527        let tmp = tempfile::tempdir().expect("tempdir");
528        fs::write(tmp.path().join("f.py"), "line1\nline2\n").expect("write");
529        let tool = EditTool::new(tmp.path())
530            .with_model_slug("anthropic/claude-opus-4-5")
531            .with_mode(crate::mode::HarnessMode::Parity);
532
533        let result = tool
534            .execute(json!({
535                "path": "f.py",
536                // Deliberately non-matching, so a SEARCH/REPLACE-first order
537                // would fail; only the diff below can actually apply. Under
538                // strict Parity this payload is never even attempted.
539                "old_string": "not-present",
540                "new_string": "x",
541                "diff": "@@ -2,1 +2,1 @@\n-line2\n+line2-diffed\n"
542            }))
543            .await;
544
545        assert!(!result.is_error(), "unexpected error: {}", result.content());
546        assert!(result.content().contains("unified_diff"));
547        let updated = fs::read_to_string(tmp.path().join("f.py")).expect("read");
548        assert_eq!(updated, "line1\nline2-diffed\n");
549    }
550
551    /// Under `HarnessMode::Parity`, an `edit` call that supplies only
552    /// SEARCH/REPLACE (no `diff`) must return a RECOVERABLE tool error — the
553    /// same `ToolResult::err` mechanism every other edit failure uses, never
554    /// a panic — whose message makes clear Parity requires a unified-diff
555    /// edit, and must NOT silently succeed via the fallback matrix (#2073,
556    /// tightened 2026-07-07: the model is scored as failing the edit, per
557    /// the owner's benchmark-fairness decision).
558    #[tokio::test]
559    async fn edit_under_parity_mode_errors_without_a_diff_payload() {
560        let tmp = tempfile::tempdir().expect("tempdir");
561        fs::write(tmp.path().join("f.py"), "line1\nline2\n").expect("write");
562        let tool = EditTool::new(tmp.path())
563            .with_model_slug("anthropic/claude-opus-4-5")
564            .with_mode(crate::mode::HarnessMode::Parity);
565
566        // A payload that WOULD succeed under DailyDriver's fallback matrix
567        // (unique old_string match) — under Parity it must never be tried.
568        let result = tool
569            .execute(json!({
570                "path": "f.py",
571                "old_string": "line2",
572                "new_string": "line2-replaced"
573            }))
574            .await;
575
576        assert!(
577            result.is_error(),
578            "Parity must reject an edit with no diff payload, got: {}",
579            result.content()
580        );
581        assert!(
582            result.content().contains("unified-diff"),
583            "error must make the Parity requirement clear: {}",
584            result.content()
585        );
586        let unchanged = fs::read_to_string(tmp.path().join("f.py")).expect("read");
587        assert_eq!(
588            unchanged, "line1\nline2\n",
589            "the file must be untouched when Parity rejects the edit"
590        );
591    }
592
593    /// Under `HarnessMode::DailyDriver`, `with_mode` must produce the exact
594    /// same outcome as the pre-#2073 default (no `with_mode` call at all) —
595    /// the mode-aware path is a no-op wrapper around the legacy per-model
596    /// matrix for this mode.
597    #[tokio::test]
598    async fn edit_under_daily_driver_mode_matches_legacy_model_based_order() {
599        let tmp = tempfile::tempdir().expect("tempdir");
600        fs::write(tmp.path().join("f.py"), "original\n").expect("write");
601        let tool = EditTool::new(tmp.path())
602            .with_model_slug("anthropic/claude-opus-4-5")
603            .with_mode(crate::mode::HarnessMode::DailyDriver);
604
605        let result = tool
606            .execute(json!({
607                "path": "f.py",
608                "old_string": "not-present-in-file",
609                "new_string": "x",
610                "content": "fallback content\n"
611            }))
612            .await;
613
614        assert!(!result.is_error(), "unexpected error: {}", result.content());
615        assert!(result.content().contains("whole_file"));
616        let updated = fs::read_to_string(tmp.path().join("f.py")).expect("read");
617        assert_eq!(updated, "fallback content\n");
618    }
619}