CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
fix(agent): codex R3 P1 — resume() must claim a run + stamp messages
xf gong608456dd0017
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.pyindex 6781af5..c099574 100644--- a/cubepi/agent/agent.py+++ b/cubepi/agent/agent.py@@ -357,7 +357,7 @@ class Agent(Generic[TMessage]):returnraise ValueError(f"Agent has checkpointed HITL elements bound to "- f"run_ids {sorted(bound)!r}; prompt(run_id=...) "+ f"run_ids {sorted(bound)!r}; {caller}(run_id=...) ""must be explicitly supplied (generate-mode rejected)")if any(b != run_id for b in bound):@@ -587,37 +587,65 @@ class Agent(Generic[TMessage]):},)- async def resume(self) -> None:+ async def resume(self, *, run_id: str | None = None) -> str:# Same fail-fast pattern as prompt(): lock.locked() is the atomic gate.if self._run_lock.locked() or self._state.is_streaming:raise RuntimeError("Agent is already processing. Wait for completion before continuing.")- async with self._run_lock:- if self._state.is_streaming: # pragma: no cover — defensive re-check- raise RuntimeError(- "Agent is already processing. Wait for completion before continuing."- )-- if not self._state._messages:- raise RuntimeError("No messages to continue from")-- last = self._state._messages[-1]- if isinstance(last, AssistantMessage):- # Check for queued messages- steering = self._steering_queue.drain()- if steering:- await self._run_prompt(steering)- return-- follow_ups = self._follow_up_queue.drain()- if follow_ups:- await self._run_prompt(follow_ups)- return+ self._validate_hitl_bindings(run_id, caller="resume")+ effective_run_id = run_id or uuid.uuid4().hex+ try:+ async with self._run_lock:+ if self._state.is_streaming: # pragma: no cover — defensive re-check+ raise RuntimeError(+ "Agent is already processing. "+ "Wait for completion before continuing."+ )- raise RuntimeError("Cannot continue from message role: assistant")+ if not self._state._messages:+ raise RuntimeError("No messages to continue from")++ last = self._state._messages[-1]+ # Validate preconditions BEFORE claim_run so a precondition+ # failure does not leave a claimed run dangling on the+ # checkpointer.+ if isinstance(last, AssistantMessage) and not (+ self._steering_queue.has_items()+ or self._follow_up_queue.has_items()+ ):+ raise RuntimeError("Cannot continue from message role: assistant")++ # Claim + stamp under the lock (same invariants as prompt()):+ # without this, messages emitted by the resumed turn would+ # land with run_id=None and fork queries (which treat NULL+ # as legacy / always-copy) would happily copy them into a+ # later fork even if this resumed work is still in flight or+ # later abandoned.+ if self._run_aware and self.thread_id is not None:+ 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- await self._run_continuation()+ if isinstance(last, AssistantMessage):+ steering = self._steering_queue.drain()+ if steering:+ await self._run_prompt(steering)+ else:+ follow_ups = self._follow_up_queue.drain()+ await self._run_prompt(follow_ups)+ else:+ await self._run_continuation()+ except BaseException:+ # Spec §3.7 parity: leave active_run_id SET on failure so callers+ # can observe which run failed.+ raise+ else:+ outcome: RunOutcome = self._state.last_outcome or "abandoned"+ await self._dispatch_outcome(outcome, effective_run_id)+ self._state.active_run_id = None+ return effective_run_iddef _build_stream_options(self, signal: asyncio.Event) -> StreamOptions:return StreamOptions(diff --git a/tests/agent/test_agent_claim_run.py b/tests/agent/test_agent_claim_run.pyindex e538a78..e99080b 100644--- a/tests/agent/test_agent_claim_run.py+++ b/tests/agent/test_agent_claim_run.py@@ -85,6 +85,80 @@ async def test_degraded_mode_v3_only_checkpointer():assert isinstance(got, str)+async def test_resume_claims_run_and_stamps_messages():+ """Regression for codex R3 P1: `resume()` must claim a run, set+ `active_run_id`, and dispatch completion — otherwise messages emitted+ by the resumed turn land with `run_id=None` and fork queries (which+ treat NULL as legacy / always-copy) would copy them into forks even+ if the resumed work is still in flight or later abandoned.+ """+ from cubepi.providers.base import TextContent, UserMessage++ cp = MemoryCheckpointer()+ a = _agent(checkpointer=cp, thread_id="t")+ # Hydrate state from a persisted UserMessage (the documented+ # checkpointed-resume pattern: host reloads from checkpointer, then+ # calls resume()).+ a._state._messages = [+ UserMessage(content=[TextContent(text="hi")], run_id="R_seed"),+ ]++ effective = await a.resume(run_id="R_resume")+ assert effective == "R_resume"+ # The run was claimed AND completed.+ assert "R_resume" in cp._runs["t"]+ assert cp._runs["t"]["R_resume"].completed_at is not None+ # Messages emitted by the resumed turn carry the resume run_id.+ appended = a.state.messages[1:]+ assert appended # the faux provider yielded an assistant message+ for m in appended:+ assert m.run_id == "R_resume", (+ f"message emitted by resume() left with run_id={m.run_id!r} "+ "(would be treated as legacy by fork queries)"+ )+++async def test_resume_auto_generates_run_id_when_not_supplied():+ """resume() without an explicit run_id auto-generates one."""+ from cubepi.providers.base import TextContent, UserMessage++ cp = MemoryCheckpointer()+ a = _agent(checkpointer=cp, thread_id="t")+ a._state._messages = [+ UserMessage(content=[TextContent(text="hi")], run_id="R_seed"),+ ]+ effective = await a.resume()+ assert isinstance(effective, str) and len(effective) > 0+ assert effective in cp._runs["t"]+ assert cp._runs["t"][effective].completed_at is not None+++async def test_resume_precondition_failure_does_not_claim():+ """Precondition failure ('Cannot continue from message role: assistant')+ must NOT call claim_run — otherwise a dangling claimed run would+ block re-resume with the same run_id.+ """+ from cubepi.providers.base import AssistantMessage, TextContent++ cp = MemoryCheckpointer()+ a = _agent(checkpointer=cp, thread_id="t")+ # Last message is AssistantMessage with no queued steering/follow-up.+ a._state._messages = [+ AssistantMessage(+ content=[TextContent(text="done")],+ stop_reason="end_turn",+ run_id="R_prev",+ ),+ ]+ with pytest.raises(RuntimeError, match="Cannot continue"):+ await a.resume(run_id="R_new")+ # R_new was NOT claimed — the precondition raised before the claim.+ assert "R_new" not in cp._runs.get("t", {})++@pytest.mark.asyncioasync def test_concurrent_cold_prompts_second_raises_fast():"""Two concurrent cold prompt() calls — the second must raise immediately