fix(agent): harden workbook patches against whole-file rewrites

Reject large whole-file FIND spans, narrow soft=True to miss-only, check
decompose CONTINUE patch counts, and unit-test workbook_solidify.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-28 16:22:39 +08:00
1 parent c36383bf28
commit d0b184939f
6 files changed
+146 -6

No files matched your search

+2 -2
View File
@@ -2,7 +2,7 @@
| | |
|---|---|
| 状态 | **规划中**(以调研结论为输入) |
| 状态 | **进行中 · A0 开工**(整文件补丁护栏 + soft 收紧 + solidify 单测) |
| 日期 | 2026-08-28 |
| 调研 | [agent-frameworks-and-marqdo.md](../research/agent-frameworks-and-marqdo.md) |
| 设计 | [ext-agent.md](../design/ext-agent.md) · [ext-agent-plan.md](../design/ext-agent-plan.md) · [ext-agent-parent.md](../design/ext-agent-parent.md) · [okf.md](../design/okf.md) |
@@ -24,7 +24,7 @@
| 波次 | 主题 | 验收线索 |
|------|------|----------|
| **A0** | 工作簿补丁 / 固化可靠性 | 金样:多轮 CONTINUE 后源码可跑;禁止整文件重写 |
| **A0** | 工作簿补丁 / 固化可靠性 | **in progress** — `apply_patch_blocks` 禁整文件 FIND;`soft` 仅吞「FIND not found」;decompose CONTINUE 检查 `n`;`workbook_solidify` 单测 |
| **A1** | OKF 复用飞轮(lookup / near / soft_match UX) | 二次同类 `plan` 走快路径;策展可读 |
| **A2** | 过程可见(stream + view 过程卡) | 对齐 [agent-streaming.md](agent-streaming.md);真相仍可写回 |
| **A3** | 上下文预算(源码/Skill 渐进披露) | 长 runbook 不爆窗,仍保持「源码即提示」 |
+8 -1
View File
@@ -1717,7 +1717,14 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
1. `dec` == CONTINUE
*n = > fs.apply_patch_blocks path=`path` text=`last_reply` soft=True*
*_ = 1*
1. `n`
*_ = 1*
2. *
*done = 1*
*status = "error"*
*err = "no patches applied"*
*summary = > extract_plan_summary reply=`last_reply`*
*skip_loop = 1*
2. `dec` == RUN
*_ = 1*
3. `dec` == DONE
+1 -1
View File
@@ -56,6 +56,6 @@ Exact FIND→REPLACE once in a UTF-8 text file. `find` must match exactly once.
Apply plan-style triple-angle FIND/REPLACE blocks from `text` to `path`.
Also accepts fenced find/replace pairs and minimal Begin Patch hunks.
When `soft=True`, FIND failures return `0` instead of aborting the run.
When `soft=True`, **only** “FIND not found” returns `0` (run continues). Empty FIND, multi-match, parse errors, and whole-file FIND still abort — whole-file rewrite is forbidden.
**> host_apply_patch_blocks path=`path` text=`text` soft=`soft`**
+1 -1
View File
@@ -54,6 +54,6 @@ description: 中文文件系统包装
+ `文本`
+ `软失败`=False
解析规划回复中的 FIND/REPLACE 块并应用到 `路径`。`软失败=真` 时找不到 FIND 返回 0 而不中断。
解析规划回复中的 FIND/REPLACE 块并应用到 `路径`。`软失败=真` 时仅「找不到 FIND」返回 0;空 FIND、多匹配、整文件重写仍报错。
**> host_apply_patch_blocks path=`路径` text=`文本` soft=`软失败`**
+50
View File
@@ -1346,4 +1346,54 @@ mod tests {
let s = near_score(a, b);
assert!(s < 0.78, "expected below default threshold, got {s}");
}
#[test]
fn workbook_solidify_rewrites_step_workbook() {
let dir = std::env::temp_dir().join(format!(
"marqdo-solidify-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let path = dir.join("wb.mq.md");
fs::write(
&path,
"---\ntitle: t\n---\n\n# main\n\n*`r` = > `worker`.step task=hi *\n**`r`**\n",
)
.unwrap();
let path_s = path.to_string_lossy().into_owned();
let args = json!({
"path": path_s,
"observation": { "value": "pong" }
});
let out = workbook_solidify(&args).unwrap();
assert_eq!(out.get("solidified").and_then(|v| v.as_bool()), Some(true));
let src = fs::read_to_string(&path).unwrap();
assert!(!needs_step_solidify(&src), "still has step: {src}");
assert!(src.contains("pong"), "{src}");
let again = workbook_solidify(&args).unwrap();
assert_eq!(
again.get("reason").and_then(|v| v.as_str()),
Some("already_solid")
);
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn workbook_solidify_no_result() {
let dir = std::env::temp_dir().join(format!(
"marqdo-solidify-nr-{}",
std::process::id()
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
let path = dir.join("wb.mq.md");
fs::write(&path, "*`r` = > `worker`.step task=hi *\n").unwrap();
let path_s = path.to_string_lossy().into_owned();
let args = json!({ "path": path_s });
let out = workbook_solidify(&args).unwrap();
assert_eq!(out.get("solidified").and_then(|v| v.as_bool()), Some(false));
assert_eq!(out.get("reason").and_then(|v| v.as_str()), Some("no_result"));
let _ = fs::remove_dir_all(&dir);
}
}
+84 -1
View File
@@ -174,11 +174,30 @@ pub fn apply_patch_blocks(
};
match apply_patch_blocks_inner(ctx, path, text) {
Ok(n) => Ok(n),
Err(_e) if soft => Ok(Value::Int(0)),
// soft only swallows unique-FIND miss — never parse / multi-match / whole-file.
Err(e) if soft && e.contains("FIND not found") => Ok(Value::Int(0)),
Err(e) => Err(e),
}
}
/// Reject FIND that rewrites a non-trivial file wholesale (exact or ≥90% span).
/// Tiny files may be replaced entirely (e.g. two-line import rewrites).
fn find_spans_whole_file(src: &str, find: &str) -> bool {
const MIN_BYTES: usize = 800;
let st = src.trim();
let ft = find.trim();
if ft.is_empty() || src.len() < MIN_BYTES {
return false;
}
if st == ft {
return true;
}
if !src.contains(find) {
return false;
}
find.len().saturating_mul(10) >= src.len().saturating_mul(9)
}
fn apply_patch_blocks_inner(
ctx: &HostContext,
path: &Value,
@@ -195,6 +214,12 @@ fn apply_patch_blocks_inner(
if find.is_empty() {
return Err("apply_patch_blocks: empty FIND".into());
}
if find_spans_whole_file(&src, &find) {
return Err(
"apply_patch_blocks: FIND spans entire file (whole-file rewrite forbidden)"
.into(),
);
}
let count = src.matches(&find).count();
if count == 0 {
return Err(format!(
@@ -527,4 +552,62 @@ PATCH:
assert_eq!(fs::read_to_string(&path).unwrap(), "hello");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn apply_patch_blocks_rejects_whole_file_find() {
let dir = temp_workspace("whole");
let path = dir.join("a.md");
let body = format!(
"---\ntitle: workbook\n---\n\n# main\n\n{}",
"line padding for size threshold\n".repeat(40)
);
assert!(body.len() >= 800, "fixture too small: {}", body.len());
fs::write(&path, &body).unwrap();
let ctx = write_ctx(&dir);
let reply = format!(
"<<<\nFIND\n{body}===\nREPLACE\n# main\n\n> print text=bye\n>>>\n"
);
let err = apply_patch_blocks(
&ctx,
&Value::Text("a.md".into()),
&Value::Text(reply),
None,
)
.unwrap_err();
assert!(
err.contains("whole-file rewrite forbidden"),
"unexpected err={err}"
);
assert_eq!(fs::read_to_string(&path).unwrap(), body);
let soft_err = apply_patch_blocks(
&ctx,
&Value::Text("a.md".into()),
&Value::Text(format!(
"<<<\nFIND\n{body}===\nREPLACE\nx\n>>>\n"
)),
Some(&Value::Bool(true)),
)
.unwrap_err();
assert!(soft_err.contains("whole-file rewrite forbidden"));
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn apply_patch_blocks_soft_keeps_multi_match_hard() {
let dir = temp_workspace("multisoft");
let path = dir.join("a.md");
fs::write(&path, "xx xx").unwrap();
let ctx = write_ctx(&dir);
let reply = "<<<\nFIND\nxx\n===\nREPLACE\nYY\n>>>\n";
let err = apply_patch_blocks(
&ctx,
&Value::Text("a.md".into()),
&Value::Text(reply.into()),
Some(&Value::Bool(true)),
)
.unwrap_err();
assert!(err.contains("matched 2 times"), "unexpected err={err}");
assert_eq!(fs::read_to_string(&path).unwrap(), "xx xx");
let _ = fs::remove_dir_all(&dir);
}
}