Harden plan parent: first DECISION, soft patches, and empty-tool step retry.
Stop import/fence prompt breakage, prefer modern workbook imports, accept common patch shapes, and recover when workers CALL disallowed tools. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
ecc92f473a
commit
1bf414c745
7 files changed
+317
-39
No files matched your search
@@ -532,7 +532,7 @@ impl HostFn {
|
||||
Self::ExtNativePath => &["name"],
|
||||
Self::OuterCallLine => &[],
|
||||
Self::TextPatch => &["path", "find", "replace"],
|
||||
Self::ApplyPatchBlocks => &["path", "text"],
|
||||
Self::ApplyPatchBlocks => &["path", "text", "soft"],
|
||||
Self::WritebackScanPath => &["path"],
|
||||
Self::MapSet => &["map", "key", "value"],
|
||||
Self::ListAppend => &["list", "item"],
|
||||
@@ -842,9 +842,12 @@ pub fn call_host(
|
||||
require(bound, "find")?,
|
||||
require(bound, "replace")?,
|
||||
),
|
||||
HostFn::ApplyPatchBlocks => {
|
||||
fs::apply_patch_blocks(ctx, require(bound, "path")?, require(bound, "text")?)
|
||||
}
|
||||
HostFn::ApplyPatchBlocks => fs::apply_patch_blocks(
|
||||
ctx,
|
||||
require(bound, "path")?,
|
||||
require(bound, "text")?,
|
||||
bound.get("soft"),
|
||||
),
|
||||
HostFn::WritebackScanPath => writeback::scan_path(ctx, require(bound, "path")?),
|
||||
HostFn::WritebackRecord => writeback::record(
|
||||
ctx,
|
||||
|
||||
+240
-3
@@ -139,7 +139,7 @@ pub fn text_patch(ctx: &HostContext, path: &Value, find: &Value, replace: &Value
|
||||
|
||||
/// Apply one or more FIND/REPLACE blocks from plan-reply text.
|
||||
///
|
||||
/// Blocks:
|
||||
/// Preferred blocks:
|
||||
/// ```text
|
||||
/// <<<
|
||||
/// FIND
|
||||
@@ -149,10 +149,41 @@ pub fn text_patch(ctx: &HostContext, path: &Value, find: &Value, replace: &Value
|
||||
/// <new>
|
||||
/// >>>
|
||||
/// ```
|
||||
pub fn apply_patch_blocks(ctx: &HostContext, path: &Value, text: &Value) -> Result<Value, String> {
|
||||
///
|
||||
/// Also accepts fenced pairs (common model mistake):
|
||||
/// ````text
|
||||
/// ```find
|
||||
/// <old>
|
||||
/// ```
|
||||
/// ```replace
|
||||
/// <new>
|
||||
/// ```
|
||||
/// ````
|
||||
pub fn apply_patch_blocks(
|
||||
ctx: &HostContext,
|
||||
path: &Value,
|
||||
text: &Value,
|
||||
soft: Option<&Value>,
|
||||
) -> Result<Value, String> {
|
||||
if !ctx.allow_fs_write() {
|
||||
return Err("apply_patch_blocks denied by host policy".into());
|
||||
}
|
||||
let soft = match soft {
|
||||
None | Some(Value::None) => false,
|
||||
Some(v) => v.truthy(),
|
||||
};
|
||||
match apply_patch_blocks_inner(ctx, path, text) {
|
||||
Ok(n) => Ok(n),
|
||||
Err(_e) if soft => Ok(Value::Int(0)),
|
||||
Err(e) => Err(e),
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_patch_blocks_inner(
|
||||
ctx: &HostContext,
|
||||
path: &Value,
|
||||
text: &Value,
|
||||
) -> Result<Value, String> {
|
||||
let blocks = parse_patch_blocks(text_body(text)?)?;
|
||||
if blocks.is_empty() {
|
||||
return Ok(Value::Int(0));
|
||||
@@ -201,9 +232,125 @@ fn parse_patch_blocks(text: &str) -> Result<Vec<(String, String)>, String> {
|
||||
let replace = strip_labeled(replace_part, "REPLACE")?;
|
||||
out.push((find, replace));
|
||||
}
|
||||
if out.is_empty() {
|
||||
parse_fence_find_replace(text, &mut out)?;
|
||||
}
|
||||
if out.is_empty() {
|
||||
parse_begin_patch_hunks(text, &mut out)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// ```find … ``` followed by ```replace … ``` (label case-insensitive).
|
||||
fn parse_fence_find_replace(text: &str, out: &mut Vec<(String, String)>) -> Result<(), String> {
|
||||
let mut i = 0;
|
||||
while i < text.len() {
|
||||
let Some(rel) = text[i..].find("```") else {
|
||||
break;
|
||||
};
|
||||
let open = i + rel;
|
||||
let after_ticks = open + 3;
|
||||
let header_end = text[after_ticks..]
|
||||
.find('\n')
|
||||
.map(|n| after_ticks + n)
|
||||
.unwrap_or(text.len());
|
||||
let label = text[after_ticks..header_end]
|
||||
.trim()
|
||||
.trim_matches('`')
|
||||
.to_ascii_lowercase();
|
||||
if label != "find" {
|
||||
i = after_ticks;
|
||||
continue;
|
||||
}
|
||||
let body_start = if header_end < text.len() {
|
||||
header_end + 1
|
||||
} else {
|
||||
header_end
|
||||
};
|
||||
let Some(rel_close) = text[body_start..].find("```") else {
|
||||
return Err("apply_patch_blocks: unclosed ```find fence".into());
|
||||
};
|
||||
let find_end = body_start + rel_close;
|
||||
let find = text[body_start..find_end]
|
||||
.trim_end_matches(['\r', '\n'])
|
||||
.to_string();
|
||||
let mut j = find_end + 3;
|
||||
while j < text.len() && text.as_bytes()[j].is_ascii_whitespace() {
|
||||
j += 1;
|
||||
}
|
||||
if text[j..].starts_with("```") {
|
||||
j += 3;
|
||||
} else {
|
||||
return Err("apply_patch_blocks: ```find without following ```replace".into());
|
||||
}
|
||||
let rep_header_end = text[j..]
|
||||
.find('\n')
|
||||
.map(|n| j + n)
|
||||
.unwrap_or(text.len());
|
||||
let rep_label = text[j..rep_header_end]
|
||||
.trim()
|
||||
.trim_matches('`')
|
||||
.to_ascii_lowercase();
|
||||
if rep_label != "replace" {
|
||||
return Err("apply_patch_blocks: ```find without following ```replace".into());
|
||||
}
|
||||
let rep_body_start = if rep_header_end < text.len() {
|
||||
rep_header_end + 1
|
||||
} else {
|
||||
rep_header_end
|
||||
};
|
||||
let Some(rel_rep_close) = text[rep_body_start..].find("```") else {
|
||||
return Err("apply_patch_blocks: unclosed ```replace fence".into());
|
||||
};
|
||||
let rep_end = rep_body_start + rel_rep_close;
|
||||
let replace = text[rep_body_start..rep_end]
|
||||
.trim_end_matches(['\r', '\n'])
|
||||
.to_string();
|
||||
out.push((find, replace));
|
||||
i = rep_end + 3;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Minimal support for `*** Begin Patch` / `*** End Patch` with `-`/`+` line pairs
|
||||
/// (same line count preferred; falls back to joining all `-` vs all `+` in the hunk).
|
||||
fn parse_begin_patch_hunks(text: &str, out: &mut Vec<(String, String)>) -> Result<(), String> {
|
||||
const BEGIN: &str = "*** Begin Patch";
|
||||
const END: &str = "*** End Patch";
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find(BEGIN) {
|
||||
let after = &rest[start + BEGIN.len()..];
|
||||
let end = after
|
||||
.find(END)
|
||||
.ok_or_else(|| "apply_patch_blocks: unclosed *** Begin Patch".to_string())?;
|
||||
let body = &after[..end];
|
||||
rest = &after[end + END.len()..];
|
||||
let mut minus: Vec<&str> = Vec::new();
|
||||
let mut plus: Vec<&str> = Vec::new();
|
||||
for line in body.lines() {
|
||||
if let Some(s) = line.strip_prefix('-') {
|
||||
if s.starts_with('-') {
|
||||
continue; // skip --- / file headers like ---
|
||||
}
|
||||
// skip diff file headers "*** Update File" already not prefixed with single -
|
||||
minus.push(s.strip_prefix(' ').unwrap_or(s));
|
||||
} else if let Some(s) = line.strip_prefix('+') {
|
||||
if s.starts_with('+') {
|
||||
continue;
|
||||
}
|
||||
plus.push(s.strip_prefix(' ').unwrap_or(s));
|
||||
}
|
||||
}
|
||||
if minus.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let find = minus.join("\n");
|
||||
let replace = plus.join("\n");
|
||||
out.push((find, replace));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn strip_labeled(chunk: &str, label: &str) -> Result<String, String> {
|
||||
let t = chunk.trim();
|
||||
let upper = t.to_ascii_uppercase();
|
||||
@@ -285,9 +432,99 @@ REPLACE
|
||||
CC
|
||||
>>>
|
||||
"#;
|
||||
let n = apply_patch_blocks(&ctx, &Value::Text("a.md".into()), &Value::Text(reply.into())).unwrap();
|
||||
let n = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, Value::Int(2));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "AA bb CC");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_patch_blocks_fence_find_replace() {
|
||||
let dir = temp_workspace("fence");
|
||||
let path = dir.join("a.md");
|
||||
fs::write(&path, "old line\nkeep\n").unwrap();
|
||||
let ctx = write_ctx(&dir);
|
||||
let reply = "DECISION: CONTINUE\nPATCH:\n```find\nold line\n```\n```replace\nnew line\n```\n";
|
||||
let n = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, Value::Int(1));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "new line\nkeep\n");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_patch_blocks_begin_patch() {
|
||||
let dir = temp_workspace("beginpatch");
|
||||
let path = dir.join("a.md");
|
||||
fs::write(
|
||||
&path,
|
||||
"> ext/ai/llm.mq.md\n> lib/json.mq.md\n",
|
||||
)
|
||||
.unwrap();
|
||||
let ctx = write_ctx(&dir);
|
||||
let reply = r#"
|
||||
DECISION: CONTINUE
|
||||
PATCH:
|
||||
```patch
|
||||
*** Begin Patch
|
||||
*** Update File: a.md
|
||||
@@
|
||||
-> ext/ai/llm.mq.md
|
||||
-> lib/json.mq.md
|
||||
+import llm:ext/ai/llm.mq.md
|
||||
+import json:lib/json.mq.md
|
||||
*** End Patch
|
||||
```
|
||||
"#;
|
||||
let n = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, Value::Int(1));
|
||||
assert_eq!(
|
||||
fs::read_to_string(&path).unwrap(),
|
||||
"import llm:ext/ai/llm.mq.md\nimport json:lib/json.mq.md\n"
|
||||
);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_patch_blocks_soft_miss() {
|
||||
let dir = temp_workspace("soft");
|
||||
let path = dir.join("a.md");
|
||||
fs::write(&path, "hello").unwrap();
|
||||
let ctx = write_ctx(&dir);
|
||||
let reply = "<<<\nFIND\nmissing\n===\nREPLACE\nx\n>>>\n";
|
||||
let hard = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
None,
|
||||
);
|
||||
assert!(hard.is_err());
|
||||
let n = apply_patch_blocks(
|
||||
&ctx,
|
||||
&Value::Text("a.md".into()),
|
||||
&Value::Text(reply.into()),
|
||||
Some(&Value::Bool(true)),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(n, Value::Int(0));
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "hello");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user