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:
cflmyandCursor committed 2026-08-16 12:07:17 +08:00
1 parent ecc92f473a
commit 1bf414c745
7 files changed
+317 -39

No files matched your search

+39 -26
View File
@@ -31,7 +31,7 @@ Assemble a readable prompt: standing, task, tools, call site, source, skill, and
*`skill` = > agent_marqdo_skill *
*`task_s` = > json.stringify value=`task` *
*`esc` = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- task ---\n","c":"\n\n--- tools ---\n","d":"\n\n--- call site ---\n","e":"\n\n--- source (.mq.md) ---\n","f":"\n\n--- marqdo skill ---\n","g":"\n\n--- how to act ---\nTools are ## functions in the source above. To call one, reply with exactly one line: CALL:<name>\n(Chinese ok: 调用:<name>)\nOtherwise reply with the final answer only.\nTools run via Marqdo subtask (spawn fn / wait).\n"} *
*`esc` = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- task ---\n","c":"\n\n--- tools ---\n","d":"\n\n--- call site ---\n","e":"\n\n--- source (.mq.md) ---\n","f":"\n\n--- marqdo skill ---\n","g":"\n\n--- how to act ---\nCall ONLY names listed under --- tools --- (whitelist). If that section is empty or says none, do NOT emit CALL / 调用 — reply with the final answer only.\nNever CALL internal framework helpers (build_step_context, plan, inspect_workbook, etc.).\nWhen calling an allowed tool, reply with exactly one line: CALL:<name>\n(Chinese ok: 调用:<name>)\nOtherwise reply with the final answer only.\nTools run via Marqdo subtask (spawn fn / wait).\n"} *
*`a` = > json.get value=`esc` key=a *
*`b` = > json.get value=`esc` key=b *
*`c` = > json.get value=`esc` key=c *
@@ -100,7 +100,7 @@ Allowlist check, then invoke the runbook `##` via `lib/subtask` (`spawn fn=` →
Build a runnable workbook. `skeleton=single` (default): one worker `step`. `skeleton=dual`: research then write agents. On success the parent chooses DONE; runtime `agent_workbook_solidify` freezes the answer.
*`q` = > json.quote text=`goal` *
*`esc` = > json.parse text={"h":"---\ntitle: agent workbook\n> ext/ai/llm.mq.md\n> ext/ai/agent.mq.md\n> lib/json.mq.md\n> lib/sys.mq.md\n> lib/writeback.mq.md\n> lib/subtask.mq.md\n---\n\n# Goal\n\nParent goal is embedded as JSON in # main.\n\n## Solidify\n\nWhen the child returns a good value, parent DECISION: DONE — runtime agent_workbook_solidify freezes the answer as **return** (do not invent long FIND/REPLACE).\n\n# main\n\n> llm.load_env\n\n","s1":"\u002a\u0060model\u0060 = > llm.llm \u002a\n","s2":"\u002a\u0060tools\u0060 = > json.parse text=[] \u002a\n","s3":"\u002a\u0060worker\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You are a workbook worker. Finish the task; do not invent tools. Prefer a direct answer. \u002a\n","s4":"\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","s5":"} \u002a\n","s6":"\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=task \u002a\n","s7":"\u002a\u0060out\u0060 = > \u0060worker\u0060.step task=\u0060task\u0060 stream=True \u002a\n","s7b":"\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=result \u002a\n","s8":"\u002a\u002a\u0060text\u0060\u002a\u002a\n","d3":"\u002a\u0060research\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You gather facts for the goal. Be concise. Do not invent tools. \u002a\n","d3b":"\u002a\u0060writer\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You write the final answer from research notes. Do not invent tools. \u002a\n","d4":"\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","d5":"} \u002a\n","d6":"\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=task \u002a\n","d7":"\u002a\u0060notes\u0060 = > \u0060research\u0060.step task=\u0060task\u0060 stream=True \u002a\n","d8":"\u002a\u0060ns\u0060 = > json.stringify value=\u0060notes\u0060 \u002a\n","d9":"\u002a\u0060wt\u0060 = Write the final answer. Research notes: \u002a\n","d10":"\u002a\u0060wt\u0060 = \u0060wt\u0060 + \u0060ns\u0060 \u002a\n","d11":"\u002a\u0060out\u0060 = > \u0060writer\u0060.step task=\u0060wt\u0060 stream=True \u002a\n","d11b":"\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=result \u002a\n","d12":"\u002a\u002a\u0060text\u0060\u002a\u002a\n"} *
*`esc` = > json.parse text={"h":"---\ntitle: agent workbook\nimport llm:ext/ai/llm.mq.md\nimport agent:ext/ai/agent.mq.md\nimport json:lib/json.mq.md\nimport sys:lib/sys.mq.md\nimport writeback:lib/writeback.mq.md\nimport subtask:lib/subtask.mq.md\n---\n\n# Goal\n\nParent goal is embedded as JSON in # main.\n\n## Solidify\n\nWhen the child returns a good value, parent DECISION: DONE — runtime agent_workbook_solidify freezes the answer as **return** (do not invent long FIND/REPLACE).\n\n# main\n\n> llm.load_env\n\n","s1":"\u002a\u0060model\u0060 = > llm.llm \u002a\n","s2":"\u002a\u0060tools\u0060 = > json.parse text=[] \u002a\n","s3":"\u002a\u0060worker\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You are a workbook worker. tools=[] means never CALL. Finish the task with a direct final answer; do not invent tools. \u002a\n","s4":"\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","s5":"} \u002a\n","s6":"\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=task \u002a\n","s7":"\u002a\u0060out\u0060 = > \u0060worker\u0060.step task=\u0060task\u0060 stream=True \u002a\n","s7b":"\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=result \u002a\n","s8":"\u002a\u002a\u0060text\u0060\u002a\u002a\n","d3":"\u002a\u0060research\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You gather facts for the goal. Be concise. Do not invent tools. \u002a\n","d3b":"\u002a\u0060writer\u0060 = > agent.agent model=\u0060model\u0060 tools=\u0060tools\u0060 standing=You write the final answer from research notes. Do not invent tools. \u002a\n","d4":"\u002a\u0060wrap\u0060 = > json.parse text={\"task\":","d5":"} \u002a\n","d6":"\u002a\u0060task\u0060 = > json.get value=\u0060wrap\u0060 key=task \u002a\n","d7":"\u002a\u0060notes\u0060 = > \u0060research\u0060.step task=\u0060task\u0060 stream=True \u002a\n","d8":"\u002a\u0060ns\u0060 = > json.stringify value=\u0060notes\u0060 \u002a\n","d9":"\u002a\u0060wt\u0060 = Write the final answer. Research notes: \u002a\n","d10":"\u002a\u0060wt\u0060 = \u0060wt\u0060 + \u0060ns\u0060 \u002a\n","d11":"\u002a\u0060out\u0060 = > \u0060writer\u0060.step task=\u0060wt\u0060 stream=True \u002a\n","d11b":"\u002a\u0060text\u0060 = > json.get value=\u0060out\u0060 key=result \u002a\n","d12":"\u002a\u002a\u0060text\u0060\u002a\u002a\n"} *
*`h` = > json.get value=`esc` key=h *
*`s1` = > json.get value=`esc` key=s1 *
*`s2` = > json.get value=`esc` key=s2 *
@@ -819,6 +819,7 @@ Bounded observation for the parent prompt (actionable, short).
+ `reply`
Parse `DECISION: DONE` / `CONTINUE` / `RUN` (Chinese: `决定:完成` / `继续` / `运行`).
**First** matching DECISION / 决定 line wins (ignore later conflicting decisions in the same reply).
*`esc` = > json.parse text={"nl":"\n","fw":":"} *
*`nl` = > json.get value=`esc` key=nl *
@@ -828,36 +829,39 @@ Parse `DECISION: DONE` / `CONTINUE` / `RUN` (Chinese: `决定:完成` / `继
*`found` = None*
- [`line`](`lines`)
*`t` = > trim value=`line` *
*`parts` = > split value=`t` sep=: *
*`n` = > len value=`parts` *
1. `n` > 1
*`head` = > at value=`parts` index=0 *
*`head` = > trim value=`head` *
*`rest` = > at value=`parts` index=1 *
*`rest` = > trim value=`rest` *
1. `head` == DECISION
*`found` = `rest`*
2. `head` == 决定
*`found` = `rest`*
3. *
*`_` = 1*
1. `found`
*`_` = 1*
2. *
*`parts` = > split value=`t` sep=`fw` *
*`t` = > trim value=`line` *
*`parts` = > split value=`t` sep=: *
*`n` = > len value=`parts` *
1. `n` > 1
*`head` = > at value=`parts` index=0 *
*`head` = > trim value=`head` *
*`rest` = > at value=`parts` index=1 *
*`rest` = > trim value=`rest` *
1. `head` == 决定
1. `head` == DECISION
*`found` = `rest`*
2. `head` == DECISION
2. `head` == 决定
*`found` = `rest`*
3. *
*`_` = 1*
2. *
*`_` = 1*
*`parts` = > split value=`t` sep=`fw` *
*`n` = > len value=`parts` *
1. `n` > 1
*`head` = > at value=`parts` index=0 *
*`head` = > trim value=`head` *
*`rest` = > at value=`parts` index=1 *
*`rest` = > trim value=`rest` *
1. `head` == 决定
*`found` = `rest`*
2. `head` == DECISION
*`found` = `rest`*
3. *
*`_` = 1*
2. *
*`_` = 1*
1. `found` == DONE
**"DONE"**
@@ -1032,7 +1036,7 @@ Parent Plan-and-Move prompt. Short protocol only — no long monologues.
*`compact` = > compact_plan_observation observation=`observation` *
*`obs_s` = > json.stringify value=`compact` *
*`goal_s` = > json.stringify value=`goal` *
*`esc` = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- goal ---\n","c":"\n\n--- observation ---\n","d":"\n\n--- skill brief ---\n","tools":"\n\n--- parent tools ---\nCALL:workbook_read | workbook_excerpt | lib_catalog | scratch_tool_write\nCALL:lib.fs.read_text|exists|list_dir | lib.json.parse|stringify | lib.sys.cwd (+ ARGS:{json})\nREAD:source | stderr | stdout | slots\nCreate tools: CONTINUE PATCH add ##, or CALL:scratch_tool_write with NAME line and fenced body.\n","e_rev":"\n\n--- how to act ---\nPlan-and-Move parent. Reply with ONE protocol only (no long reasoning).\n1) exit_code=0 and has_value → DECISION: DONE + one-line SUMMARY. solidify_on_done. Do not CONTINUE just because has_worker_step.\n2) Need more evidence → READ:kind or CALL:tool (then you will be re-prompted).\n3) Failure / wrong value → DECISION: CONTINUE + short PATCH (<20 lines). Never paste user prose into REPLACE.\nProtocols:\nCALL:name\nREAD:kind\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\nPATCH with FIND/REPLACE fences\n","e_dec":"\n\n--- how to act ---\nPRE-RUN decompose. Reply with ONE protocol only (no long reasoning).\n1) Skeleton OK → DECISION: RUN.\n2) Need evidence → READ:source or CALL:workbook_read / lib_catalog.\n3) Reshape → DECISION: CONTINUE + short PATCH (<20 lines).\n4) Fixed answer without LLM → PATCH to return, then RUN or DONE.\nProtocols:\nCALL:name\nREAD:kind\nDECISION: RUN\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\nPATCH with FIND/REPLACE fences\n","f":"\n\n--- explore ---\n"} *
*`esc` = > json.parse text={"a":"\n\n--- standing ---\n","b":"\n\n--- goal ---\n","c":"\n\n--- observation ---\n","d":"\n\n--- skill brief ---\n","tools":"\n\n--- parent tools ---\nCALL:workbook_read | workbook_excerpt | lib_catalog | scratch_tool_write\nCALL:lib.fs.read_text|exists|list_dir | lib.json.parse|stringify | lib.sys.cwd (+ ARGS:{json})\nREAD:source | stderr | stdout | slots\nCreate tools: CONTINUE PATCH add ##, or CALL:scratch_tool_write with NAME line and fenced body.\n","e_rev":"\n\n--- how to act ---\nPlan-and-Move parent. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line.\n1) exit_code=0 and has_value → DECISION: DONE + one-line SUMMARY. solidify_on_done. Do not CONTINUE just because has_worker_step.\n2) Need more evidence → READ:kind or CALL:tool (then you will be re-prompted).\n3) Failure / wrong value → DECISION: CONTINUE + short PATCH (<20 lines). Never paste user prose into REPLACE.\n4) Do NOT CONTINUE only to rewrite frontmatter imports; skeleton already uses import llm:/agent:/json:….\nPATCH must use triple-angle blocks only:\n<<<\nFIND\n<exact old>\n===\nREPLACE\n<new>\n>>>\nDo not use \u0060\u0060\u0060find, \u0060\u0060\u0060replace, or *** Begin Patch ***.\nProtocols:\nCALL:name\nREAD:kind\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\n","e_dec":"\n\n--- how to act ---\nPRE-RUN decompose. Reply with ONE protocol only (no long reasoning). Exactly one DECISION line.\n1) Skeleton OK → DECISION: RUN (preferred). Do not rewrite imports; they are already import llm:/agent:/….\n2) Need evidence → READ:source or CALL:workbook_read / lib_catalog.\n3) Reshape body/logic only → DECISION: CONTINUE + short PATCH (<20 lines).\n4) Fixed answer without LLM → PATCH to return, then RUN or DONE.\nPATCH must use <<< FIND === REPLACE >>> only (no \u0060\u0060\u0060find / Begin Patch).\nProtocols:\nCALL:name\nREAD:kind\nDECISION: RUN\nDECISION: DONE\nSUMMARY: one line\nDECISION: CONTINUE\n","f":"\n\n--- explore ---\n"} *
*`a` = > json.get value=`esc` key=a *
*`b` = > json.get value=`esc` key=b *
*`c` = > json.get value=`esc` key=c *
@@ -1362,9 +1366,18 @@ With `stream=True`, the model call uses SSE; `echo=True` prints delta text to st
*`deny` = > split value=`tool_s` sep=Tool not allowed *
*`deny_n` = > len value=`deny` *
1. `deny_n` > 1
*`out` = > json.set map=`out` key=status value=error *
*`out` = > json.set map=`out` key=error value=`tool_s` *
*`reply` = `tool_s`*
*`task_s` = > json.stringify value=`task` *
*`fp` = "Tool CALL was rejected (not on the tools whitelist). Do NOT emit CALL. Answer the user task directly with the final answer only.\n\nUser task:\n" *
*`fp` = `fp` + `task_s` *
1. `stream`
*`evs_retry` = > `model`.complete prompt=`fp` stream=True echo=`echo` *
*`reply` = > llm.stream_result events=`evs_retry` *
2. *
*`reply` = > `model`.complete prompt=`fp` *
*`out` = > json.set map=`out` key=status value=ok *
*`out` = > json.set map=`out` key=decision value=`decision` *
*`out` = > json.set map=`out` key=denied_tool value=`tool_name` *
*`out` = > json.set map=`out` key=result value=`reply` *
2. *
*`task_s` = > json.stringify value=`task` *
*`fp` = "The user asked:" *
@@ -1703,7 +1716,7 @@ Reuse lookup: exact → alias → canonicalize → optional local n-gram `near`
*`events` = > json.get value=`turn` key=events *
1. `dec` == CONTINUE
*`n` = > fs.apply_patch_blocks path=`path` text=`last_reply` *
*`n` = > fs.apply_patch_blocks path=`path` text=`last_reply` soft=True *
*`_` = 1*
2. `dec` == RUN
*`_` = 1*
@@ -1789,7 +1802,7 @@ Deterministic success stop (loop engineering): when the child already returned a
*`err` = None*
*`left` = 0*
2. `dec` == CONTINUE
*`n` = > fs.apply_patch_blocks path=`path` text=`last_reply` *
*`n` = > fs.apply_patch_blocks path=`path` text=`last_reply` soft=True *
1. `n`
*`left` = `left` - 1*
2. *
+5 -2
View File
@@ -52,7 +52,10 @@ Exact FIND→REPLACE once in a UTF-8 text file. `find` must match exactly once.
## apply_patch_blocks
+ `path`
+ `text`
+ `soft`=False
Apply plan-style `<<<` / FIND / === / REPLACE / `>>>` blocks from `text` to `path`.
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.
**> host_apply_patch_blocks path=`path` text=`text`**
**> host_apply_patch_blocks path=`path` text=`text` soft=`soft`**
+3 -2
View File
@@ -52,7 +52,8 @@ description: 中文文件系统包装
## 应用补丁块
+ `路径`
+ `文本`
+ `软失败`=False
解析规划回复中的 `<<<` / FIND / === / REPLACE / `>>>` 块并应用到 `路径`。
解析规划回复中的 FIND/REPLACE 块并应用到 `路径`。`软失败=真` 时找不到 FIND 返回 0 而不中断。
**> host_apply_patch_blocks path=`路径` text=`文本`**
**> host_apply_patch_blocks path=`路径` text=`文本` soft=`软失败`**
+7 -4
View File
@@ -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
View File
@@ -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);
}
}
+22 -1
View File
@@ -31,6 +31,10 @@ import fs:lib/fs.mq.md
*`r5` = > agent.extract_plan_decision reply=`d5` *
> print text=`r5`
*`d6` = "DECISION: DONE\nSUMMARY: first wins\nDECISION: CONTINUE\nPATCH:\nbogus\n" *
*`r6` = > agent.extract_plan_decision reply=`d6` *
> print text=`r6`
*`act_call` = "CALL:lib_catalog" *
*`a1` = > agent.extract_plan_act reply=`act_call` *
*`a1k` = > json.get value=`a1` key=kind *
@@ -73,7 +77,14 @@ import fs:lib/fs.mq.md
2. *
> print text=solidify-missing
*`paths` = > json.parse text={"p":".marqdo/agent-runs/decision-patch.md","t":"keep old keep"} *
*`has_imp` = > split value=`dual` sep=import llm:ext/ai/llm.mq.md *
*`n_imp` = > len value=`has_imp` *
1. `n_imp` > 1
> print text=import-ok
2. *
> print text=import-missing
*`paths` = > json.parse text={"p":".marqdo/agent-runs/decision-patch.md","t":"keep old keep","fence":"alpha beta","p2":".marqdo/agent-runs/decision-fence.md"} *
*`path` = > json.get value=`paths` key=p *
*`seed` = > json.get value=`paths` key=t *
> fs.write_text path=`path` text=`seed`
@@ -81,3 +92,13 @@ import fs:lib/fs.mq.md
> print text=`n`
*`out` = > fs.read_text path=`path` *
> print text=`out`
*`path2` = > json.get value=`paths` key=p2 *
*`seed2` = > json.get value=`paths` key=fence *
> fs.write_text path=`path2` text=`seed2`
*`fence_pack` = > json.parse text={"t":"DECISION: CONTINUE\n\u0060\u0060\u0060find\nalpha\n\u0060\u0060\u0060\n\u0060\u0060\u0060replace\nALPHA\n\u0060\u0060\u0060\n"} *
*`fence_reply` = > json.get value=`fence_pack` key=t *
*`n2` = > fs.apply_patch_blocks path=`path2` text=`fence_reply` *
> print text=`n2`
*`out2` = > fs.read_text path=`path2` *
> print text=`out2`
+1 -1
View File
@@ -1731,7 +1731,7 @@ fn ext_agent_plan_confirm() {
fn ext_agent_plan_decision() {
assert_out(
"tests/ext/agent-plan-decision.mq.md",
"DONE\nall good\nCONTINUE\nDONE\nRUN\nRUN\ncall\nlib_catalog\nread\nstderr\ndecision\ncatalog-ok\ndual-ok\nsolidify-ok\n1\nkeep new keep",
"DONE\nall good\nCONTINUE\nDONE\nRUN\nRUN\nDONE\ncall\nlib_catalog\nread\nstderr\ndecision\ncatalog-ok\ndual-ok\nsolidify-ok\nimport-ok\n1\nkeep new keep\n1\nALPHA beta",
);
}