fix(maestro): align structured diff hunks

This commit is contained in:
Miguel Palhas
2026-09-05 09:27:37 +01:00
parent efb54750ed
commit f96f94db8f
3 changed files with 230 additions and 54 deletions
+208 -52
View File
@@ -14,6 +14,7 @@ use crate::session_task::SessionState;
use crate::structured_task::{offered_decisions, StructuredHandle, StructuredState};
const DIFF_PREVIEW_LINES: usize = 3;
const DIFF_CONTEXT_LINES: usize = 3;
const LCS_CELL_LIMIT: usize = 250_000;
#[derive(Debug, Clone)]
@@ -521,7 +522,7 @@ fn split_diff_lines(text: &str) -> Vec<SourceLine<'_>> {
.collect()
}
fn lcs_diff<'a>(old: &[SourceLine<'a>], new: &[SourceLine<'a>], limit: usize) -> Vec<DiffOp<'a>> {
fn lcs_diff<'a>(old: &[SourceLine<'a>], new: &[SourceLine<'a>]) -> Vec<DiffOp<'a>> {
if old.is_empty() {
return new
.iter()
@@ -530,7 +531,6 @@ fn lcs_diff<'a>(old: &[SourceLine<'a>], new: &[SourceLine<'a>], limit: usize) ->
kind: DiffKind::Add,
line,
})
.take(limit)
.collect();
}
if new.is_empty() {
@@ -541,7 +541,6 @@ fn lcs_diff<'a>(old: &[SourceLine<'a>], new: &[SourceLine<'a>], limit: usize) ->
kind: DiffKind::Delete,
line,
})
.take(limit)
.collect();
}
if old.len().saturating_mul(new.len()) > LCS_CELL_LIMIT {
@@ -556,7 +555,6 @@ fn lcs_diff<'a>(old: &[SourceLine<'a>], new: &[SourceLine<'a>], limit: usize) ->
kind: DiffKind::Add,
line,
}))
.take(limit)
.collect();
}
@@ -574,7 +572,7 @@ fn lcs_diff<'a>(old: &[SourceLine<'a>], new: &[SourceLine<'a>], limit: usize) ->
let mut ops = Vec::with_capacity(old.len() + new.len());
let (mut i, mut j) = (0, 0);
while i < old.len() && j < new.len() && ops.len() < limit {
while i < old.len() && j < new.len() {
if old[i] == new[j] {
ops.push(DiffOp {
kind: DiffKind::Context,
@@ -596,32 +594,18 @@ fn lcs_diff<'a>(old: &[SourceLine<'a>], new: &[SourceLine<'a>], limit: usize) ->
j += 1;
}
}
let remaining = limit.saturating_sub(ops.len());
ops.extend(
old[i..]
.iter()
.copied()
.map(|line| DiffOp {
kind: DiffKind::Delete,
line,
})
.take(remaining),
);
let remaining = limit.saturating_sub(ops.len());
ops.extend(
new[j..]
.iter()
.copied()
.map(|line| DiffOp {
kind: DiffKind::Add,
line,
})
.take(remaining),
);
ops.extend(old[i..].iter().copied().map(|line| DiffOp {
kind: DiffKind::Delete,
line,
}));
ops.extend(new[j..].iter().copied().map(|line| DiffOp {
kind: DiffKind::Add,
line,
}));
ops
}
fn diff_ops<'a>(old: &'a str, new: &'a str, limit: usize) -> Vec<DiffOp<'a>> {
fn diff_ops<'a>(old: &'a str, new: &'a str) -> Vec<DiffOp<'a>> {
let old = split_diff_lines(old);
let new = split_diff_lines(new);
let mut prefix = 0;
@@ -643,15 +627,11 @@ fn diff_ops<'a>(old: &'a str, new: &'a str, limit: usize) -> Vec<DiffOp<'a>> {
kind: DiffKind::Context,
line,
})
.take(limit)
.collect::<Vec<_>>();
let remaining = limit.saturating_sub(ops.len());
ops.extend(lcs_diff(
&old[prefix..old.len() - suffix],
&new[prefix..new.len() - suffix],
remaining,
));
let remaining = limit.saturating_sub(ops.len());
ops.extend(
old[old.len() - suffix..]
.iter()
@@ -659,14 +639,71 @@ fn diff_ops<'a>(old: &'a str, new: &'a str, limit: usize) -> Vec<DiffOp<'a>> {
.map(|line| DiffOp {
kind: DiffKind::Context,
line,
})
.take(remaining),
}),
);
ops
}
fn render_diff_ops(ops: &[DiffOp<'_>]) -> Vec<String> {
let mut rendered = Vec::with_capacity(ops.len());
let mut index = 0;
while index < ops.len() {
if ops[index].kind != DiffKind::Context {
push_diff_op(&mut rendered, ops[index]);
index += 1;
continue;
}
let mut end = index;
while end < ops.len() && ops[end].kind == DiffKind::Context {
end += 1;
}
let run = &ops[index..end];
let whole_diff = index == 0 && end == ops.len();
let keep_head = if whole_diff || index > 0 {
DIFF_CONTEXT_LINES
} else {
0
};
let keep_tail = if whole_diff || end < ops.len() {
DIFF_CONTEXT_LINES
} else {
0
};
if run.len() <= keep_head + keep_tail {
for op in run {
push_diff_op(&mut rendered, *op);
}
} else {
for op in run.iter().take(keep_head) {
push_diff_op(&mut rendered, *op);
}
rendered.push(format!(
"… {} unchanged lines …",
run.len() - keep_head - keep_tail
));
for op in run.iter().skip(run.len() - keep_tail) {
push_diff_op(&mut rendered, *op);
}
}
index = end;
}
rendered
}
fn push_diff_op(rendered: &mut Vec<String>, op: DiffOp<'_>) {
let prefix = match op.kind {
DiffKind::Add => "+ ",
DiffKind::Delete => "- ",
DiffKind::Context => " ",
};
rendered.push(format!("{prefix}{}", op.line.text));
if !op.line.terminated {
rendered.push("\\ No newline at end of file".into());
}
}
fn render_diff(old: Option<&str>, new: &str, limit: Option<usize>) -> Vec<String> {
let op_limit = limit.unwrap_or(usize::MAX);
let ops = old.map_or_else(
|| {
split_diff_lines(new)
@@ -675,26 +712,13 @@ fn render_diff(old: Option<&str>, new: &str, limit: Option<usize>) -> Vec<String
kind: DiffKind::Add,
line,
})
.take(op_limit)
.collect()
},
|old| diff_ops(old, new, op_limit),
|old| diff_ops(old, new),
);
let mut rendered = Vec::with_capacity(ops.len());
for op in ops {
let prefix = match op.kind {
DiffKind::Add => "+ ",
DiffKind::Delete => "- ",
DiffKind::Context => " ",
};
rendered.push(format!("{prefix}{}", op.line.text));
if op.kind != DiffKind::Context && !op.line.terminated {
rendered.push("\\ No newline at end of file".into());
}
if limit.is_some_and(|limit| rendered.len() >= limit) {
rendered.truncate(limit.unwrap_or(0));
break;
}
let mut rendered = render_diff_ops(&ops);
if let Some(limit) = limit {
rendered.truncate(limit);
}
rendered
}
@@ -977,6 +1001,138 @@ mod tests {
diff_content(Some("a\n"), "a"),
["x:", "- a", "+ a", "\\ No newline at end of file"]
);
assert_eq!(
diff_content(None, "a"),
["x:", "+ a", "\\ No newline at end of file"]
);
}
#[test]
fn structured_diff_marks_unchanged_unterminated_final_context() {
assert_eq!(
diff_content(Some("a\nb\nc"), "a\nX\nc"),
[
"x:",
" a",
"- b",
"+ X",
" c",
"\\ No newline at end of file"
]
);
}
#[test]
fn structured_diff_collapses_long_context_around_changes() {
let common = (0..20)
.map(|index| format!("line{index}"))
.collect::<Vec<_>>();
let old = common[..10]
.iter()
.cloned()
.chain(["OLD".into()])
.chain(common[10..].iter().cloned())
.collect::<Vec<_>>()
.join("\n");
let new = common[..10]
.iter()
.cloned()
.chain(["NEW".into()])
.chain(common[10..].iter().cloned())
.collect::<Vec<_>>()
.join("\n");
assert_eq!(
render_diff(Some(&old), &new, None),
[
"… 7 unchanged lines …",
" line7",
" line8",
" line9",
"- OLD",
"+ NEW",
" line10",
" line11",
" line12",
"… 7 unchanged lines …",
]
);
}
#[test]
fn structured_diff_collapses_only_long_interior_context() {
let middle = (0..10).map(|index| format!("c{index}")).collect::<Vec<_>>();
let old = ["lead0", "lead1", "OLD1"]
.into_iter()
.map(str::to_string)
.chain(middle.iter().cloned())
.chain(["OLD2", "trail0", "trail1"].into_iter().map(str::to_string))
.collect::<Vec<_>>()
.join("\n");
let new = ["lead0", "lead1", "NEW1"]
.into_iter()
.map(str::to_string)
.chain(middle.iter().cloned())
.chain(["NEW2", "trail0", "trail1"].into_iter().map(str::to_string))
.collect::<Vec<_>>()
.join("\n");
let rendered = render_diff(Some(&old), &new, None);
assert_eq!(
rendered
.iter()
.filter(|line| line.contains("unchanged lines"))
.count(),
1
);
assert_eq!(&rendered[..4], [" lead0", " lead1", "- OLD1", "+ NEW1"]);
assert_eq!(
&rendered[4..11],
[
" c0",
" c1",
" c2",
"… 4 unchanged lines …",
" c7",
" c8",
" c9"
]
);
assert_eq!(
&rendered[11..],
[
"- OLD2",
"+ NEW2",
" trail0",
" trail1",
"\\ No newline at end of file"
]
);
}
#[test]
fn structured_diff_preview_remains_bounded_after_hunking() {
let common = (0..10)
.map(|index| format!("line{index}"))
.collect::<Vec<_>>();
let old = common
.iter()
.cloned()
.chain(["OLD".into()])
.collect::<Vec<_>>()
.join("\n");
let new = common
.iter()
.cloned()
.chain(["NEW".into()])
.collect::<Vec<_>>()
.join("\n");
let expanded = render_diff(Some(&old), &new, None);
assert_eq!(render_diff(Some(&old), &new, Some(4)), expanded[..4]);
assert_eq!(expanded[0], "… 7 unchanged lines …");
assert!(expanded.contains(&"- OLD".into()));
assert!(expanded.contains(&"+ NEW".into()));
}
#[test]