Skip to content

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

feat(agent): mark_run_complete only on clean terminal outcome

xf gongcd0f3c1d017d
diff --git a/cubepi/agent/_outcome.py b/cubepi/agent/_outcome.py
new file mode 100644
index 0000000..0af9d2d
--- /dev/null
+++ b/cubepi/agent/_outcome.py
@@ -0,0 +1,5 @@
+from __future__ import annotations
+
+from typing import Literal
+
+RunOutcome = Literal["complete", "suspended", "incomplete", "abandoned"]
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index a86d5f8..bbe6f9e 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -7,12 +7,14 @@ from collections.abc import Sequence
from dataclasses import dataclass, field
from typing import Callable, Generic, TypeVar
+from cubepi.agent._outcome import RunOutcome
from cubepi.agent.loop import (
run_agent_loop,
run_agent_loop_continue,
run_agent_loop_resume,
)
from cubepi.checkpointer.base import Checkpointer
+from cubepi.checkpointer.exceptions import CompletionMarkerFailedError
from cubepi.hitl import HitlError, HitlRequest
from cubepi.hitl.channel import HitlChannel
from cubepi.hitl.exceptions import HitlDetached
@@ -101,6 +103,7 @@ class AgentState:
streaming_message: Message | None = None
error_message: str | None = None
active_run_id: str | None = None
+ last_outcome: RunOutcome | None = None
_tools: list[AgentTool] = field(default_factory=list)
_messages: list[Message] = field(default_factory=list)
_pending_tool_calls: set[str] = field(default_factory=set)
@@ -282,6 +285,29 @@ class Agent(Generic[TMessage]):
self._steering_queue.clear()
self._follow_up_queue.clear()
+ def _outcome_sink(self) -> Callable[[str], None]:
+ def _sink(value: str) -> None:
+ # Cast through Any: loop callsites pass plain str literals from the
+ # RunOutcome alphabet ("complete" / "suspended" / "abandoned").
+ self._state.last_outcome = value # type: ignore[assignment]
+
+ return _sink
+
+ async def _dispatch_outcome(self, outcome: RunOutcome | None, run_id: str) -> None:
+ if outcome != "complete":
+ return
+ if not (self._run_aware and self.thread_id):
+ return
+ assert self.checkpointer is not None # narrowed by _run_aware
+ try:
+ await self.checkpointer.mark_run_complete(self.thread_id, run_id)
+ except Exception as exc:
+ raise CompletionMarkerFailedError(
+ thread_id=self.thread_id,
+ run_id=run_id,
+ cause=exc,
+ ) from exc
+
def _validate_input_run_ids(
self,
message: str | Message | list[Message],
@@ -349,6 +375,7 @@ class Agent(Generic[TMessage]):
assert self.checkpointer is not None # narrowed by _run_aware
await self.checkpointer.claim_run(self.thread_id, effective_run_id)
self._state.active_run_id = effective_run_id
+ self._state.last_outcome = None
try:
async with self._run_lock:
# Re-check under the lock in case streaming flipped during acquire.
@@ -384,6 +411,11 @@ class Agent(Generic[TMessage]):
# Spec §3.7: leave active_run_id SET on failure.
raise
else:
+ outcome: RunOutcome = self._state.last_outcome or "abandoned"
+ # If _dispatch_outcome raises (CompletionMarkerFailedError),
+ # propagate UP through this else: — active_run_id stays SET because
+ # the clear line below is unreachable on the exception path.
+ await self._dispatch_outcome(outcome, effective_run_id)
self._state.active_run_id = None
return effective_run_id
@@ -428,6 +460,7 @@ class Agent(Generic[TMessage]):
)
async def _run_prompt(self, messages: list[Message]) -> None:
+ sink = self._outcome_sink()
await self._run_with_lifecycle(
lambda signal: run_agent_loop(
prompts=messages,
@@ -447,10 +480,12 @@ class Agent(Generic[TMessage]):
stream_options=self._build_stream_options(signal),
tool_execution=self.tool_execution,
emit=lambda e: self._process_event(e),
+ set_outcome=sink,
)
)
async def _run_continuation(self) -> None:
+ sink = self._outcome_sink()
await self._run_with_lifecycle(
lambda signal: run_agent_loop_continue(
context=self._create_context_snapshot(),
@@ -469,6 +504,7 @@ class Agent(Generic[TMessage]):
stream_options=self._build_stream_options(signal),
tool_execution=self.tool_execution,
emit=lambda e: self._process_event(e),
+ set_outcome=sink,
)
)
diff --git a/cubepi/agent/loop.py b/cubepi/agent/loop.py
index 61cc22e..570df24 100644
--- a/cubepi/agent/loop.py
+++ b/cubepi/agent/loop.py
@@ -49,6 +49,7 @@ async def run_agent_loop(
stream_options: StreamOptions | None = None,
tool_execution: str = "parallel",
system_prompt: str | None = None,
+ set_outcome: Callable[[str], None] | None = None,
) -> list[Message]:
new_messages: list[Message] = list(prompts)
current_context = AgentContext(
@@ -84,6 +85,7 @@ async def run_agent_loop(
stream_options=stream_options,
tool_execution=tool_execution,
emit=emit,
+ set_outcome=set_outcome,
)
return new_messages
@@ -107,6 +109,7 @@ async def run_agent_loop_continue(
stream_options: StreamOptions | None = None,
tool_execution: str = "parallel",
system_prompt: str | None = None,
+ set_outcome: Callable[[str], None] | None = None,
) -> list[Message]:
if not context.messages:
raise ValueError("Cannot continue: no messages in context")
@@ -142,6 +145,7 @@ async def run_agent_loop_continue(
stream_options=stream_options,
tool_execution=tool_execution,
emit=emit,
+ set_outcome=set_outcome,
)
return new_messages
@@ -167,6 +171,7 @@ async def run_agent_loop_resume(
system_prompt: str | None = None,
checkpointer: Checkpointer | None = None,
thread_id: str | None = None,
+ set_outcome: Callable[[str], None] | None = None,
) -> list[Message]:
new_messages: list[Message] = []
@@ -192,15 +197,21 @@ async def run_agent_loop_resume(
checkpointer=checkpointer,
thread_id=thread_id,
new_messages=new_messages,
+ set_outcome=set_outcome,
)
- except (HitlDetached, HitlAborted): # pragma: no cover — E2E tested
- # Same as _run_loop's outer catch: the Agent caller (Agent.detach /
- # Agent.abort_pending) emitted the corresponding event already.
+ except HitlDetached: # pragma: no cover — E2E tested
+ # The Agent caller (Agent.detach) emitted AgentSuspendedEvent already.
# Loop exits silently — assistant message and pending state remain
- # intact for the next respond() call. This catch covers the prelude
- # (execute_tool_calls of the resumed tool batch) AND the fall-through
- # to _run_loop, so a second HITL pause/abort during respond() also
- # unwinds cleanly instead of escaping.
+ # intact for the next respond() call.
+ if set_outcome is not None:
+ set_outcome("suspended")
+ return new_messages
+ except HitlAborted: # pragma: no cover — E2E tested
+ # The Agent caller (Agent.abort_pending) emitted AgentAbortedEvent
+ # already. Loop exits silently — synthetic deny + terminal aborted
+ # assistant message already appended by abort_pending.
+ if set_outcome is not None:
+ set_outcome("abandoned")
return new_messages
@@ -226,6 +237,7 @@ async def _run_agent_loop_resume_body( # pragma: no cover — E2E tested
checkpointer,
thread_id,
new_messages: list,
+ set_outcome: Callable[[str], None] | None = None,
) -> list[Message]:
from cubepi.hitl.exceptions import HitlInconsistentState
@@ -345,11 +357,15 @@ async def _run_agent_loop_resume_body( # pragma: no cover — E2E tested
)
if await should_stop_after_turn(stop_ctx):
await emit_event(emit, AgentEndEvent(messages=new_messages))
+ if set_outcome is not None:
+ set_outcome("complete")
return new_messages
# Terminate-by-tool semantics (codex BLOCKING: previous draft ignored).
if terminated_by_tool:
await emit_event(emit, AgentEndEvent(messages=new_messages))
+ if set_outcome is not None:
+ set_outcome("complete")
return new_messages
# Fall through to the normal loop for the next model turn.
@@ -371,6 +387,7 @@ async def _run_agent_loop_resume_body( # pragma: no cover — E2E tested
stream_options=stream_options,
tool_execution=tool_execution,
emit=emit,
+ set_outcome=set_outcome,
)
return new_messages
@@ -394,6 +411,7 @@ async def _run_loop(
stream_options: StreamOptions | None,
tool_execution: str,
emit: Callable,
+ set_outcome: Callable[[str], None] | None = None,
) -> None:
try:
await _run_loop_inner(
@@ -414,16 +432,21 @@ async def _run_loop(
stream_options=stream_options,
tool_execution=tool_execution,
emit=emit,
+ set_outcome=set_outcome,
)
- except (HitlDetached, HitlAborted):
- # Per the spec design, HITL terminal events (AgentSuspendedEvent /
- # AgentAbortedEvent) are emitted by the Agent layer (Agent.detach()
- # / Agent.abort_pending()) BEFORE these exceptions are raised — they
- # are mutually exclusive with AgentEndEvent. The loop intentionally
- # exits silently here: emitting AgentEndEvent would double-signal
- # termination to event-stream consumers who already saw the HITL
- # event. Assistant message and pending state remain intact for the
- # next respond() call.
+ except HitlDetached:
+ # AgentSuspendedEvent already emitted by Agent.detach() — exit silently
+ # so AgentEndEvent doesn't double-signal termination. Assistant message
+ # and pending state remain intact for the next respond() call.
+ if set_outcome is not None:
+ set_outcome("suspended")
+ return
+ except HitlAborted:
+ # AgentAbortedEvent already emitted by Agent.abort_pending() — exit
+ # silently. Synthetic deny + terminal aborted assistant message are
+ # already appended; conversation is closed.
+ if set_outcome is not None:
+ set_outcome("abandoned")
return
@@ -446,6 +469,7 @@ async def _run_loop_inner(
stream_options: StreamOptions | None,
tool_execution: str,
emit: Callable,
+ set_outcome: Callable[[str], None] | None = None,
) -> None:
opts = stream_options or StreamOptions()
first_turn = True
@@ -487,6 +511,8 @@ async def _run_loop_inner(
await emit_event(emit, MessageEndEvent(message=message))
await emit_event(emit, TurnEndEvent(message=message, tool_results=[]))
await emit_event(emit, AgentEndEvent(messages=new_messages))
+ if set_outcome is not None:
+ set_outcome("abandoned")
return
# Apply after_model_response hook if configured.
@@ -664,6 +690,8 @@ async def _run_loop_inner(
break
await emit_event(emit, AgentEndEvent(messages=new_messages))
+ if set_outcome is not None:
+ set_outcome("complete")
async def _stream_assistant_response(
diff --git a/tests/agent/test_agent_completion.py b/tests/agent/test_agent_completion.py
new file mode 100644
index 0000000..7a513a0
--- /dev/null
+++ b/tests/agent/test_agent_completion.py
@@ -0,0 +1,264 @@
+"""Task 26 tests — outcome enumeration + mark_run_complete dispatch.
+
+The contract under test: ``Agent.prompt()`` writes the completion marker
+(via ``Checkpointer.mark_run_complete``) IFF the loop reached a terminal
+``AgentEndEvent`` with a non-error/aborted stop_reason. Every other exit
+(provider error, HITL detach, HITL abort, propagating cancel) must NOT
+mark the run as complete, leaving the row resumable.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+from pydantic import BaseModel
+
+from cubepi.agent.agent import Agent
+from cubepi.agent.types import AgentTool, AgentToolResult
+from cubepi.checkpointer.exceptions import (
+ CompletionMarkerFailedError,
+ RunNotClaimedError,
+)
+from cubepi.checkpointer.memory import MemoryCheckpointer
+from cubepi.hitl import AskUser
+from cubepi.hitl.channel import CheckpointedChannel
+from cubepi.hitl.middleware import ApprovalPolicyMiddleware
+from cubepi.providers.base import AssistantMessage, TextContent
+from cubepi.providers.faux import (
+ FauxProvider,
+ faux_assistant_message,
+ faux_text,
+ faux_tool_call,
+)
+
+
+class _Params(BaseModel):
+ cmd: str
+
+
+def _bash_tool() -> AgentTool:
+ async def execute(call_id, args, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text=f"ran {args.cmd}")])
+
+ return AgentTool(
+ name="bash",
+ description="run a shell command",
+ parameters=_Params,
+ execute=execute,
+ execution_mode="sequential",
+ )
+
+
+def _ok_faux() -> FauxProvider:
+ p = FauxProvider(provider_id="faux")
+ p.set_responses(
+ [AssistantMessage(content=[TextContent(text="ok")], stop_reason="end_turn")]
+ )
+ return p
+
+
+# ---------------------------------------------------------------------------
+# Clean success path → mark_run_complete IS called.
+# ---------------------------------------------------------------------------
+
+
+async def test_clean_success_marks_complete():
+ cp = MemoryCheckpointer()
+ a = Agent(model=_ok_faux().model("faux-m"), checkpointer=cp, thread_id="t")
+ got = await a.prompt("hi", run_id="R1")
+ assert got == "R1"
+ assert a.state.last_outcome == "complete"
+ assert a.state.active_run_id is None
+ # mark_run_complete actually ran — row has completion_seq set.
+ state = cp._runs["t"]["R1"]
+ assert state.completed_at is not None
+ assert state.completion_seq is not None
+
+
+# ---------------------------------------------------------------------------
+# Provider error → loop emits stop_reason="error" → outcome="abandoned" → no mark.
+# ---------------------------------------------------------------------------
+
+
+async def test_provider_error_does_not_mark():
+ """FauxProvider with no queued responses surfaces stop_reason=error."""
+ cp = MemoryCheckpointer()
+ provider = FauxProvider(provider_id="faux")
+ # Empty response queue → faux returns AssistantMessage(stop_reason="error").
+ a = Agent(model=provider.model("faux-m"), checkpointer=cp, thread_id="t")
+ got = await a.prompt("hi", run_id="R1") # _handle_run_failure swallows
+ assert got == "R1"
+ assert a.state.last_outcome == "abandoned"
+ # Run row claimed but NOT completed — still resumable.
+ state = cp._runs["t"]["R1"]
+ assert state.completed_at is None
+
+
+# ---------------------------------------------------------------------------
+# HITL detach → outcome="suspended" → no mark.
+# ---------------------------------------------------------------------------
+
+
+def _two_turn_bash_responses():
+ return [
+ faux_assistant_message(
+ [faux_text("ok"), faux_tool_call("bash", {"cmd": "ls"}, id="tc-1")],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("done"),
+ ]
+
+
+async def test_hitl_detached_outcome_suspended_no_mark():
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t")
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(_two_turn_bash_responses())
+ a = Agent(
+ model=provider.model("faux-m"),
+ tools=[_bash_tool()],
+ middleware=[ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser())],
+ channel=ch,
+ checkpointer=cp,
+ thread_id="t",
+ )
+
+ task = asyncio.create_task(a.prompt("hi", run_id="R1"))
+ # Wait for pending HITL request.
+ for _ in range(200):
+ if ch.pending is not None:
+ break
+ await asyncio.sleep(0.01)
+ else:
+ pytest.fail("agent did not suspend on HITL")
+
+ await a.detach()
+ await task
+
+ assert a.state.last_outcome == "suspended"
+ # Row claimed, NOT completed.
+ state = cp._runs["t"]["R1"]
+ assert state.completed_at is None
+ # active_run_id cleared on clean else: branch (suspended is NOT an error).
+ assert a.state.active_run_id is None
+
+
+# ---------------------------------------------------------------------------
+# HITL abort_pending → outcome="abandoned" → no mark.
+# ---------------------------------------------------------------------------
+
+
+async def test_hitl_aborted_via_abort_pending_does_not_mark():
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t")
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(_two_turn_bash_responses())
+ a = Agent(
+ model=provider.model("faux-m"),
+ tools=[_bash_tool()],
+ middleware=[ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser())],
+ channel=ch,
+ checkpointer=cp,
+ thread_id="t",
+ )
+
+ task = asyncio.create_task(a.prompt("hi", run_id="R1"))
+ for _ in range(200):
+ if ch.pending is not None:
+ break
+ await asyncio.sleep(0.01)
+ else:
+ pytest.fail("agent did not suspend on HITL")
+
+ # abort_pending: Phase 1 sets the agent signal — _BaseChannel._await_answer
+ # raises HitlAborted, which surfaces from the loop as outcome="abandoned".
+ await a.abort_pending(reason="user closed")
+ await task
+
+ assert a.state.last_outcome == "abandoned"
+ # Row claimed, NOT completed.
+ state = cp._runs["t"]["R1"]
+ assert state.completed_at is None
+
+
+# ---------------------------------------------------------------------------
+# Propagating asyncio.CancelledError → outcome stays None → no mark.
+# ---------------------------------------------------------------------------
+
+
+async def test_propagating_cancel_does_not_mark():
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t")
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(_two_turn_bash_responses())
+ a = Agent(
+ model=provider.model("faux-m"),
+ tools=[_bash_tool()],
+ middleware=[ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser())],
+ channel=ch,
+ checkpointer=cp,
+ thread_id="t",
+ )
+
+ task = asyncio.create_task(a.prompt("hi", run_id="R1"))
+ for _ in range(200):
+ if ch.pending is not None:
+ break
+ await asyncio.sleep(0.01)
+ else:
+ pytest.fail("agent did not suspend on HITL")
+
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ # Cancel propagates through prompt()'s `except BaseException: raise` —
+ # active_run_id stays SET; no mark_run_complete call.
+ assert a.state.active_run_id == "R1"
+ state = cp._runs["t"]["R1"]
+ assert state.completed_at is None
+ # last_outcome may remain None (no loop terminal path fired).
+ assert a.state.last_outcome != "complete"
+
+
+# ---------------------------------------------------------------------------
+# CompletionMarkerFailedError path: when mark_run_complete raises, the wrapped
+# error propagates UP through prompt() carrying the generated run_id, and
+# active_run_id stays SET so the host can introspect it.
+# ---------------------------------------------------------------------------
+
+
+async def test_completion_marker_failed_carries_run_id_when_generated():
+ cp = MemoryCheckpointer()
+
+ boom_raised: dict[str, bool] = {}
+
+ async def _boom_mark(thread_id: str, run_id: str) -> None:
+ boom_raised["called"] = True
+ boom_raised["run_id"] = run_id
+ raise RunNotClaimedError("simulated DB hiccup")
+
+ # Monkey-patch mark_run_complete on this checkpointer instance.
+ cp.mark_run_complete = _boom_mark # type: ignore[method-assign]
+
+ a = Agent(model=_ok_faux().model("faux-m"), checkpointer=cp, thread_id="t")
+ # run_id=None → cubepi generates one. Test that the generated value is
+ # carried on the raised CompletionMarkerFailedError.
+ with pytest.raises(CompletionMarkerFailedError) as excinfo:
+ await a.prompt("hi")
+
+ assert boom_raised.get("called") is True
+ err = excinfo.value
+ assert err.thread_id == "t"
+ assert err.run_id == boom_raised["run_id"]
+ # active_run_id stays SET — the clear line is unreachable past the raise.
+ assert a.state.active_run_id == err.run_id
+ # Outcome was "complete" before dispatch failed.
+ assert a.state.last_outcome == "complete"