Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(todo): invalidate task waits after human tool approval

xf gongb8500fad6f9b
diff --git a/cubeloop/hitl/channel.py b/cubeloop/hitl/channel.py
index 4eaa8e3..0eee99e 100644
--- a/cubeloop/hitl/channel.py
+++ b/cubeloop/hitl/channel.py
@@ -231,6 +231,7 @@ class _BaseChannel:
):
_, ans = self._resume_slot
self._resume_slot = None
+ ans = _normalize_answer(payload, ans)
from_resume = True
outcome = _outcome_from_answer(kind, ans)
if self._emit is not None:
diff --git a/cubeloop/hitl/middleware.py b/cubeloop/hitl/middleware.py
index 883b482..b596dee 100644
--- a/cubeloop/hitl/middleware.py
+++ b/cubeloop/hitl/middleware.py
@@ -95,7 +95,7 @@ class ApprovalPolicyMiddleware(Middleware):
)
if answer.decision == "approve":
- return None
+ return BeforeToolCallResult(hitl_trace={"decision": "human_approve"})
if answer.decision == "deny":
return BeforeToolCallResult(
block=True,
diff --git a/dev/plans/2026-09-21-todo-task-wait.md b/dev/plans/2026-09-21-todo-task-wait.md
index 455f210..77ac82b 100644
--- a/dev/plans/2026-09-21-todo-task-wait.md
+++ b/dev/plans/2026-09-21-todo-task-wait.md
@@ -4,7 +4,7 @@ Goal: let a host-validated background wait finish the current run without falsel
1. Extend `cubeloop/middleware/todo.py` with typed validation/binding records, the optional callback, and `WriteTodosInput.wait_for_tasks`. Keep the callback optional and the existing guard as the default.
2. Use the public before-tool hook to obtain the live `AgentContext`. The tool validates before atomically updating Todo and declaration extra state; no private Agent fields or new Session lifecycle APIs. Reject a waiting tool call that lacks a matching hook context.
-3. Bind to the run and current input fingerprint, including committed internal inputs. Persist only JSON-compatible data. Recheck binding and host evidence just before the pure-text unfinished guard. Cancelled is valid only with the previous successful declaration; record the reason without generating input or forcing a model turn.
+3. Bind to the run and current input fingerprint, including committed internal inputs and HITL answer evidence. Human tool approvals carry structured evidence; resume-slot JSON answers receive the same typed normalization as checkpoint-loaded answers. Cover approved, denied, and edited tool calls through Session suspend/respond. Persist only JSON-compatible data. Recheck binding and host evidence just before the pure-text unfinished guard. Cancelled is valid only with the previous successful declaration; record the reason without generating input or forcing a model turn.
4. Ensure parallel writes cannot retain one call's wait binding after checklist rollback. Normal updates clear waiting, and changed input or malformed saved bindings fail closed.
5. Add deterministic tool and real Session/checkpoint tests in `tests/middleware/test_todo_task_wait.py`. Keep `tests/test_synthetic_messages.py` and existing middleware behavior green. Update the current Todo guides and lazy exports in the same PR.
6. Persist existing Session extra in `Agent._process_event` at tool-turn end and suspension, before publishing the event. Keep normal run-end persistence. Mark a failed extra write as a checkpoint failure; cover the next-model boundary, HITL handoff, and failed writes without changing the execution lifecycle.
diff --git a/dev/specs/2026-09-21-todo-task-wait.md b/dev/specs/2026-09-21-todo-task-wait.md
index 7d316a2..8c6faeb 100644
--- a/dev/specs/2026-09-21-todo-task-wait.md
+++ b/dev/specs/2026-09-21-todo-task-wait.md
@@ -14,7 +14,7 @@ Extra must be saved at completed tool-turn boundaries before the next model call
Before the existing unfinished-Todo pure-text guard forces another model call, revalidate the declaration. `valid` allows natural completion while leaving unfinished items unchanged. `cancelled` does the same only for an existing, still-bound successful declaration, and stores the user's cancellation reason. It never permits creation of a new declaration. Invalid IDs, missing authority, validation failures, changed input, or an unconfigured validator retain the normal guard.
-HITL answers are new input too. Their structured tool-result evidence invalidates an earlier wait even when resuming the same run; the model must handle the answer before declaring a new wait.
+HITL answers are new input too. Their structured tool-result evidence invalidates an earlier wait even when resuming the same run; the model must handle the answer before declaring a new wait. Human approval records evidence just like denial and editing; automatic policy approval is not new human input. JSON answers restored through the resume slot use the same typed normalization as checkpoint-loaded answers.
This exemption cannot bypass malformed Todo input, parallel write restrictions, explicit stop, HITL, or another middleware's stop decision. It emits no notification, starts no run, and does not modify historical messages or a dynamic system prompt prefix.
diff --git a/tests/hitl/test_approval_policy_middleware.py b/tests/hitl/test_approval_policy_middleware.py
index f73bf05..8c2cbdb 100644
--- a/tests/hitl/test_approval_policy_middleware.py
+++ b/tests/hitl/test_approval_policy_middleware.py
@@ -49,7 +49,8 @@ async def test_ask_user_policy_invokes_channel_human_approve():
asyncio.create_task(host())
mw = ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser())
result = await mw.before_tool_call(_ctx())
- assert result is None
+ assert result is not None and not result.block
+ assert result.hitl_trace == {"decision": "human_approve"}
async def test_ask_user_policy_human_deny_blocks():
diff --git a/tests/hitl/test_confirm_tool_call_middleware.py b/tests/hitl/test_confirm_tool_call_middleware.py
index dd89271..95343a6 100644
--- a/tests/hitl/test_confirm_tool_call_middleware.py
+++ b/tests/hitl/test_confirm_tool_call_middleware.py
@@ -30,7 +30,9 @@ async def test_set_based_require_confirm_only_asks_for_listed():
asyncio.create_task(host())
mw = ConfirmToolCallMiddleware(ch, require_confirm={"bash"})
# bash: prompts
- assert (await mw.before_tool_call(_ctx("bash"))) is None
+ result = await mw.before_tool_call(_ctx("bash"))
+ assert result is not None and not result.block
+ assert result.hitl_trace == {"decision": "human_approve"}
# read_file: not in set — passes through silently
assert (await mw.before_tool_call(_ctx("read_file"))) is None
# bash prompted exactly once; read_file did not engage channel
@@ -51,7 +53,9 @@ async def test_predicate_require_confirm():
return ctx.tool_call.name.startswith("dangerous_")
mw = ConfirmToolCallMiddleware(ch, require_confirm=needs_confirm)
- assert (await mw.before_tool_call(_ctx("dangerous_op"))) is None
+ result = await mw.before_tool_call(_ctx("dangerous_op"))
+ assert result is not None and not result.block
+ assert result.hitl_trace == {"decision": "human_approve"}
async def test_default_none_asks_for_every_tool():
@@ -64,4 +68,6 @@ async def test_default_none_asks_for_every_tool():
asyncio.create_task(host())
mw = ConfirmToolCallMiddleware(ch) # no require_confirm
- assert (await mw.before_tool_call(_ctx("anything"))) is None
+ result = await mw.before_tool_call(_ctx("anything"))
+ assert result is not None and not result.block
+ assert result.hitl_trace == {"decision": "human_approve"}
diff --git a/tests/middleware/test_todo_task_wait.py b/tests/middleware/test_todo_task_wait.py
index 654c9d1..49b878b 100644
--- a/tests/middleware/test_todo_task_wait.py
+++ b/tests/middleware/test_todo_task_wait.py
@@ -5,12 +5,14 @@ import json
from typing import Any
import pytest
+from pydantic import BaseModel
from cubeloop import Agent
-from cubeloop.agent.types import AgentContext
+from cubeloop.agent.types import AgentContext, AgentTool, AgentToolResult
from cubeloop.checkpointer.memory import MemoryCheckpointer
from cubeloop.hitl.ask_user import ask_user_tool
from cubeloop.hitl.channel import CheckpointedChannel
+from cubeloop.hitl.middleware import ConfirmToolCallMiddleware
from cubeloop.middleware.base import Middleware, TurnAction
from cubeloop.middleware.todo import (
TaskWaitBinding,
@@ -466,9 +468,19 @@ async def test_wait_state_does_not_change_system_prompt_prefix() -> None:
assert await mw.transform_system_prompt("base", ctx=ctx) == before
[email protected]("same_turn", [False, True])
+ ("same_turn", "answer_kind"),
+ [
+ (False, "ask"),
+ (True, "ask"),
+ (False, "approve"),
+ (False, "deny"),
+ (False, "edit"),
+ ],
+)
async def test_valid_task_wait_does_not_complete_a_pending_hitl_request(
same_turn: bool,
+ answer_kind: str,
) -> None:
storage = MemoryCheckpointer()
channel = CheckpointedChannel(
@@ -478,6 +490,18 @@ async def test_valid_task_wait_does_not_complete_a_pending_hitl_request(
ask = faux_tool_call(
"ask_user", {"questions": [{"key": "continue", "prompt": "Continue?"}]}
)
+
+ class ActionParams(BaseModel):
+ command: str
+
+ executed: list[str] = []
+
+ async def action(tool_call_id, params, *, signal=None, on_update=None):
+ executed.append(params.command)
+ return AgentToolResult(content=[TextContent(text="Executed.")])
+
+ if answer_kind != "ask":
+ ask = faux_tool_call("action", {"command": "original"})
provider.set_responses(
[faux_assistant_message([*waiting_call().content, ask])]
if same_turn
@@ -488,8 +512,19 @@ async def test_valid_task_wait_does_not_complete_a_pending_hitl_request(
)
agent = Agent(
model=provider.model("faux"),
- tools=[ask_user_tool(channel)],
- middleware=[todo],
+ tools=[
+ ask_user_tool(channel),
+ AgentTool(
+ name="action",
+ description="Act",
+ parameters=ActionParams,
+ execute=action,
+ ),
+ ],
+ middleware=[
+ todo,
+ ConfirmToolCallMiddleware(channel, require_confirm=["action"]),
+ ],
checkpointer=storage,
channel=channel,
thread_id="task-wait",
@@ -535,13 +570,35 @@ async def test_valid_task_wait_does_not_complete_a_pending_hitl_request(
run_id="run-a",
attempt_id="attempt-b",
question_id=result.pending_request.question_id,
- answer={"continue": "yes"},
+ answer=(
+ {"continue": "yes"}
+ if answer_kind == "ask"
+ else {"decision": answer_kind, "edited_args": {"command": "edited"}}
+ ),
)
)
assert resumed.outcome == "completed"
checkpoint = await storage.load("task-wait")
+ if answer_kind != "ask":
+ assert checkpoint is not None
+ result_message = next(
+ m
+ for m in checkpoint.messages
+ if isinstance(m, ToolResultMessage) and m.tool_name == "action"
+ )
+ assert (
+ isinstance(result_message.details, dict)
+ and "hitl" in result_message.details
+ ), result_message
assert checkpoint is not None and checkpoint.extra["todo_task_wait"] is None
assert checkpoint.extra["todos"][0]["status"] == "completed"
+ assert executed == (
+ ["original"]
+ if answer_kind == "approve"
+ else ["edited"]
+ if answer_kind == "edit"
+ else []
+ )
async def test_wait_binding_is_checkpointed_before_the_next_model_call() -> None:
diff --git a/website/docs/guides/middleware/todo.md b/website/docs/guides/middleware/todo.md
index 4ecf689..c4cb31b 100644
--- a/website/docs/guides/middleware/todo.md
+++ b/website/docs/guides/middleware/todo.md
@@ -117,8 +117,9 @@ input boundary. Before forcing a finalization correction, CubeLoop asks the
host again. A valid wait lets the run end naturally without completing unfinished
Todos or making another model call. An ordinary Todo update without task IDs
clears the declaration. New user or internal input, including a new run's initial
-message or a HITL answer, invalidates it. A changed or unprovable boundary after compaction also
-requires a new declaration.
+message or a HITL answer (including approval, denial, or editing of a tool call),
+invalidates it. Automatic policy approval is not new human input. A changed or
+unprovable boundary after compaction also requires a new declaration.
If the user cancels previously validated work, the callback may return
`status="cancelled"` with a nonempty `reason`, after proving cancellation happened
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.md
index 913a8c5..e47f7d9 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.md
@@ -97,7 +97,8 @@ scope、发起者权限、取消状态,以及任务是否仍有可观察、待
成功的声明绑定任务 ID、Todo 快照、run 和当前输入边界。纯文本收尾触发未完成守卫前,
CubeLoop 再次调用宿主校验;仍有效则正常结束当前 run,不勾选未完成 Todo,也不强制
追加模型调用。不带任务 ID 的普通 Todo 更新会清除声明。新的用户或内部输入、新 run
-的初始消息或 HITL 答复都会使旧声明失效;压缩上下文后无法确认原输入边界时也需重新声明。
+的初始消息或 HITL 答复(包括人工批准、拒绝或编辑工具调用)都会使旧声明失效。
+策略自动批准不属于新的人工输入;压缩上下文后无法确认原输入边界时也需重新声明。
用户后来取消已验证的工作时,宿主证明取消发生在原校验之后,可返回
`status="cancelled"` 和非空 `reason`,允许自然收尾并保留未完成列表和取消原因。