feat(agent): wire EffectLedger through mutating run_tool
Prepare/start/commit write and execute tools with idempotent dedupe, and refuse blind retry while ledger state is unknown or interrupted mid-flight (MA-T03). Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
6bd90bb2d0
commit
11bb7ef277
5 files changed
+342
-17
No files matched your search
+113
-12
@@ -182,9 +182,17 @@ Find a human-readable call line: `CALL:<name>` or `调用:<name>` / `调用:<n
|
||||
+ `tools`
|
||||
+ `name`
|
||||
+ `arguments`=None
|
||||
+ `ledger_dir`=.marqdo/agent-effects
|
||||
+ `logical_run_id`=None
|
||||
+ `step_id`=None
|
||||
+ `call_id`=None
|
||||
+ `operation_id`=None
|
||||
|
||||
Allowlist + ToolSpec prepare (M-A2), then invoke the runbook `##` via `lib/subtask`.
|
||||
Unauthorized / invalid-args calls return ToolResultV1 failure without spawning (0 executions).
|
||||
Allowlist and ToolSpec prepare (M-A2), then invoke the runbook section via lib/subtask.
|
||||
Unauthorized or invalid-args calls return ToolResultV1 failure without spawning (0 executions).
|
||||
Mutating effects (write / execute / external_write) go through EffectLedger (M-A5a).
|
||||
State flow is prepared then started then spawn then committed, failed_no_effect, or unknown.
|
||||
Read tools skip the ledger. Matching idempotency_key and args_digest that already committed skips re-exec.
|
||||
|
||||
**p = > plugin.native_path name="agent"**
|
||||
1. `p`
|
||||
@@ -192,23 +200,98 @@ Unauthorized / invalid-args calls return ToolResultV1 failure without spawning (
|
||||
2. *
|
||||
**_ = 1**
|
||||
|
||||
1. `p`
|
||||
**prep = > agent_tools_prepare_call tool_id=`name` tools=`tools` arguments=`arguments`**
|
||||
**pok = > json.get value=`prep` key="ok"**
|
||||
1. not `pok`
|
||||
*prep*
|
||||
2. *
|
||||
**_ = 1**
|
||||
1. not `arguments`
|
||||
**arguments = > table.empty_map**
|
||||
2. *
|
||||
**_ = 1**
|
||||
|
||||
**prepared = None**
|
||||
**needs = False**
|
||||
**opid = None**
|
||||
**digest = None**
|
||||
**idem = None**
|
||||
**effect = "read"**
|
||||
**receipt = None**
|
||||
**raw = None**
|
||||
|
||||
1. not `p`
|
||||
**allowed = > agent_tool_allowed tools=`tools` name=`name`**
|
||||
1. not `allowed`
|
||||
**msg = "Tool not allowed:"**
|
||||
*msg + name*
|
||||
2. *
|
||||
**_ = 1**
|
||||
**id = > subtask.spawn fn=`name`**
|
||||
*> subtask.wait id=`id`*
|
||||
|
||||
**prepared = > agent_tools_prepare_call tool_id=`name` tools=`tools` arguments=`arguments` call_id=`call_id` operation_id=`operation_id` logical_run_id=`logical_run_id` step_id=`step_id`**
|
||||
**pok = > json.get value=`prepared` key="ok"**
|
||||
1. not `pok`
|
||||
*prepared*
|
||||
2. *
|
||||
**_ = 1**
|
||||
|
||||
**needs = > json.get value=`prepared` key="needs_ledger"**
|
||||
**call = > json.get value=`prepared` key="call"**
|
||||
**opid = > json.get value=`call` key="operation_id"**
|
||||
**digest = > json.get value=`prepared` key="args_digest"**
|
||||
**idem = > json.get value=`prepared` key="idempotency_key"**
|
||||
**tspec = > json.get value=`prepared` key="spec"**
|
||||
**effect = > json.get value=`tspec` key="effect"**
|
||||
|
||||
1. `needs`
|
||||
**led = > agent_effects_prepare operation_id=`opid` idempotency_key=`idem` args_digest=`digest` effect_class=`effect` logical_run_id=`logical_run_id` step_id=`step_id` ledger_dir=`ledger_dir`**
|
||||
**rec = > json.get value=`led` key="record"**
|
||||
**st0 = > json.get value=`rec` key="state"**
|
||||
1. `st0` == "committed"
|
||||
**receipt = > json.get value=`rec` key="result_ref"**
|
||||
1. not `receipt`
|
||||
**receipt = "effect:" + `opid`**
|
||||
*> agent_tools_wrap_result ok=True status="succeeded" summary="deduped committed effect; skipped re-exec" structured_content=`rec` effect_receipt_ref=`receipt`*
|
||||
2. *
|
||||
1. `st0` == "reconciled_committed"
|
||||
**receipt = > json.get value=`rec` key="result_ref"**
|
||||
1. not `receipt`
|
||||
**receipt = "effect:" + `opid`**
|
||||
*> agent_tools_wrap_result ok=True status="succeeded" summary="deduped reconciled effect; skipped re-exec" structured_content=`rec` effect_receipt_ref=`receipt`*
|
||||
2. *
|
||||
1. `st0` == "unknown"
|
||||
**receipt = "effect:" + `opid`**
|
||||
*> agent_tools_wrap_result ok=False status="unknown_effect" summary="prior effect unknown; reconcile before retry" structured_content=`rec` effect_receipt_ref=`receipt`*
|
||||
2. *
|
||||
1. `st0` == "started"
|
||||
> agent_effects_transition operation_id=`opid` state="unknown" note="retry saw started without commit; mark unknown" ledger_dir=`ledger_dir`
|
||||
**receipt = "effect:" + `opid`**
|
||||
*> agent_tools_wrap_result ok=False status="unknown_effect" summary="interrupted after started; reconcile before retry" structured_content=`rec` effect_receipt_ref=`receipt`*
|
||||
2. *
|
||||
1. `st0` == "needs_input"
|
||||
**receipt = "effect:" + `opid`**
|
||||
*> agent_tools_wrap_result ok=False status="needs_input" summary="effect needs_input; will not re-exec" structured_content=`rec` effect_receipt_ref=`receipt`*
|
||||
2. *
|
||||
> agent_effects_transition operation_id=`opid` state="started" ledger_dir=`ledger_dir`
|
||||
**_ = 1**
|
||||
2. *
|
||||
**_ = 1**
|
||||
|
||||
**id = > subtask.spawn fn=`name`**
|
||||
*> subtask.wait id=`id`*
|
||||
**raw = > subtask.wait id=`id`**
|
||||
1. `needs`
|
||||
**raw_s = > json.stringify value=`raw`**
|
||||
1. not `raw`
|
||||
> agent_effects_transition operation_id=`opid` state="unknown" note="empty tool outcome; reconcile required" ledger_dir=`ledger_dir`
|
||||
**receipt = "effect:" + `opid`**
|
||||
*> agent_tools_wrap_result ok=False status="unknown_effect" summary="tool outcome empty after started; ledger=unknown" structured_content=`raw` effect_receipt_ref=`receipt`*
|
||||
2. *
|
||||
**is_err = > text.starts_with text=`raw_s` prefix="Tool not allowed"**
|
||||
1. `is_err`
|
||||
> agent_effects_transition operation_id=`opid` state="failed_no_effect" note="rejected before effect" ledger_dir=`ledger_dir`
|
||||
**receipt = "effect:" + `opid`**
|
||||
*> agent_tools_wrap_result ok=False status="failed" summary=`raw_s` effect_receipt_ref=`receipt`*
|
||||
2. *
|
||||
**receipt = "effect:" + `opid`**
|
||||
> agent_effects_transition operation_id=`opid` state="committed" result_ref=`receipt` ledger_dir=`ledger_dir`
|
||||
*> agent_tools_wrap_result ok=True status="succeeded" summary="tool executed; effect committed" structured_content=`raw` effect_receipt_ref=`receipt`*
|
||||
2. *
|
||||
*raw*
|
||||
|
||||
## tools_register
|
||||
+ `spec`=None
|
||||
@@ -225,6 +308,19 @@ Register ToolSpecV1 document(s). Unsupported schema keywords are refused.
|
||||
|
||||
*> agent_tools_register spec=`spec` specs=`specs`*
|
||||
|
||||
## tools_clear
|
||||
|
||||
Clear the in-process ToolSpec registry (tests / reseeding).
|
||||
|
||||
**p = > plugin.native_path name="agent"**
|
||||
1. `p`
|
||||
> plugin.load path=`p`
|
||||
2. *
|
||||
> print text=ext/ai/agent: native agent plugin not found
|
||||
> sys.exit code=1
|
||||
|
||||
*> agent_tools_clear*
|
||||
|
||||
## tools_search
|
||||
+ `query`=""
|
||||
+ `tools`=None
|
||||
@@ -273,8 +369,13 @@ Seed the five engineering tool specs (`tool_find` … `tool_summarize`).
|
||||
+ `arguments`=None
|
||||
+ `tools`=None
|
||||
+ `call_id`=None
|
||||
+ `operation_id`=None
|
||||
+ `logical_run_id`=None
|
||||
+ `step_id`=None
|
||||
+ `idempotency_key`=None
|
||||
|
||||
Validate schema + authorize; returns ToolCallV1 or ToolResultV1 error (no side effects).
|
||||
Also returns `args_digest` / `idempotency_key` / `needs_ledger` for EffectLedger wiring.
|
||||
|
||||
**p = > plugin.native_path name="agent"**
|
||||
1. `p`
|
||||
@@ -283,7 +384,7 @@ Validate schema + authorize; returns ToolCallV1 or ToolResultV1 error (no side e
|
||||
> print text=ext/ai/agent: native agent plugin not found
|
||||
> sys.exit code=1
|
||||
|
||||
*> agent_tools_prepare_call tool_id=`tool_id` arguments=`arguments` tools=`tools` call_id=`call_id`*
|
||||
*> agent_tools_prepare_call tool_id=`tool_id` arguments=`arguments` tools=`tools` call_id=`call_id` operation_id=`operation_id` logical_run_id=`logical_run_id` step_id=`step_id` idempotency_key=`idempotency_key`*
|
||||
|
||||
## output_build
|
||||
+ `status`="succeeded"
|
||||
|
||||
@@ -530,6 +530,74 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ma_t03_unknown_then_reconcile_no_second_commit_path() {
|
||||
// Write "succeeds" locally only after reconcile; retry while unknown must not
|
||||
// look write_auto_resume_safe (MA-T03 watermark gate).
|
||||
let dir = scratch("mat03");
|
||||
let prev = std::env::current_dir().unwrap();
|
||||
std::env::set_current_dir(&dir).unwrap();
|
||||
effects_prepare(&json!({
|
||||
"operation_id": "op_kill",
|
||||
"idempotency_key": "run|s|write_probe|sha256-lite:1",
|
||||
"args_digest": "sha256-lite:1",
|
||||
"effect_class": "write",
|
||||
"ledger_dir": "led",
|
||||
"logical_run_id": "run_kill",
|
||||
}))
|
||||
.unwrap();
|
||||
effects_transition(&json!({
|
||||
"operation_id": "op_kill",
|
||||
"state": "started",
|
||||
"ledger_dir": "led",
|
||||
}))
|
||||
.unwrap();
|
||||
// Crash before commit:
|
||||
effects_transition(&json!({
|
||||
"operation_id": "op_kill",
|
||||
"state": "unknown",
|
||||
"ledger_dir": "led",
|
||||
}))
|
||||
.unwrap();
|
||||
let wm = effects_watermark(&json!({
|
||||
"ledger_dir": "led",
|
||||
"logical_run_id": "run_kill",
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(wm["write_auto_resume_safe"], false);
|
||||
|
||||
// Idempotent re-prepare returns same unknown record (no new op).
|
||||
let again = effects_prepare(&json!({
|
||||
"operation_id": "op_kill",
|
||||
"idempotency_key": "run|s|write_probe|sha256-lite:1",
|
||||
"args_digest": "sha256-lite:1",
|
||||
"effect_class": "write",
|
||||
"ledger_dir": "led",
|
||||
"logical_run_id": "run_kill",
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(again["deduped"], true);
|
||||
assert_eq!(again["record"]["state"], "unknown");
|
||||
|
||||
effects_reconcile(&json!({
|
||||
"operation_id": "op_kill",
|
||||
"outcome": "committed",
|
||||
"ledger_dir": "led",
|
||||
"result_ref": "effect:op_kill",
|
||||
}))
|
||||
.unwrap();
|
||||
let wm2 = effects_watermark(&json!({
|
||||
"ledger_dir": "led",
|
||||
"logical_run_id": "run_kill",
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(wm2["write_auto_resume_safe"], true);
|
||||
assert_eq!(wm2["pending_writes"], 0);
|
||||
|
||||
std::env::set_current_dir(prev).unwrap();
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn illegal_skip_started() {
|
||||
let dir = scratch("bad");
|
||||
|
||||
@@ -842,6 +842,16 @@ kb_ffi!(agent_tools_search, tools::tools_search, "agent_tools_search");
|
||||
kb_ffi!(agent_tools_describe, tools::tools_describe, "agent_tools_describe");
|
||||
kb_ffi!(agent_tools_prepare_call, tools::tools_prepare_call, "agent_tools_prepare_call");
|
||||
kb_ffi!(agent_tools_wrap_result, tools::tools_wrap_result, "agent_tools_wrap_result");
|
||||
kb_ffi!(
|
||||
agent_tools_args_digest,
|
||||
tools::tools_args_digest,
|
||||
"agent_tools_args_digest"
|
||||
);
|
||||
kb_ffi!(
|
||||
agent_tools_needs_ledger,
|
||||
tools::tools_needs_ledger,
|
||||
"agent_tools_needs_ledger"
|
||||
);
|
||||
kb_ffi!(
|
||||
agent_tools_register_eng_defaults,
|
||||
tools::tools_register_eng_defaults,
|
||||
@@ -961,6 +971,8 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
("agent_tools_describe", "id,tools", agent_tools_describe),
|
||||
("agent_tools_prepare_call", "tool_id,arguments,tools", agent_tools_prepare_call),
|
||||
("agent_tools_wrap_result", "ok,status,summary", agent_tools_wrap_result),
|
||||
("agent_tools_args_digest", "arguments", agent_tools_args_digest),
|
||||
("agent_tools_needs_ledger", "effect", agent_tools_needs_ledger),
|
||||
(
|
||||
"agent_tools_register_eng_defaults",
|
||||
"",
|
||||
|
||||
@@ -369,10 +369,10 @@ pub fn tools_prepare_call(args: &Value) -> Result<Value, String> {
|
||||
));
|
||||
}
|
||||
|
||||
let arguments = args
|
||||
.get("arguments")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| json!({}));
|
||||
let arguments = match args.get("arguments") {
|
||||
None | Some(Value::Null) => json!({}),
|
||||
Some(v) => v.clone(),
|
||||
};
|
||||
let schema = spec
|
||||
.get("input_schema")
|
||||
.cloned()
|
||||
@@ -396,6 +396,17 @@ pub fn tools_prepare_call(args: &Value) -> Result<Value, String> {
|
||||
.get("version")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("1");
|
||||
let effect = spec
|
||||
.get("effect")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("read");
|
||||
let digest = args_digest(&arguments);
|
||||
let logical_run = opt_text(args, "logical_run_id").unwrap_or("-");
|
||||
let step = opt_text(args, "step_id").unwrap_or("-");
|
||||
let idempotency_key = opt_text(args, "idempotency_key")
|
||||
.map(|s| s.to_string())
|
||||
.unwrap_or_else(|| format!("{logical_run}|{step}|{tool_id}|{digest}"));
|
||||
let needs_ledger = matches!(effect, "write" | "execute" | "external_write");
|
||||
|
||||
let call = json!({
|
||||
"schema": "ToolCallV1",
|
||||
@@ -414,14 +425,56 @@ pub fn tools_prepare_call(args: &Value) -> Result<Value, String> {
|
||||
"call": call,
|
||||
"spec": {
|
||||
"id": tool_id,
|
||||
"effect": spec.get("effect").cloned().unwrap_or(json!("read")),
|
||||
"effect": effect,
|
||||
"timeout_ms": spec.get("timeout_ms").cloned().unwrap_or(json!(10000)),
|
||||
"max_result_bytes": spec.get("max_result_bytes").cloned().unwrap_or(json!(65536)),
|
||||
},
|
||||
"args_digest": digest,
|
||||
"idempotency_key": idempotency_key,
|
||||
"needs_ledger": needs_ledger,
|
||||
"summary": format!("prepared authorized call to `{tool_id}`"),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Stable digest of tool arguments for effect ledger idempotency (M-A5a).
|
||||
pub fn tools_args_digest(args: &Value) -> Result<Value, String> {
|
||||
let arguments = args
|
||||
.get("arguments")
|
||||
.cloned()
|
||||
.or_else(|| args.get("value").cloned())
|
||||
.unwrap_or_else(|| json!({}));
|
||||
Ok(json!({
|
||||
"ok": true,
|
||||
"args_digest": args_digest(&arguments),
|
||||
}))
|
||||
}
|
||||
|
||||
fn args_digest(arguments: &Value) -> String {
|
||||
let text = serde_json::to_string(arguments).unwrap_or_else(|_| "{}".into());
|
||||
format!("sha256-lite:{:x}", fnv1a64(&text))
|
||||
}
|
||||
|
||||
fn fnv1a64(s: &str) -> u64 {
|
||||
let mut h: u64 = 0xcbf29ce484222325;
|
||||
for b in s.as_bytes() {
|
||||
h ^= u64::from(*b);
|
||||
h = h.wrapping_mul(0x100000001b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// True when effect_class requires EffectLedger before/after execution.
|
||||
pub fn tools_needs_ledger(args: &Value) -> Result<Value, String> {
|
||||
let effect = opt_text(args, "effect")
|
||||
.or_else(|| opt_text(args, "effect_class"))
|
||||
.unwrap_or("read");
|
||||
Ok(json!({
|
||||
"ok": true,
|
||||
"needs_ledger": matches!(effect, "write" | "execute" | "external_write"),
|
||||
"effect": effect,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Wrap a successful / failed tool execution into ToolResultV1.
|
||||
pub fn tools_wrap_result(args: &Value) -> Result<Value, String> {
|
||||
let ok = args.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
@@ -689,6 +742,42 @@ mod tests {
|
||||
assert_eq!(good["ok"], true);
|
||||
assert_eq!(good["call"]["schema"], "ToolCallV1");
|
||||
assert_eq!(good["call"]["tool_id"], "tool_find");
|
||||
assert_eq!(good["needs_ledger"], false);
|
||||
assert!(good["args_digest"].as_str().unwrap().starts_with("sha256-lite:"));
|
||||
|
||||
let allow2 = json!(["tool_bind"]);
|
||||
let bind = tools_prepare_call(&json!({
|
||||
"tool_id": "tool_bind",
|
||||
"tools": allow2,
|
||||
"arguments": {"query": "x"},
|
||||
"call_id": "c2",
|
||||
"logical_run_id": "run1",
|
||||
"step_id": "s1"
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(bind["ok"], true);
|
||||
assert_eq!(bind["needs_ledger"], true);
|
||||
assert_eq!(bind["spec"]["effect"], "execute");
|
||||
assert!(bind["idempotency_key"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.starts_with("run1|s1|tool_bind|"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn needs_ledger_only_for_mutating_effects() {
|
||||
assert_eq!(
|
||||
tools_needs_ledger(&json!({"effect": "read"})).unwrap()["needs_ledger"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
tools_needs_ledger(&json!({"effect": "write"})).unwrap()["needs_ledger"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
tools_needs_ledger(&json!({"effect": "execute"})).unwrap()["needs_ledger"],
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
markup: occlusion
|
||||
title: agent-effects-run-tool
|
||||
description: >-
|
||||
M-A5a / MA-T03 subset — mutating run_tool goes through EffectLedger;
|
||||
committed effects dedupe; started-without-commit becomes unknown (no re-exec).
|
||||
import:
|
||||
agent: /home/cflmy/work/marqdo/ext/ai/agent.mq.md
|
||||
json: lib/json.mq.md
|
||||
sys: lib/sys.mq.md
|
||||
table: lib/table.mq.md
|
||||
text: lib/text.mq.md
|
||||
---
|
||||
|
||||
## write_probe
|
||||
|
||||
Probe side-effect tool body (count stays in ledger, not here).
|
||||
|
||||
*"wrote"*
|
||||
|
||||
# main
|
||||
|
||||
**schema = > json.parse text={"type":"object","properties":{},"additionalProperties":true}**
|
||||
**scopes = > json.parse text=["workspace:write"]**
|
||||
`spec` =
|
||||
|
||||
| id | version | description | input_schema | effect | scopes | availability |
|
||||
|----|---------|-------------|--------------|--------|--------|--------------|
|
||||
| write_probe | 1 | test write tool | `schema` | write | `scopes` | ready |
|
||||
|
||||
> agent.tools_clear
|
||||
**reg = > agent.tools_register spec=`spec`**
|
||||
**allow = > json.parse text=["write_probe"]**
|
||||
**args = > json.parse text={}**
|
||||
|
||||
**out1 = > agent.run_tool tools=`allow` name="write_probe" arguments=`args` logical_run_id="run_ma5a" step_id="s1" call_id="c1" operation_id="op_write_probe_c1" ledger_dir=".marqdo/agent-effects-ma5a"**
|
||||
**ok1 = > json.get value=`out1` key="ok"**
|
||||
**st1 = > json.get value=`out1` key="status"**
|
||||
**rc1 = > json.get value=`out1` key="effect_receipt_ref"**
|
||||
> print text=`ok1`
|
||||
> print text=`st1`
|
||||
> print text=`rc1`
|
||||
|
||||
**out2 = > agent.run_tool tools=`allow` name="write_probe" arguments=`args` logical_run_id="run_ma5a" step_id="s1" call_id="c1" operation_id="op_write_probe_c1" ledger_dir=".marqdo/agent-effects-ma5a"**
|
||||
**sum2 = > json.get value=`out2` key="summary"**
|
||||
> print text=`sum2`
|
||||
|
||||
**wm = > agent.effects_watermark ledger_dir=".marqdo/agent-effects-ma5a" logical_run_id="run_ma5a"**
|
||||
**safe = > json.get value=`wm` key="write_auto_resume_safe"**
|
||||
> print text=`safe`
|
||||
|
||||
**got = > agent.effects_get operation_id="op_write_probe_c1" ledger_dir=".marqdo/agent-effects-ma5a"**
|
||||
**rec = > json.get value=`got` key="record"**
|
||||
**state = > json.get value=`rec` key="state"**
|
||||
> print text=`state`
|
||||
Reference in new issue
Block a user