mod diff;
use std::path::Path;
use super::FsError;
use crate::mode::HarnessMode;
pub(crate) use diff::apply_unified_diff;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditFormat {
SearchReplace,
UnifiedDiff,
WholeFile,
}
impl EditFormat {
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())
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum EditPayload {
SearchReplace {
old_string: String,
new_string: String,
},
UnifiedDiff { diff: String },
WholeFile { content: String },
}
impl EditPayload {
fn format(&self) -> EditFormat {
match self {
EditPayload::SearchReplace { .. } => EditFormat::SearchReplace,
EditPayload::UnifiedDiff { .. } => EditFormat::UnifiedDiff,
EditPayload::WholeFile { .. } => EditFormat::WholeFile,
}
}
}
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,
]
}
}
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,
}),
}
}
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()),
}
}
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)
}
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),
}
}
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)
}
}
}
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))
}
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(),
}))
}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::*;
#[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");
}
#[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}"
);
}
}
#[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}"
);
}
}
#[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}"
);
}
}
#[test]
fn select_and_apply_search_replace_unique_match() {
let payloads = [EditPayload::SearchReplace {
old_string: "foo".into(),
new_string: "bar".into(),
}];
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);
}
#[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, .. }));
}
#[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);
}
#[test]
fn select_and_apply_falls_back_on_failure() {
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);
}
#[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 { .. }));
}
#[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}"
);
}
}
#[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}"
);
}
}
#[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");
}
#[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}"
);
}
#[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:?}"
);
}
#[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(),
},
];
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");
}
}