aKode 0.9.1: correzioni dalla prova di Fourier (apply_patch, write_file, errori visibili, rete dei pacchetti)
- apply_patch tollerante: aggiunge '*** Begin Patch'/'*** End Patch' mancanti quando
il contenuto inizia con Add/Update/Delete File, toglie i recinti ```; ogni altra
ambiguità resta un errore; riga con il formato e un esempio negli errori di formato.
- Strumento write_file (path + contenuto) sulla pipeline di apply_patch (stesse
verifiche, sandbox, approvazioni e hook), [tools] write_file (predefinito attivo);
dopo la scrittura ricorda al modello di verificare il file.
- Chiamate a strumento fallite visibili nella TUI ("✗ strumento: motivo · riprovo").
- Avanzamento mentre il modello scrive una chiamata lunga ("Scrivo file · N token")
e stato del gateway imeAI ("In coda…", "Leggo il prompt · 42%").
- write_stdin con id inesistente: elenca le sessioni aperte e indica exec_command o
write_file; descrizione più chiara.
- Protezione dai loop: un avviso al modello prima di fermare il turno.
- Sandbox predefinita: rete attiva solo verso i registri dei pacchetti attraverso il
proxy di rete ([features.network_proxy] nei default impacchettati); scritture
invariate; nota al modello sugli errori di rete in sandbox.
- Testi della TUI in italiano (benvenuto, segnaposto, suggerimenti, «Errore fatale»).
- Test adattati ai nuovi default (rete del profilo :workspace, allowlist), snapshot e
schemi rigenerati.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -42,6 +42,10 @@ pub use standalone_executable::main;
|
||||
|
||||
use crate::invocation::ExtractHeredocError;
|
||||
|
||||
/// One-line reminder of the patch format, appended by aKode to parse errors
|
||||
/// returned to the model so that it can fix the patch on the next attempt.
|
||||
pub const PATCH_FORMAT_HINT: &str = "Patch format: first line '*** Begin Patch'; then '*** Add File: <path>' followed by the file lines each prefixed with '+' (or '*** Update File: <path>' with '@@' hunks of ' ', '-', '+' lines, or '*** Delete File: <path>'); last line '*** End Patch'. Minimal example, one item per line: '*** Begin Patch' / '*** Add File: hello.py' / '+print(\"hi\")' / '*** End Patch'.";
|
||||
|
||||
/// Special argv[1] flag used when the Codex executable self-invokes to run the
|
||||
/// internal `apply_patch` path.
|
||||
///
|
||||
|
||||
@@ -193,7 +193,7 @@ enum ParseMode {
|
||||
fn parse_patch_text(patch: &str, mode: ParseMode) -> Result<ApplyPatchArgs, ParseError> {
|
||||
let lines: Vec<&str> = patch.trim().lines().collect();
|
||||
let patch_lines = match mode {
|
||||
ParseMode::Strict => check_patch_boundaries_strict(&lines)?,
|
||||
ParseMode::Strict => check_patch_boundaries_strict(&lines)?.to_vec(),
|
||||
ParseMode::Lenient => check_patch_boundaries_lenient(&lines)?,
|
||||
};
|
||||
|
||||
@@ -227,32 +227,121 @@ fn check_patch_boundaries_strict<'a>(lines: &'a [&'a str]) -> Result<&'a [&'a st
|
||||
/// 4 lines total because the heredoc markers take up 2 lines and the patch text
|
||||
/// must have at least 2 lines.
|
||||
///
|
||||
/// aKode: local models (e.g. Qwen) often emit an otherwise valid patch without
|
||||
/// the `*** Begin Patch` first line or without the `*** End Patch` last line,
|
||||
/// or wrap it in a Markdown code fence. In lenient mode we also:
|
||||
/// - strip a surrounding ``` fence (opening and closing fence both present);
|
||||
/// - add `*** Begin Patch` when the first line is `*** Add File: `,
|
||||
/// `*** Update File: ` or `*** Delete File: `;
|
||||
/// - add `*** End Patch` when the patch starts correctly and the last line is
|
||||
/// not another `***` marker (except `*** End of File`).
|
||||
///
|
||||
/// Any other shape stays an error. The hunk parser still validates every line,
|
||||
/// and the resulting patch goes through the same verification, sandbox and
|
||||
/// approval path as a well-formed one.
|
||||
///
|
||||
/// If successful, returns the lines of the patch text that contain the patch
|
||||
/// contents, excluding the heredoc markers.
|
||||
fn check_patch_boundaries_lenient<'a>(
|
||||
original_lines: &'a [&'a str],
|
||||
) -> Result<&'a [&'a str], ParseError> {
|
||||
) -> Result<Vec<&'a str>, ParseError> {
|
||||
let original_parse_error = match check_patch_boundaries_strict(original_lines) {
|
||||
Ok(lines) => return Ok(lines),
|
||||
Ok(lines) => return Ok(lines.to_vec()),
|
||||
Err(e) => e,
|
||||
};
|
||||
|
||||
match original_lines {
|
||||
[first, .., last] => {
|
||||
let lines = strip_code_fence(original_lines);
|
||||
if lines.len() != original_lines.len() {
|
||||
if let Ok(lines) = check_patch_boundaries_strict(lines) {
|
||||
return Ok(lines.to_vec());
|
||||
}
|
||||
}
|
||||
|
||||
let (lines, parse_error) = match lines {
|
||||
[first, .., last]
|
||||
if (first == &"<<EOF" || first == &"<<'EOF'" || first == &"<<\"EOF\"")
|
||||
&& last.ends_with("EOF")
|
||||
&& original_lines.len() >= 4
|
||||
{
|
||||
let inner_lines = &original_lines[1..original_lines.len() - 1];
|
||||
check_patch_boundaries_strict(inner_lines)
|
||||
} else {
|
||||
Err(original_parse_error)
|
||||
&& lines.len() >= 4 =>
|
||||
{
|
||||
let inner_lines = &lines[1..lines.len() - 1];
|
||||
match check_patch_boundaries_strict(inner_lines) {
|
||||
Ok(inner_lines) => return Ok(inner_lines.to_vec()),
|
||||
Err(inner_error) => (inner_lines, inner_error),
|
||||
}
|
||||
}
|
||||
_ => Err(original_parse_error),
|
||||
_ => (lines, original_parse_error),
|
||||
};
|
||||
|
||||
add_missing_patch_markers(lines).ok_or(parse_error)
|
||||
}
|
||||
|
||||
/// Removes a Markdown code fence around the patch (```` ``` ````, ```` ```diff ````,
|
||||
/// ```` ```patch ````...). Both fences must be present; otherwise the lines are
|
||||
/// returned unchanged.
|
||||
fn strip_code_fence<'a>(lines: &'a [&'a str]) -> &'a [&'a str] {
|
||||
match lines {
|
||||
[first, inner @ .., last] if lines.len() >= 3 => {
|
||||
let first = first.trim();
|
||||
let info = first.strip_prefix("```").map(str::trim);
|
||||
let is_fence_open = info.is_some_and(|info| {
|
||||
!info.contains('`') && info.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
|
||||
});
|
||||
if is_fence_open && last.trim() == "```" {
|
||||
inner
|
||||
} else {
|
||||
lines
|
||||
}
|
||||
}
|
||||
_ => lines,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds `*** Begin Patch` / `*** End Patch` when they are missing but the
|
||||
/// content is unambiguously a patch. Returns `None` when the shape is anything
|
||||
/// else, so the caller can report the original error.
|
||||
fn add_missing_patch_markers<'a>(lines: &[&'a str]) -> Option<Vec<&'a str>> {
|
||||
let first = lines.first()?.trim();
|
||||
let last = lines.last()?.trim();
|
||||
let starts_with_hunk = [ADD_FILE_MARKER, UPDATE_FILE_MARKER, DELETE_FILE_MARKER]
|
||||
.iter()
|
||||
.any(|marker| first.starts_with(marker.trim_end()));
|
||||
let has_begin = first == BEGIN_PATCH_MARKER;
|
||||
if !has_begin && !starts_with_hunk {
|
||||
return None;
|
||||
}
|
||||
if has_begin && lines.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let has_end = lines.len() > 1 && last == END_PATCH_MARKER;
|
||||
if !has_end && last.starts_with("***") && last != EOF_MARKER {
|
||||
// Some other (possibly misspelled) marker in last position: ambiguous.
|
||||
let is_hunk_header = [ADD_FILE_MARKER, DELETE_FILE_MARKER]
|
||||
.iter()
|
||||
.any(|marker| last.starts_with(marker.trim_end()));
|
||||
if !is_hunk_header {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
// A stray `*** Begin Patch` or `*** End Patch` in the middle is ambiguous too.
|
||||
let inner_start = usize::from(has_begin);
|
||||
let inner_end = lines.len() - usize::from(has_end);
|
||||
if lines[inner_start..inner_end]
|
||||
.iter()
|
||||
.any(|line| matches!(line.trim(), BEGIN_PATCH_MARKER | END_PATCH_MARKER))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut normalized = Vec::with_capacity(lines.len() + 2);
|
||||
if !has_begin {
|
||||
normalized.push(BEGIN_PATCH_MARKER);
|
||||
}
|
||||
normalized.extend_from_slice(lines);
|
||||
if !has_end {
|
||||
normalized.push(END_PATCH_MARKER);
|
||||
}
|
||||
Some(normalized)
|
||||
}
|
||||
|
||||
fn check_start_and_end_lines_strict(
|
||||
first_line: Option<&&str>,
|
||||
last_line: Option<&&str>,
|
||||
@@ -636,6 +725,8 @@ fn test_parse_patch_lenient() {
|
||||
parse_patch_text(&patch_text_with_missing_closing_heredoc, ParseMode::Strict),
|
||||
Err(expected_error)
|
||||
);
|
||||
// aKode: a trailing `*** Update File:` header is not completed with
|
||||
// `*** End Patch` (the hunk would be empty), so the error is unchanged.
|
||||
assert_eq!(
|
||||
parse_patch_text(&patch_text_with_missing_closing_heredoc, ParseMode::Lenient),
|
||||
Err(InvalidPatchError(
|
||||
@@ -644,6 +735,178 @@ fn test_parse_patch_lenient() {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn add_hello_args(patch: &str) -> ApplyPatchArgs {
|
||||
ApplyPatchArgs {
|
||||
hunks: vec![AddFile {
|
||||
path: PathBuf::from("hello.py"),
|
||||
contents: "print(1)\nprint(2)\n".to_string(),
|
||||
}],
|
||||
patch: patch.to_string(),
|
||||
workdir: None,
|
||||
environment_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
const NORMALIZED_HELLO_PATCH: &str =
|
||||
"*** Begin Patch\n*** Add File: hello.py\n+print(1)\n+print(2)\n*** End Patch";
|
||||
|
||||
#[test]
|
||||
fn test_lenient_adds_missing_begin_patch() {
|
||||
let patch = "*** Add File: hello.py\n+print(1)\n+print(2)\n*** End Patch\n";
|
||||
assert_eq!(
|
||||
parse_patch_text(patch, ParseMode::Lenient),
|
||||
Ok(add_hello_args(NORMALIZED_HELLO_PATCH))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_patch_text(patch, ParseMode::Strict),
|
||||
Err(InvalidPatchError(
|
||||
"The first line of the patch must be '*** Begin Patch'".to_string()
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lenient_adds_missing_end_patch() {
|
||||
let patch = "*** Begin Patch\n*** Add File: hello.py\n+print(1)\n+print(2)\n";
|
||||
assert_eq!(
|
||||
parse_patch_text(patch, ParseMode::Lenient),
|
||||
Ok(add_hello_args(NORMALIZED_HELLO_PATCH))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_patch_text(patch, ParseMode::Strict),
|
||||
Err(InvalidPatchError(
|
||||
"The last line of the patch must be '*** End Patch'".to_string()
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lenient_adds_both_markers() {
|
||||
let patch = "*** Add File: hello.py\n+print(1)\n+print(2)";
|
||||
assert_eq!(
|
||||
parse_patch_text(patch, ParseMode::Lenient),
|
||||
Ok(add_hello_args(NORMALIZED_HELLO_PATCH))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lenient_adds_markers_for_update_and_delete() {
|
||||
let update = "*** Update File: file2.py\n import foo\n+bar";
|
||||
let args = parse_patch_text(update, ParseMode::Lenient).expect("update parses");
|
||||
assert_eq!(
|
||||
args.patch,
|
||||
"*** Begin Patch\n*** Update File: file2.py\n import foo\n+bar\n*** End Patch"
|
||||
);
|
||||
assert!(matches!(args.hunks.as_slice(), [UpdateFile { .. }]));
|
||||
|
||||
let delete = "*** Delete File: old.txt\n*** End Patch";
|
||||
let args = parse_patch_text(delete, ParseMode::Lenient).expect("delete parses");
|
||||
assert_eq!(
|
||||
args.hunks,
|
||||
vec![DeleteFile {
|
||||
path: PathBuf::from("old.txt")
|
||||
}]
|
||||
);
|
||||
|
||||
let delete_last = "*** Begin Patch\n*** Delete File: old.txt";
|
||||
let args = parse_patch_text(delete_last, ParseMode::Lenient).expect("delete parses");
|
||||
assert_eq!(
|
||||
args.hunks,
|
||||
vec![DeleteFile {
|
||||
path: PathBuf::from("old.txt")
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lenient_strips_code_fence() {
|
||||
for fence in ["```", "```diff", "```patch", "``` text"] {
|
||||
let full = format!("{fence}\n{NORMALIZED_HELLO_PATCH}\n```\n");
|
||||
assert_eq!(
|
||||
parse_patch_text(&full, ParseMode::Lenient),
|
||||
Ok(add_hello_args(NORMALIZED_HELLO_PATCH)),
|
||||
"fence {fence:?} with markers"
|
||||
);
|
||||
let bare = format!("{fence}\n*** Add File: hello.py\n+print(1)\n+print(2)\n```");
|
||||
assert_eq!(
|
||||
parse_patch_text(&bare, ParseMode::Lenient),
|
||||
Ok(add_hello_args(NORMALIZED_HELLO_PATCH)),
|
||||
"fence {fence:?} without markers"
|
||||
);
|
||||
assert!(parse_patch_text(&full, ParseMode::Strict).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lenient_keeps_ambiguous_patches_as_errors() {
|
||||
let first_line_error =
|
||||
InvalidPatchError("The first line of the patch must be '*** Begin Patch'".to_string());
|
||||
let last_line_error =
|
||||
InvalidPatchError("The last line of the patch must be '*** End Patch'".to_string());
|
||||
|
||||
// Text before the first hunk.
|
||||
assert_eq!(
|
||||
parse_patch_text(
|
||||
"Here is the patch:\n*** Add File: hello.py\n+print(1)\n*** End Patch",
|
||||
ParseMode::Lenient
|
||||
),
|
||||
Err(first_line_error.clone())
|
||||
);
|
||||
// Only the opening fence.
|
||||
assert_eq!(
|
||||
parse_patch_text(
|
||||
"```diff\n*** Add File: hello.py\n+print(1)\n*** End Patch",
|
||||
ParseMode::Lenient
|
||||
),
|
||||
Err(first_line_error.clone())
|
||||
);
|
||||
// Misspelled end marker.
|
||||
assert_eq!(
|
||||
parse_patch_text(
|
||||
"*** Begin Patch\n*** Add File: hello.py\n+print(1)\n*** End Patch ***",
|
||||
ParseMode::Lenient
|
||||
),
|
||||
Err(last_line_error.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
parse_patch_text(
|
||||
"*** Begin Patch\n*** Add File: hello.py\n+print(1)\n*** End",
|
||||
ParseMode::Lenient
|
||||
),
|
||||
Err(last_line_error.clone())
|
||||
);
|
||||
// A stray end marker in the middle, with trailing text after it.
|
||||
assert_eq!(
|
||||
parse_patch_text(
|
||||
"*** Add File: hello.py\n+print(1)\n*** End Patch\nDone!",
|
||||
ParseMode::Lenient
|
||||
),
|
||||
Err(first_line_error.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
parse_patch_text(
|
||||
"*** Begin Patch\n*** Add File: hello.py\n+print(1)\n*** End Patch\nDone!",
|
||||
ParseMode::Lenient
|
||||
),
|
||||
Err(last_line_error)
|
||||
);
|
||||
// Not a patch at all.
|
||||
assert_eq!(
|
||||
parse_patch_text("print(1)", ParseMode::Lenient),
|
||||
Err(first_line_error)
|
||||
);
|
||||
// Lines without the `+` prefix are still rejected by the hunk parser.
|
||||
assert!(
|
||||
parse_patch_text(
|
||||
"*** Add File: hello.py\nprint(1)\n*** End Patch",
|
||||
ParseMode::Lenient
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_patch_environment_id_preamble() {
|
||||
assert_eq!(
|
||||
|
||||
Reference in New Issue
Block a user