diff --git a/src/agent_env/a2a_agent/conversation_store.py b/src/agent_env/a2a_agent/conversation_store.py
index 8721e4bf4..1ada4fed6 100644
--- a/src/agent_env/a2a_agent/conversation_store.py
+++ b/src/agent_env/a2a_agent/conversation_store.py
@@ -62,6 +62,7 @@ def create_conversation(
task_instance_id: str,
source_agent_name: str,
target_agent_name: str,
+ step_id: Optional[str] = None,
) -> dict:
"""Insert a new conversation in the `active` state with empty messages and a2a_tasks.
@@ -72,8 +73,13 @@ def create_conversation(
HITL where a solver consults a human peer: source=the solver's name,
target="human_agent".
+ `step_id`, when given, is the step that owns the conversation, so a re-run of
+ that step can close what an earlier run left open (`close_active_for_step`).
+
Raises `agent_env.store.DuplicateKeyError` if `conversation_id` already
- exists — callers should treat that as "use the existing conversation."
+ exists and the store has the unique index `ensure_indexes` creates. A store
+ without that index inserts a second document with the same id, so a caller
+ that may re-run looks for the conversation first (`reopen`).
"""
now = datetime.now(timezone.utc)
doc = {
@@ -89,6 +95,8 @@ def create_conversation(
"created_at_utc": now,
"updated_at_utc": now,
}
+ if step_id is not None:
+ doc["step_id"] = step_id
_doc_store().insert(_COLLECTION_NAME, doc)
return doc
@@ -139,12 +147,15 @@ def add_a2a_task(
(never rewritten), so no entry is dropped.
Returns the post-update conversation doc, or None if `conversation_id`
- doesn't exist.
+ doesn't exist or is no longer `active`. The status is read under the same
+ swap, so a close that lands first refuses the append rather than racing it.
"""
now = datetime.now(timezone.utc)
new_message = _message(role, parts, now, env_clock)
- def _mutate(doc: dict) -> UpdateSpec:
+ def _mutate(doc: dict) -> Optional[UpdateSpec]:
+ if doc.get("status") != "active":
+ return None
idx = len(doc.get("messages", []))
new_a2a_task = {
"a2a_task_id": a2a_task_id,
@@ -171,8 +182,10 @@ def complete_a2a_task(
parts: list[dict],
role: str,
env_clock: Optional[list[dict]] = None,
+ state: TaskState = TaskState.completed,
) -> Optional[dict]:
- """Append a responder-side message and complete the oldest working a2a_task.
+ """Append a responder-side message and end the oldest working a2a_task in `state`,
+ the terminal state the responder's own task reached.
Called when the responder replies. The responder's role depends on the
conversation direction:
@@ -226,7 +239,7 @@ def complete_a2a_task(
_REV, rev_precondition(existing, _REV)
)
if oldest_working_idx is not None:
- spec.set[f"a2a_tasks.{oldest_working_idx}.state"] = TaskState.completed.value
+ spec.set[f"a2a_tasks.{oldest_working_idx}.state"] = TaskState(state).value
spec.set[f"a2a_tasks.{oldest_working_idx}.response_message_idx"] = idx
spec.set[f"a2a_tasks.{oldest_working_idx}.ended_at"] = now.isoformat()
filter_ = filter_.where(
@@ -304,15 +317,14 @@ def cancel_a2a_task(
)
-def mark_closed(conversation_id: str) -> Optional[dict]:
- """Set `status=closed` and cancel any working a2a_tasks.
+def _end_working_tasks(conversation_id: str, status: str) -> Optional[dict]:
+ """Set `status`, clear `pending` and cancel any working a2a_tasks.
Reads the conversation, cancels working a2a_tasks in Python, and writes the
transformed array back under a `rev` compare-and-swap so a concurrently
appended a2a_task (e.g. a `start_a2a_task` push that lands between the read
and the write) is not clobbered by this whole-array write. On a lost swap we
- re-read and re-transform; a task that landed mid-close is then canceled too,
- which is correct for a terminal close.
+ re-read and re-transform; a task that landed mid-write is then canceled too.
Returns the post-update conversation doc, or None if not found.
"""
@@ -338,7 +350,7 @@ def mark_closed(conversation_id: str) -> Optional[dict]:
),
UpdateSpec(
set={
- "status": "closed",
+ "status": status,
"pending": False,
"updated_at_utc": now,
"a2a_tasks": new_tasks,
@@ -349,8 +361,30 @@ def mark_closed(conversation_id: str) -> Optional[dict]:
if result is not None:
return result
raise RuntimeError(
- f"mark_closed: rev CAS did not converge for conversation_id={conversation_id}"
+ f"set status {status}: rev CAS did not converge for conversation_id={conversation_id}"
+ )
+
+
+def mark_closed(conversation_id: str) -> Optional[dict]:
+ """Set `status=closed` and cancel any working a2a_tasks. Returns the post-update doc, or None if not found."""
+ return _end_working_tasks(conversation_id, "closed")
+
+
+def reopen(conversation_id: str) -> Optional[dict]:
+ """Set `status=active` for a re-run of the conversation's owner, canceling any working a2a_tasks an earlier
+ run left, so the next reply completes the re-run's own task. Returns the post-update doc, or None if not found."""
+ return _end_working_tasks(conversation_id, "active")
+
+
+def close_active_for_step(task_instance_id: str, step_id: str) -> list[str]:
+ """Close every active conversation step `step_id` of `task_instance_id` created; return their ids."""
+ active = _doc_store().query(
+ _COLLECTION_NAME, Filter.of(task_instance_id=task_instance_id, step_id=step_id, status="active")
)
+ closed = [doc["conversation_id"] for doc in active]
+ for conversation_id in closed:
+ mark_closed(conversation_id)
+ return closed
def list_pending(limit: int = 50) -> list[dict]:
diff --git a/src/agent_env/task_step/task_steps/prompt_agent.py b/src/agent_env/task_step/task_steps/prompt_agent.py
index 3d4f61362..c16e07507 100644
--- a/src/agent_env/task_step/task_steps/prompt_agent.py
+++ b/src/agent_env/task_step/task_steps/prompt_agent.py
@@ -113,6 +113,10 @@ def _parse_structured_output(text: str) -> Optional[dict]:
return last
+class _ConversationClosed(Exception):
+ """The store refused the turn because someone closed the conversation, so the message is not sent."""
+
+
def _duplicates_prompt_text(parts: list[dict], prompt_text: Optional[str]) -> bool:
"""True when ``parts`` is exactly the single text part already persisted as
``PromptResponse.prompt_text`` — i.e. the first conversation turn of a
@@ -504,6 +508,11 @@ async def _execute(self, context: TaskStepContext) -> TaskStepContext:
# Minted here, not in `_execute_conversation`, so the series can address the
# same session before the first turn.
a2a_context_id = self.context_id or uuid.uuid4().hex
+ if not self.context_id and context.instance_id:
+ # Before anything reaches the agent, so a re-run that fails early still closes what a dead run left active.
+ leftovers = conversation_store.close_active_for_step(context.instance_id, self.id)
+ if leftovers:
+ logger.info(f"prompt_agent '{self.id}': closed conversations an earlier run left active: {leftovers}")
if not self.snapshot_config:
return await self._execute_conversation(context, a2a_context_id=a2a_context_id)
series = SnapshotSeries(
@@ -652,22 +661,6 @@ async def _converse(
conversation_id = f"{self.context_id}-{run_component}-{len(run_component)}"
else:
conversation_id = solver_context_id
- try:
- conversation_store.create_conversation(
- conversation_id=conversation_id,
- task_instance_id=context.instance_id or "",
- source_agent_name=self.user_agent_name,
- target_agent_name=self.agent_name,
- )
- except DuplicateKeyError:
- # reuse a pre-existing conversation on retry/resume (store raises agent_env.store.DuplicateKeyError, not pymongo's)
- logger.info(f"Reusing existing conversation {conversation_id} on re-run")
- context.metadata.setdefault("a2a_conversations", {})[self.id] = conversation_id
- logger.info(
- f"Started multi-turn conversation {conversation_id} (max {self.max_conversation_turns} turns) "
- f"between {self.user_agent_name} and {self.agent_name}"
- )
-
current_user_parts = initial_parts
clock_envs = [d for d in context.deployed_envs if d.supports(EXT_CLOCK_URI, "state")]
# What comes due for the agent's role on these envs (notifications/v1) opens its next message.
@@ -714,6 +707,26 @@ async def _converse(
# Set by a user's done with a message: the agent answers it, then the conversation ends for this reason.
end_after: Optional[str] = None
+ # A re-run under the same instance id (a retry) takes back the conversation its earlier run closed.
+ if conversation_store.reopen(conversation_id) is not None:
+ logger.info(f"Reusing existing conversation {conversation_id} on re-run")
+ else:
+ try:
+ conversation_store.create_conversation(
+ conversation_id=conversation_id,
+ task_instance_id=context.instance_id or "",
+ source_agent_name=self.user_agent_name,
+ target_agent_name=self.agent_name,
+ step_id=None if self.context_id else self.id,
+ )
+ except DuplicateKeyError: # another run created it after our reopen found none
+ conversation_store.reopen(conversation_id)
+ context.metadata.setdefault("a2a_conversations", {})[self.id] = conversation_id
+ logger.info(
+ f"Started multi-turn conversation {conversation_id} (max {self.max_conversation_turns} turns) "
+ f"between {self.user_agent_name} and {self.agent_name}"
+ )
+
try:
for turn in range(self.max_conversation_turns):
# `target_a2a_task_id` is the client A2A message id sent to the target
@@ -725,14 +738,16 @@ async def _converse(
# The turn records the objects' own URLs, and only once the parts are ready to send, so an
# object the agent can't be sent leaves no turn waiting.
def record_turn() -> None:
- sent_to_target.update(_file_uris(current_user_parts))
- conversation_store.add_a2a_task(
+ recorded = conversation_store.add_a2a_task(
conversation_id=conversation_id,
parts=current_user_parts,
a2a_task_id=target_a2a_task_id,
role="user",
**sent_clock,
)
+ if recorded is None:
+ raise _ConversationClosed()
+ sent_to_target.update(_file_uris(current_user_parts))
# Turn 0 of a prompt-mode step re-sends exactly the text already
# persisted as PromptResponse.prompt_text; store a None placeholder
# instead of a second copy so the doc doesn't carry the prompt twice.
@@ -752,6 +767,13 @@ def record_turn() -> None:
poll_interval_seconds=self.poll_interval_seconds, before_send=record_turn,
on_sent=live_turn.follow if live_turn else None,
)
+ except _ConversationClosed:
+ if turn == 0:
+ raise RuntimeError(
+ f"conversation {conversation_id} was closed before the first turn; "
+ "nothing was sent to the agent") from None
+ logger.info(f"Conversation {conversation_id} was closed before turn {turn+1}; ending multi-turn")
+ break
except (TimeoutError, asyncio.CancelledError):
usage.cut_off(ModelRole.SOLVER)
raise
@@ -768,6 +790,7 @@ def record_turn() -> None:
conversation_id=conversation_id,
parts=agent_response_parts,
role="agent",
+ state=target_state,
**(await self._env_clock(clock_envs)),
)
@@ -856,6 +879,13 @@ def record_turn() -> None:
atif_copies.cancel()
raise
finally:
+ # Before any await, so a cancellation landing in this cleanup can't skip it.
+ try:
+ final_conv = conversation_store.get_conversation(conversation_id)
+ if final_conv and final_conv.get("status") == "active":
+ conversation_store.mark_closed(conversation_id)
+ except Exception:
+ logger.warning(f"Could not close conversation {conversation_id}", exc_info=True)
# On failure too, so a reader of the last turn knows no other follows.
if live_turns is not None:
await live_turns.end()
@@ -864,10 +894,6 @@ def record_turn() -> None:
await self._persist_env_trigger_state(context)
- final_conv = conversation_store.get_conversation(conversation_id)
- if final_conv and final_conv.get("status") == "active":
- conversation_store.mark_closed(conversation_id)
-
if trig_ext and triggers_registered: # best-effort firing-log readback (provenance only; never fails the run)
try:
async with httpx.AsyncClient() as client:
diff --git a/tst/formal/a2a_conversation/AGENTS.md b/tst/formal/a2a_conversation/AGENTS.md
new file mode 100644
index 000000000..6530fa6a2
--- /dev/null
+++ b/tst/formal/a2a_conversation/AGENTS.md
@@ -0,0 +1,125 @@
+# AGENTS.md: model-checking a prompt step's A2A conversation record
+
+How to check a change to how `prompt_agent` opens, records and closes its A2A conversation against the TLA+ model in
+this directory. The repository-wide rules are in the root `AGENTS.md`.
+
+`ConversationLifecycle.tla` models one `prompt_agent` step's record in the `agent_env_a2a_conversations` collection,
+the step that owns it (`PromptAgentTaskStep._converse`), a scheduler retry of the step under the same instance id, a
+process that dies mid-step, and a human peer's A2A endpoint that records its own turns through the same store and may
+close the conversation. Each store writer is one action: each loops on a `rev` compare-and-swap that rereads and
+recomputes on every attempt, so a lost attempt writes nothing. TLC, the TLA+ model checker, explores every order of
+those actors' calls. It checks six invariants:
+
+- `EndedStepLeavesConversationClosed`. When the step ends for any reason (it returns, times out, is cancelled or
+ raises), its conversation is closed. If it is left active and pending, `list_pending` keeps listing a dead run as
+ waiting for a reply, and its working task never ends.
+- `ClosedConversationGainsNoTask`. A closed conversation never gains a task. If it does, the record holds a working
+ task and `pending=True` that no one will answer.
+- `CompletedTaskWasNotAFailedTurn`. A task recorded `completed` was not a turn the agent failed. If it was, a reader
+ of the record (a `tasks/get` served from it, a grader) sees a failed turn as a success.
+- `StepTurnRefusedOnlyAfterOthersClose`. The store refuses the step's turn only when someone other than the step
+ closed the conversation during this run. If it refuses otherwise, a retry finds the conversation its own earlier run
+ closed and sends nothing.
+- `ReplyEndsItsOwnTask`. The agent's reply ends the step's task for that turn. `complete_a2a_task` ends the oldest
+ working task, so if an earlier run left one working, the retry's reply is stored against the earlier run's turn and
+ the retry's own turn stays working.
+- `StepThatSentNothingFails`. A run of the step that sent the agent nothing does not end as a success. If it does, the
+ step records an empty answer and a grader grades nothing.
+
+## Configs and the expected result
+
+Every config runs with two runs of the step, two turns each, at most one close by the peer and at most one process
+death. `check.sh` runs each config once per invariant.
+
+| Config | What it models | Breaks |
+| --- | --- | --- |
+| `before-fix.cfg` | the code before the fix: no close on exceptions, no status check, every reply recorded `completed`, no reopen | the first three invariants and `ReplyEndsItsOwnTask` |
+| `fixed.cfg` | the code as it is | nothing (39,211 distinct states) |
+| `mutant-no-finally.cfg` | no close in the `finally` | `EndedStepLeavesConversationClosed` |
+| `mutant-close-after-live-end.cfg` | the `finally` awaits `live_turns.end()` before it closes | `EndedStepLeavesConversationClosed` (a cancellation during that await skips the close) |
+| `mutant-no-guard.cfg` | no status check in `add_a2a_task` | `ClosedConversationGainsNoTask` |
+| `mutant-no-guard-no-peer-close.cfg` | the same, with a peer that never closes | `ClosedConversationGainsNoTask` (the peer records the step's message after the step closed) |
+| `mutant-no-end-state.cfg` | no `state=` in `complete_a2a_task` | `CompletedTaskWasNotAFailedTurn` |
+| `mutant-no-reopen.cfg` | no `reopen` on a re-run | `StepTurnRefusedOnlyAfterOthersClose`, `ReplyEndsItsOwnTask` |
+| `mutant-reopen-keeps-left-tasks.cfg` | `reopen` that does not cancel the working tasks a killed run left | `ReplyEndsItsOwnTask` |
+| `mutant-no-first-turn-failure.cfg` | a refused first turn ends the loop instead of raising | `StepThatSentNothingFails` |
+| `known-gap-late-peer-record.cfg` | the code as it is, where the peer's endpoint may record an earlier run's message after the retry reopened | `ReplyEndsItsOwnTask` |
+
+The last row is a gap in the code, not in the model. The earlier run asks the peer and dies or raises before the
+peer's endpoint records the ask. The retry reopens the conversation, and the endpoint then appends the earlier ask
+ahead of the retry's turn. The retry's reply ends that ask, because `complete_a2a_task` ends the oldest working task.
+Every other config keeps the endpoint to the current run's messages (`LatePeerRecord = FALSE`).
+
+## When to run it
+
+Run the check when a change touches a function in this table. Each action's comment in `ConversationLifecycle.tla`
+cites the lines it stands for. The paths are under `src/agent_env/`.
+
+| Code | Model action |
+| --- | --- |
+| `a2a_agent/conversation_store.py:add_a2a_task` | `Add`, `AddRefused`, used by `StepRecordsTurn` and `PeerRecordsMessage` |
+| `a2a_agent/conversation_store.py:complete_a2a_task` | `Complete`, used by `StepRecordsReply` and `PeerReplies` |
+| `a2a_agent/conversation_store.py:mark_closed`, `_end_working_tasks` | `Close` |
+| `a2a_agent/conversation_store.py:reopen`, `create_conversation` | `StepOpensConversation` |
+| `a2a_agent/conversation_store.py:list_pending` | the worklist `PeerReplies` reads |
+| `task_step/task_steps/prompt_agent.py:PromptAgentTaskStep._converse`, from `reopen` to the `finally` that closes | every `Step*` action |
+| `task_step/task_steps/prompt_agent.py:_UserSide._send_to_peer` | `StepAsksPeer`, `StepGetsAnswer`, `StepPeerEnds`, and `StepRaises` on a cancellation |
+| `task/task.py:_roll_back_span` (a retry re-runs the step under the same instance id) | `StepRetried` |
+
+The model was last confirmed against the code at the commit that last changed this directory
+(`git log -1 -- tst/formal/a2a_conversation`). To list the covered changes since then, run:
+
+```sh
+git log "$(git log -1 --format=%H -- tst/formal/a2a_conversation)"..HEAD -- \
+ src/agent_env/a2a_agent/conversation_store.py src/agent_env/task_step/task_steps/prompt_agent.py \
+ src/agent_env/task/task.py
+```
+
+After you confirm that the model still describes a change to the covered code, re-check every line citation in the
+spec and touch this guide in the same commit.
+
+## Run the check
+
+```sh
+tst/formal/a2a_conversation/check.sh
+```
+
+The script needs Java 11 or later and `tla2tools.jar` v1.7.4 (https://github.com/tlaplus/tlaplus/releases/tag/v1.7.4).
+The first run downloads the jar and checks its sha256. `TLA2TOOLS` names a local copy instead, which must match the
+same sha256, and `JAVA` names the java binary when it is not on `PATH`. The script exits nonzero when any run differs
+from the table above. A passing run prints 66 lines that start with `ok`, the `fixed` lines reading
+`holds 39211 distinct states found`, and ends with `TLC 1.7.4; specs, configs and tlc.out in
`.
+
+To run one config with plain TLC from this directory:
+
+```sh
+java -XX:+UseParallelGC -cp tla2tools.jar tlc2.TLC -workers 1 -metadir "$(mktemp -d)" -config fixed.cfg ConversationLifecycle.tla
+```
+
+It ends with `Model checking completed. No error has been found.` Plain TLC stops at the first invariant that breaks,
+so use `check.sh` to see every invariant.
+
+## How to read a failure
+
+An `UNEXPECTED` line names the config, the invariant and what TLC found. Its `tlc.out`, in the directory the last line
+prints, holds the shortest trace: one state per action, named by the action. Read the trace as calls in the code, using
+each action's citation.
+
+When an invariant breaks on `fixed.cfg`, replay the trace against the real code, as the tests in
+`tst/unit/task_step/test_prompt_agent_conversation_close.py` do: they run the step on the local document store and
+assert the stored record. If the replay produces the same record, the code has the bug. If it does not, the model has
+drifted: find the action whose citation no longer matches the code and fix the model, not the invariant.
+
+When a mutant config stops breaking its invariant, the model no longer depends on the guard that config removes. Check
+that the guard is still in the code and that its action still models it.
+
+## What the model leaves out
+
+- Two runs racing to create the conversation. `prompt_agent` catches the `DuplicateKeyError` the unique index raises
+ and reopens; a store without that index inserts a second document instead.
+- A store call that fails inside the `finally`. The step logs it and keeps the original exception, and the
+ conversation stays active.
+- The message arrays and their index pointers (`input_message_idx`, `response_message_idx`).
+- User simulators, post-turn hooks and notifications, which reach the store only through the same calls.
+- `always_on`, which closes its conversation in its own `finally`.
+- A process that dies and is never re-run: nothing closes its conversation, and no sweep or TTL does.
diff --git a/tst/formal/a2a_conversation/ConversationLifecycle.tla b/tst/formal/a2a_conversation/ConversationLifecycle.tla
new file mode 100644
index 000000000..a96062f51
--- /dev/null
+++ b/tst/formal/a2a_conversation/ConversationLifecycle.tla
@@ -0,0 +1,346 @@
+---- MODULE ConversationLifecycle ----
+\* One prompt_agent step's A2A conversation record (src/agent_env/a2a_agent/conversation_store.py)
+\* and the step that owns it (src/agent_env/task_step/task_steps/prompt_agent.py, PromptAgentTaskStep._converse),
+\* with a human peer's endpoint that records its own turns through the same store.
+\*
+\* Each store writer is one action: add_a2a_task, complete_a2a_task, mark_closed and reopen each loop
+\* on a `rev` compare-and-swap that rereads and recomputes on every attempt, so a lost attempt writes
+\* nothing and the call takes effect at its one successful write.
+EXTENDS Naturals, Sequences
+
+CONSTANTS
+ Attempts, \* how many times the scheduler may run the step (retry_config)
+ MaxTurns, \* max_conversation_turns
+ PeerMayClose, \* how many times the human may close the conversation: 0 or 1
+ Kills, \* how many times the process may die mid-step: 0 or 1
+ LatePeerRecord, \* the peer's endpoint may record an earlier run's message after a retry reopened
+ CloseOnAnyEnd, \* fix: the step closes its conversation in a finally
+ RefuseAddWhenClosed, \* fix: add_a2a_task appends only to an active conversation
+ RecordEndState, \* fix: complete_a2a_task records the reply's own end state
+ ReopenOnReuse, \* fix: a re-run that finds its conversation reopens it
+ ReopenCancelsLeftTasks, \* fix: reopen cancels the working tasks an earlier run left
+ FailOnFirstTurnRefused, \* fix: a refused first turn raises instead of ending the step with no answer
+ CloseBeforeLiveEnd \* fix: the finally closes the conversation before it awaits live_turns.end()
+
+VARIABLES
+ status, \* the conversation document's status: "none" before it exists
+ tasks, \* its a2a_tasks array
+ pending, \* its pending flag
+ pc, \* where the step is
+ attempt, \* which run of the step this is
+ retriesLeft, \* how many more times the scheduler may retry the step
+ killsLeft, \* how many more times the process may die
+ turn, \* the step's turn number
+ agentReply, \* how the agent's last reply ended: "completed" or "failed"
+ raised, \* this run of the step ended by an exception
+ recordedThisRun, \* this run of the step recorded a turn
+ messageToPeer, \* a message the step sent the human peer that its endpoint has not recorded yet
+ peerClosesLeft, \* how many more times the human may close the conversation
+ closedByPeer, \* the peer closed the conversation during this run of the step
+ addedWhileClosed, \* a task was appended to a closed conversation
+ ownTurnRefused, \* the store refused a turn of the step that nobody else had closed
+ wrongTaskCompleted \* the step's reply ended a task other than its own turn's
+
+vars == <>
+
+NoMessage == [attempt |-> 0, turn |-> 0]
+
+NewTask(kind, from) == [kind |-> kind, from |-> from, state |-> "working", reply |-> "none"]
+
+CancelWorking(ts) ==
+ [i \in DOMAIN ts |-> IF ts[i].state = "working" THEN [ts[i] EXCEPT !.state = "canceled"] ELSE ts[i]]
+
+OldestWorking ==
+ IF \E i \in DOMAIN tasks : tasks[i].state = "working"
+ THEN CHOOSE i \in DOMAIN tasks : tasks[i].state = "working" /\ \A j \in 1..(i - 1) : tasks[j].state # "working"
+ ELSE 0
+
+\* add_a2a_task (conversation_store.py:122-171). Refused leaves the record as it was.
+AddRefused == RefuseAddWhenClosed /\ status # "active"
+Add(kind, from) ==
+ /\ tasks' = Append(tasks, NewTask(kind, from))
+ /\ pending' = TRUE
+ /\ addedWhileClosed' = (addedWhileClosed \/ status # "active")
+
+\* complete_a2a_task (conversation_store.py:174-264): ends the oldest working task, whoever it belongs to.
+Complete(replyEnd) ==
+ /\ tasks' = IF OldestWorking = 0 THEN tasks
+ ELSE [tasks EXCEPT ![OldestWorking].state = IF RecordEndState THEN replyEnd ELSE "completed",
+ ![OldestWorking].reply = replyEnd]
+ /\ pending' = FALSE
+
+\* The oldest working task is not the step's task for this turn.
+EndsOtherTask ==
+ /\ OldestWorking # 0
+ /\ \/ tasks[OldestWorking].kind # "agent_turn"
+ \/ tasks[OldestWorking].from # [attempt |-> attempt, turn |-> turn]
+
+\* mark_closed (conversation_store.py:362-364, through _end_working_tasks at 314-359).
+Close ==
+ /\ status' = "closed"
+ /\ tasks' = CancelWorking(tasks)
+ /\ pending' = FALSE
+
+FinallyStart == IF CloseBeforeLiveEnd THEN "closing_read" ELSE "ending_live"
+
+FinallyExit(hasRaised) == IF hasRaised THEN "ended" ELSE "after_loop"
+
+Init ==
+ /\ status = "none"
+ /\ tasks = <<>>
+ /\ pending = FALSE
+ /\ pc = "start"
+ /\ attempt = 1
+ /\ retriesLeft = Attempts - 1
+ /\ killsLeft = Kills
+ /\ turn = 1
+ /\ agentReply = "none"
+ /\ raised = FALSE
+ /\ recordedThisRun = FALSE
+ /\ messageToPeer = NoMessage
+ /\ peerClosesLeft = PeerMayClose
+ /\ closedByPeer = FALSE
+ /\ addedWhileClosed = FALSE
+ /\ ownTurnRefused = FALSE
+ /\ wrongTaskCompleted = FALSE
+
+\* reopen, else create_conversation (prompt_agent.py:706-717; conversation_store.py:367-370, 60-95).
+StepOpensConversation ==
+ /\ pc = "start"
+ /\ IF status = "none"
+ THEN /\ status' = "active" /\ tasks' = <<>> /\ pending' = FALSE
+ ELSE IF ReopenOnReuse
+ THEN /\ status' = "active" /\ pending' = FALSE
+ /\ tasks' = IF ReopenCancelsLeftTasks THEN CancelWorking(tasks) ELSE tasks
+ ELSE UNCHANGED <>
+ /\ pc' = "turn"
+ /\ turn' = 1
+ /\ raised' = FALSE
+ /\ recordedThisRun' = FALSE
+ /\ closedByPeer' = FALSE
+ /\ UNCHANGED <>
+
+\* record_turn, run by send_and_wait just before the message goes out; a refusal raises _ConversationClosed, which
+\* fails the step on the first turn and ends the loop on a later one (prompt_agent.py:734-753, 757-770).
+StepRecordsTurn ==
+ /\ pc = "turn"
+ /\ IF AddRefused
+ THEN /\ raised' = (FailOnFirstTurnRefused /\ turn = 1)
+ /\ pc' = IF CloseOnAnyEnd THEN FinallyStart ELSE IF raised' THEN "ended" ELSE "after_loop"
+ /\ ownTurnRefused' = (ownTurnRefused \/ ~closedByPeer)
+ /\ UNCHANGED <>
+ ELSE /\ Add("agent_turn", [attempt |-> attempt, turn |-> turn])
+ /\ pc' = "waiting"
+ /\ recordedThisRun' = TRUE
+ /\ UNCHANGED <>
+ /\ UNCHANGED <>
+
+\* send_and_wait returns the agent's terminal task (prompt_agent.py:757-776).
+AgentReplies(end) ==
+ /\ pc = "waiting"
+ /\ agentReply' = end
+ /\ pc' = "replied"
+ /\ UNCHANGED <>
+
+LoopExit == IF CloseOnAnyEnd THEN FinallyStart ELSE "after_loop"
+
+\* complete_a2a_task for the agent's reply, then the failed / last-turn breaks (prompt_agent.py:783-789, 822-830).
+StepRecordsReply ==
+ /\ pc = "replied"
+ /\ Complete(agentReply)
+ /\ wrongTaskCompleted' = (wrongTaskCompleted \/ EndsOtherTask)
+ /\ pc' = IF agentReply = "failed" THEN "close_now"
+ ELSE IF turn = MaxTurns THEN LoopExit
+ ELSE "check"
+ /\ UNCHANGED <>
+
+\* mark_closed where the loop ends the conversation itself (prompt_agent.py:823, 859, 870).
+StepEndsConversation ==
+ /\ pc = "close_now"
+ /\ Close
+ /\ pc' = LoopExit
+ /\ UNCHANGED <>
+
+\* get_conversation: someone else may have closed it (prompt_agent.py:832-835).
+StepChecksActive ==
+ /\ pc = "check"
+ /\ pc' = IF status # "active" THEN LoopExit ELSE "asking"
+ /\ UNCHANGED <>
+
+\* _UserSide._send_to_peer: message/send to the human peer (prompt_agent.py:853, 1421-1439).
+StepAsksPeer ==
+ /\ pc = "asking"
+ /\ messageToPeer' = [attempt |-> attempt, turn |-> turn]
+ /\ pc' = "awaiting_peer"
+ /\ UNCHANGED <>
+
+\* The peer's task is the step's open ask; its state reaches the step through the peer's tasks/get.
+PeerTaskEnded(end) ==
+ \E i \in DOMAIN tasks : /\ tasks[i].kind = "peer_turn" /\ tasks[i].state = end
+ /\ tasks[i].from = [attempt |-> attempt, turn |-> turn]
+
+\* The peer answered: the conversation goes on (prompt_agent.py:1458-1459, 866).
+StepGetsAnswer ==
+ /\ pc = "awaiting_peer"
+ /\ PeerTaskEnded("completed")
+ /\ turn' = turn + 1
+ /\ pc' = "turn"
+ /\ UNCHANGED <>
+
+\* The peer's task ended otherwise, or the step's wait for it ran out: {"end": ...}
+\* (prompt_agent.py:1443-1456, 854-860).
+StepPeerEnds ==
+ /\ pc = "awaiting_peer"
+ /\ pc' = "close_now"
+ /\ UNCHANGED <>
+
+\* Anything in the step raises: a TimeoutError or AgentUnreachableError from the agent's poll, a cancellation,
+\* a failed trajectory join or trigger-state write (prompt_agent.py:771-773, 1440-1442, 886-889).
+StepRaises ==
+ /\ pc \in {"turn", "waiting", "replied", "check", "asking", "awaiting_peer", "after_loop"}
+ /\ raised' = TRUE
+ /\ pc' = IF CloseOnAnyEnd /\ pc # "after_loop" THEN FinallyStart ELSE "ended"
+ /\ UNCHANGED <>
+
+\* The process dies mid-step, so no finally runs, and a later run under the same instance id runs the step again.
+\* reopen's docstring names this case (conversation_store.py:368-369).
+StepKilled ==
+ /\ pc \in {"turn", "waiting", "replied", "close_now", "check", "asking", "awaiting_peer", "after_loop",
+ "closing_read", "closing_write", "ending_live"}
+ /\ killsLeft > 0
+ /\ killsLeft' = killsLeft - 1
+ /\ attempt' = attempt + 1
+ /\ pc' = "start"
+ /\ UNCHANGED <>
+
+\* Joining the trajectory copies and saving trigger state, after the loop (prompt_agent.py:886-889).
+StepFinishesLoop ==
+ /\ pc = "after_loop"
+ /\ pc' = IF CloseOnAnyEnd THEN "ended" ELSE "closing_read"
+ /\ UNCHANGED <>
+
+CloseDone ==
+ IF ~CloseOnAnyEnd THEN "ended" ELSE IF CloseBeforeLiveEnd THEN "ending_live" ELSE FinallyExit(raised)
+
+\* get_conversation, then mark_closed if still active (prompt_agent.py:877-880).
+StepReadsForClose ==
+ /\ pc = "closing_read"
+ /\ pc' = IF status = "active" THEN "closing_write"
+ ELSE CloseDone
+ /\ UNCHANGED <>
+
+StepClosesAtEnd ==
+ /\ pc = "closing_write"
+ /\ Close
+ /\ pc' = CloseDone
+ /\ UNCHANGED <>
+
+\* await live_turns.end() (prompt_agent.py:884-885), which ends or is cancelled; a cancellation leaves the finally
+\* there and skips whatever of it comes after.
+StepEndsLiveTurns ==
+ /\ pc = "ending_live"
+ /\ pc' = IF CloseBeforeLiveEnd THEN FinallyExit(raised) ELSE "closing_read"
+ /\ UNCHANGED <>
+
+StepCancelledEndingLiveTurns ==
+ /\ pc = "ending_live"
+ /\ raised' = TRUE
+ /\ pc' = "ended"
+ /\ UNCHANGED <>
+
+\* A failed step with retries left is run again under the same instance id (task.py:_roll_back_span).
+StepRetried ==
+ /\ pc = "ended"
+ /\ raised
+ /\ retriesLeft > 0
+ /\ retriesLeft' = retriesLeft - 1
+ /\ attempt' = attempt + 1
+ /\ pc' = "start"
+ /\ UNCHANGED <>
+
+StepFinished ==
+ /\ pc = "ended"
+ /\ ~(raised /\ retriesLeft > 0)
+ /\ pc' = "done"
+ /\ UNCHANGED <>
+
+\* The peer's endpoint records the step's message as its own task, possibly after the step stopped waiting.
+PeerRecordsMessage ==
+ /\ messageToPeer # NoMessage
+ /\ LatePeerRecord \/ messageToPeer.attempt = attempt
+ /\ messageToPeer' = NoMessage
+ /\ IF AddRefused
+ THEN UNCHANGED <>
+ ELSE Add("peer_turn", messageToPeer)
+ /\ UNCHANGED <>
+
+\* The human answers a conversation the worklist (list_pending, conversation_store.py:373-383) shows.
+PeerReplies ==
+ /\ status = "active"
+ /\ pending
+ /\ \E i \in DOMAIN tasks : tasks[i].kind = "peer_turn" /\ tasks[i].state = "working"
+ /\ Complete("completed")
+ /\ UNCHANGED <>
+
+PeerCloses ==
+ /\ status = "active"
+ /\ peerClosesLeft > 0
+ /\ Close
+ /\ peerClosesLeft' = peerClosesLeft - 1
+ /\ closedByPeer' = TRUE
+ /\ UNCHANGED <>
+
+Done == pc = "done" /\ UNCHANGED vars
+
+Next ==
+ \/ StepOpensConversation \/ StepRecordsTurn \/ AgentReplies("completed") \/ AgentReplies("failed")
+ \/ StepRecordsReply \/ StepEndsConversation \/ StepChecksActive \/ StepAsksPeer \/ StepGetsAnswer
+ \/ StepPeerEnds \/ StepRaises \/ StepKilled \/ StepFinishesLoop \/ StepReadsForClose \/ StepClosesAtEnd
+ \/ StepEndsLiveTurns \/ StepCancelledEndingLiveTurns \/ StepRetried \/ StepFinished
+ \/ PeerRecordsMessage \/ PeerReplies \/ PeerCloses
+ \/ Done
+
+Spec == Init /\ [][Next]_vars
+
+\* When the step ends for any reason, its conversation is closed, so no worklist shows it as waiting.
+EndedStepLeavesConversationClosed == pc \in {"ended", "done"} => status = "closed"
+
+\* A closed conversation never gains a task.
+ClosedConversationGainsNoTask == ~addedWhileClosed
+
+\* A task recorded completed was not a failed turn.
+CompletedTaskWasNotAFailedTurn ==
+ \A i \in DOMAIN tasks : tasks[i].state = "completed" => tasks[i].reply # "failed"
+
+\* The store refuses the step's turn only when someone else closed the conversation in this run.
+StepTurnRefusedOnlyAfterOthersClose == ~ownTurnRefused
+
+\* The agent's reply ends the step's task for that turn, not one an earlier run left.
+ReplyEndsItsOwnTask == ~wrongTaskCompleted
+
+\* A run of the step that sent the agent nothing does not end as a success.
+StepThatSentNothingFails == (pc \in {"ended", "done"} /\ ~raised) => recordedThisRun
+
+====
diff --git a/tst/formal/a2a_conversation/before-fix.cfg b/tst/formal/a2a_conversation/before-fix.cfg
new file mode 100644
index 000000000..26356919c
--- /dev/null
+++ b/tst/formal/a2a_conversation/before-fix.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 1
+ Kills = 1
+ LatePeerRecord = FALSE
+ CloseOnAnyEnd = FALSE
+ RefuseAddWhenClosed = FALSE
+ RecordEndState = FALSE
+ ReopenOnReuse = FALSE
+ ReopenCancelsLeftTasks = FALSE
+ CloseBeforeLiveEnd = FALSE
+ FailOnFirstTurnRefused = FALSE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/formal/a2a_conversation/check.sh b/tst/formal/a2a_conversation/check.sh
new file mode 100755
index 000000000..0cbc9b37f
--- /dev/null
+++ b/tst/formal/a2a_conversation/check.sh
@@ -0,0 +1,76 @@
+#!/usr/bin/env bash
+# Check every config of ConversationLifecycle.tla against every rule, one rule per TLC run, and compare with EXPECTED.
+#
+# tst/formal/a2a_conversation/check.sh
+#
+# Exits nonzero when any result differs. Needs Java 11+ and, on the first run, the network to fetch tla2tools.jar
+# v1.7.4, unless TLA2TOOLS names a copy; either jar must match the pinned sha256. JAVA names the java binary when it
+# is not on PATH.
+set -euo pipefail
+
+here=$(cd "$(dirname "$0")" && pwd)
+TLA_VERSION=1.7.4
+TLA_SHA256=936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88
+TLA_URL=https://github.com/tlaplus/tlaplus/releases/download/v$TLA_VERSION/tla2tools.jar
+java=${JAVA:-java}
+out=${OUT:-$(mktemp -d "${TMPDIR:-/tmp}/conversation-lifecycle-tlc.XXXXXX")}
+
+RULES=(EndedStepLeavesConversationClosed ClosedConversationGainsNoTask CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose ReplyEndsItsOwnTask StepThatSentNothingFails)
+# config: the rules it must break; every other rule must hold.
+EXPECTED=(
+ "before-fix: EndedStepLeavesConversationClosed ClosedConversationGainsNoTask CompletedTaskWasNotAFailedTurn ReplyEndsItsOwnTask"
+ "fixed:"
+ "mutant-no-finally: EndedStepLeavesConversationClosed"
+ "mutant-close-after-live-end: EndedStepLeavesConversationClosed"
+ "mutant-no-guard: ClosedConversationGainsNoTask"
+ "mutant-no-guard-no-peer-close: ClosedConversationGainsNoTask"
+ "mutant-no-end-state: CompletedTaskWasNotAFailedTurn"
+ "mutant-no-reopen: StepTurnRefusedOnlyAfterOthersClose ReplyEndsItsOwnTask"
+ "mutant-reopen-keeps-left-tasks: ReplyEndsItsOwnTask"
+ "mutant-no-first-turn-failure: StepThatSentNothingFails"
+ "known-gap-late-peer-record: ReplyEndsItsOwnTask"
+)
+
+sha256() { if command -v sha256sum >/dev/null; then sha256sum "$1"; else shasum -a 256 "$1"; fi | cut -d' ' -f1; }
+
+jar=${TLA2TOOLS:-}
+if [[ -z $jar ]]; then
+ cache=${XDG_CACHE_HOME:-$HOME/.cache}/agentenv-formal
+ jar=$cache/tla2tools-$TLA_VERSION.jar
+ if [[ ! -f $jar || $(sha256 "$jar") != "$TLA_SHA256" ]]; then
+ mkdir -p "$cache"
+ part=$(mktemp "$cache/tla2tools.XXXXXX")
+ curl -fsSL -o "$part" "$TLA_URL" || { rm -f "$part"; exit 2; }
+ [[ $(sha256 "$part") == "$TLA_SHA256" ]] || { rm -f "$part"; echo "tla2tools.jar sha256 mismatch" >&2; exit 2; }
+ mv -f "$part" "$jar"
+ fi
+elif [[ $(sha256 "$jar") != "$TLA_SHA256" ]]; then
+ echo "TLA2TOOLS=$jar is not tla2tools.jar v$TLA_VERSION (sha256 $TLA_SHA256)" >&2
+ exit 2
+fi
+jar=$(cd "$(dirname "$jar")" && pwd)/$(basename "$jar")
+
+status=0
+for line in "${EXPECTED[@]}"; do
+ config=${line%%:*}
+ breaks=" ${line#*:} "
+ for rule in "${RULES[@]}"; do
+ dir=$out/$config-$rule
+ mkdir -p "$dir"
+ cp "$here/ConversationLifecycle.tla" "$dir/"
+ sed -e '/^INVARIANTS/,$d' "$here/$config.cfg" > "$dir/run.cfg"
+ printf 'INVARIANT %s\n' "$rule" >> "$dir/run.cfg"
+ (cd "$dir" && "$java" -XX:+UseParallelGC -cp "$jar" tlc2.TLC -workers 1 -metadir meta -config run.cfg \
+ ConversationLifecycle.tla > tlc.out 2>&1) || true
+ if grep -q "Invariant $rule is violated" "$dir/tlc.out"; then got=breaks
+ elif grep -q 'Model checking completed. No error has been found.' "$dir/tlc.out"; then got=holds
+ else got=error; fi
+ [[ $breaks == *" $rule "* ]] && want=breaks || want=holds
+ states=$(grep -Eo '[0-9,]+ distinct states found' "$dir/tlc.out" | tail -1 || true)
+ if [[ $got == "$want" ]]; then mark=ok; else mark=UNEXPECTED; status=1; fi
+ printf '%-11s %-30s %-36s %-7s %s\n' "$mark" "$config" "$rule" "$got" "$states"
+ done
+done
+echo "TLC $TLA_VERSION; specs, configs and tlc.out in $out"
+exit $status
diff --git a/tst/formal/a2a_conversation/fixed.cfg b/tst/formal/a2a_conversation/fixed.cfg
new file mode 100644
index 000000000..eb05a4edd
--- /dev/null
+++ b/tst/formal/a2a_conversation/fixed.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 1
+ Kills = 1
+ LatePeerRecord = FALSE
+ CloseOnAnyEnd = TRUE
+ RefuseAddWhenClosed = TRUE
+ RecordEndState = TRUE
+ ReopenOnReuse = TRUE
+ ReopenCancelsLeftTasks = TRUE
+ CloseBeforeLiveEnd = TRUE
+ FailOnFirstTurnRefused = TRUE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/formal/a2a_conversation/known-gap-late-peer-record.cfg b/tst/formal/a2a_conversation/known-gap-late-peer-record.cfg
new file mode 100644
index 000000000..bf9dc3f2a
--- /dev/null
+++ b/tst/formal/a2a_conversation/known-gap-late-peer-record.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 1
+ Kills = 1
+ LatePeerRecord = TRUE
+ CloseOnAnyEnd = TRUE
+ RefuseAddWhenClosed = TRUE
+ RecordEndState = TRUE
+ ReopenOnReuse = TRUE
+ ReopenCancelsLeftTasks = TRUE
+ CloseBeforeLiveEnd = TRUE
+ FailOnFirstTurnRefused = TRUE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/formal/a2a_conversation/mutant-close-after-live-end.cfg b/tst/formal/a2a_conversation/mutant-close-after-live-end.cfg
new file mode 100644
index 000000000..f47de7076
--- /dev/null
+++ b/tst/formal/a2a_conversation/mutant-close-after-live-end.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 1
+ Kills = 1
+ LatePeerRecord = FALSE
+ CloseOnAnyEnd = TRUE
+ RefuseAddWhenClosed = TRUE
+ RecordEndState = TRUE
+ ReopenOnReuse = TRUE
+ ReopenCancelsLeftTasks = TRUE
+ CloseBeforeLiveEnd = FALSE
+ FailOnFirstTurnRefused = TRUE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/formal/a2a_conversation/mutant-no-end-state.cfg b/tst/formal/a2a_conversation/mutant-no-end-state.cfg
new file mode 100644
index 000000000..e2de2011a
--- /dev/null
+++ b/tst/formal/a2a_conversation/mutant-no-end-state.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 1
+ Kills = 1
+ LatePeerRecord = FALSE
+ CloseOnAnyEnd = TRUE
+ RefuseAddWhenClosed = TRUE
+ RecordEndState = FALSE
+ ReopenOnReuse = TRUE
+ ReopenCancelsLeftTasks = TRUE
+ CloseBeforeLiveEnd = TRUE
+ FailOnFirstTurnRefused = TRUE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/formal/a2a_conversation/mutant-no-finally.cfg b/tst/formal/a2a_conversation/mutant-no-finally.cfg
new file mode 100644
index 000000000..d84af95e5
--- /dev/null
+++ b/tst/formal/a2a_conversation/mutant-no-finally.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 1
+ Kills = 1
+ LatePeerRecord = FALSE
+ CloseOnAnyEnd = FALSE
+ RefuseAddWhenClosed = TRUE
+ RecordEndState = TRUE
+ ReopenOnReuse = TRUE
+ ReopenCancelsLeftTasks = TRUE
+ CloseBeforeLiveEnd = TRUE
+ FailOnFirstTurnRefused = TRUE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/formal/a2a_conversation/mutant-no-first-turn-failure.cfg b/tst/formal/a2a_conversation/mutant-no-first-turn-failure.cfg
new file mode 100644
index 000000000..3a7c549b4
--- /dev/null
+++ b/tst/formal/a2a_conversation/mutant-no-first-turn-failure.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 1
+ Kills = 1
+ LatePeerRecord = FALSE
+ CloseOnAnyEnd = TRUE
+ RefuseAddWhenClosed = TRUE
+ RecordEndState = TRUE
+ ReopenOnReuse = TRUE
+ ReopenCancelsLeftTasks = TRUE
+ CloseBeforeLiveEnd = TRUE
+ FailOnFirstTurnRefused = FALSE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/formal/a2a_conversation/mutant-no-guard-no-peer-close.cfg b/tst/formal/a2a_conversation/mutant-no-guard-no-peer-close.cfg
new file mode 100644
index 000000000..77317ced1
--- /dev/null
+++ b/tst/formal/a2a_conversation/mutant-no-guard-no-peer-close.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 0
+ Kills = 1
+ LatePeerRecord = FALSE
+ CloseOnAnyEnd = TRUE
+ RefuseAddWhenClosed = FALSE
+ RecordEndState = TRUE
+ ReopenOnReuse = TRUE
+ ReopenCancelsLeftTasks = TRUE
+ CloseBeforeLiveEnd = TRUE
+ FailOnFirstTurnRefused = TRUE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/formal/a2a_conversation/mutant-no-guard.cfg b/tst/formal/a2a_conversation/mutant-no-guard.cfg
new file mode 100644
index 000000000..076733f03
--- /dev/null
+++ b/tst/formal/a2a_conversation/mutant-no-guard.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 1
+ Kills = 1
+ LatePeerRecord = FALSE
+ CloseOnAnyEnd = TRUE
+ RefuseAddWhenClosed = FALSE
+ RecordEndState = TRUE
+ ReopenOnReuse = TRUE
+ ReopenCancelsLeftTasks = TRUE
+ CloseBeforeLiveEnd = TRUE
+ FailOnFirstTurnRefused = TRUE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/formal/a2a_conversation/mutant-no-reopen.cfg b/tst/formal/a2a_conversation/mutant-no-reopen.cfg
new file mode 100644
index 000000000..06266eeba
--- /dev/null
+++ b/tst/formal/a2a_conversation/mutant-no-reopen.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 1
+ Kills = 1
+ LatePeerRecord = FALSE
+ CloseOnAnyEnd = TRUE
+ RefuseAddWhenClosed = TRUE
+ RecordEndState = TRUE
+ ReopenOnReuse = FALSE
+ ReopenCancelsLeftTasks = TRUE
+ CloseBeforeLiveEnd = TRUE
+ FailOnFirstTurnRefused = TRUE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/formal/a2a_conversation/mutant-reopen-keeps-left-tasks.cfg b/tst/formal/a2a_conversation/mutant-reopen-keeps-left-tasks.cfg
new file mode 100644
index 000000000..cfd9b0b50
--- /dev/null
+++ b/tst/formal/a2a_conversation/mutant-reopen-keeps-left-tasks.cfg
@@ -0,0 +1,21 @@
+SPECIFICATION Spec
+CONSTANTS
+ Attempts = 2
+ MaxTurns = 2
+ PeerMayClose = 1
+ Kills = 1
+ LatePeerRecord = FALSE
+ CloseOnAnyEnd = TRUE
+ RefuseAddWhenClosed = TRUE
+ RecordEndState = TRUE
+ ReopenOnReuse = TRUE
+ ReopenCancelsLeftTasks = FALSE
+ CloseBeforeLiveEnd = TRUE
+ FailOnFirstTurnRefused = TRUE
+INVARIANTS
+ EndedStepLeavesConversationClosed
+ ClosedConversationGainsNoTask
+ CompletedTaskWasNotAFailedTurn
+ StepTurnRefusedOnlyAfterOthersClose
+ ReplyEndsItsOwnTask
+ StepThatSentNothingFails
diff --git a/tst/unit/a2a_agent/conversation_store_test.py b/tst/unit/a2a_agent/conversation_store_test.py
new file mode 100644
index 000000000..72968885a
--- /dev/null
+++ b/tst/unit/a2a_agent/conversation_store_test.py
@@ -0,0 +1,40 @@
+"""The step that owns a conversation, and closing what an earlier run of that step left active."""
+
+import uuid
+
+from a2a.types import TaskState
+
+from agent_env.a2a_agent import conversation_store as cs
+
+
+def _new(instance: str, step_id: str | None = None) -> str:
+ conversation_id = uuid.uuid4().hex
+ cs.create_conversation(conversation_id, instance, "user", "solver", step_id=step_id)
+ return conversation_id
+
+
+def _status(conversation_id: str) -> str:
+ return cs.get_conversation(conversation_id)["status"]
+
+
+def test_a_conversation_records_its_step_only_when_given_one(local_stores):
+ with_step, without = _new("ti", step_id="solve"), _new("ti")
+
+ assert cs.get_conversation(with_step)["step_id"] == "solve"
+ assert "step_id" not in cs.get_conversation(without)
+
+
+def test_closing_a_steps_leftovers_closes_only_its_active_conversations(local_stores):
+ leftover = _new("ti", step_id="solve")
+ cs.add_a2a_task(leftover, [{"kind": "text", "text": "hi"}], "turn", "user")
+ already_closed = _new("ti", step_id="solve")
+ cs.mark_closed(already_closed)
+ other_step, other_instance, unowned = _new("ti", step_id="other"), _new("ti-2", step_id="solve"), _new("ti")
+
+ assert cs.close_active_for_step("ti", "solve") == [leftover]
+
+ closed = cs.get_conversation(leftover)
+ assert closed["status"] == "closed"
+ assert closed["a2a_tasks"][0]["state"] == TaskState.canceled.value
+ assert [_status(c) for c in (other_step, other_instance, unowned)] == ["active"] * 3
+ assert cs.close_active_for_step("ti", "solve") == []
diff --git a/tst/unit/task_step/prompt_agent_file_parts_test.py b/tst/unit/task_step/prompt_agent_file_parts_test.py
index cb1d196cb..cdccc9da9 100644
--- a/tst/unit/task_step/prompt_agent_file_parts_test.py
+++ b/tst/unit/task_step/prompt_agent_file_parts_test.py
@@ -29,8 +29,8 @@ def store(tmp_path):
def recorded(monkeypatch):
"""The parts the run records of each turn."""
turns = []
- monkeypatch.setattr(pa.conversation_store, "add_a2a_task", lambda *a, parts, **kw: turns.append(parts))
- for fn in ("create_conversation", "complete_a2a_task", "mark_closed", "get_conversation"):
+ monkeypatch.setattr(pa.conversation_store, "add_a2a_task", lambda *a, parts, **kw: turns.append(parts) or {})
+ for fn in ("reopen", "create_conversation", "complete_a2a_task", "mark_closed", "get_conversation"):
monkeypatch.setattr(pa.conversation_store, fn, lambda *a, **kw: None)
return turns
diff --git a/tst/unit/task_step/prompt_agent_rig.py b/tst/unit/task_step/prompt_agent_rig.py
index 1d3602583..7134d93db 100644
--- a/tst/unit/task_step/prompt_agent_rig.py
+++ b/tst/unit/task_step/prompt_agent_rig.py
@@ -12,14 +12,14 @@
from agent_env.task_step.task_steps import prompt_agent as pa
#: The conversation store calls a prompt step makes, which these tests keep from reaching a store.
-CONVERSATION_STORE_CALLS = ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed",
- "get_conversation")
+CONVERSATION_STORE_CALLS = ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed",
+ "get_conversation", "close_active_for_step")
AGENT_URL = "http://agent.test"
def quiet_conversations(monkeypatch: pytest.MonkeyPatch) -> None:
for name in CONVERSATION_STORE_CALLS:
- monkeypatch.setattr(pa.conversation_store, name, lambda *args, **kwargs: None)
+ monkeypatch.setattr(pa.conversation_store, name, lambda *args, **kwargs: {})
def route_clients(monkeypatch: pytest.MonkeyPatch, transport: httpx.AsyncBaseTransport, **options: Any) -> None:
diff --git a/tst/unit/task_step/test_prompt_agent.py b/tst/unit/task_step/test_prompt_agent.py
index a03948399..3e6928eaf 100644
--- a/tst/unit/task_step/test_prompt_agent.py
+++ b/tst/unit/task_step/test_prompt_agent.py
@@ -246,9 +246,9 @@ async def _one_turn(monkeypatch, tmp_path, extension: dict, answer: Callable[[di
sent and the store it wrote to."""
store = LocalFilesystemObjectStore(str(tmp_path))
configure(object_store=store)
- for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task",
+ for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task",
"mark_closed", "get_conversation"):
- monkeypatch.setattr(pa.conversation_store, fn, lambda *a, **kw: None)
+ monkeypatch.setattr(pa.conversation_store, fn, lambda *a, **kw: {})
requests: list[dict] = []
def trajectory(request: httpx.Request) -> httpx.Response:
diff --git a/tst/unit/task_step/test_prompt_agent_builtin_tools.py b/tst/unit/task_step/test_prompt_agent_builtin_tools.py
index f441bb811..3dcefe492 100644
--- a/tst/unit/task_step/test_prompt_agent_builtin_tools.py
+++ b/tst/unit/task_step/test_prompt_agent_builtin_tools.py
@@ -22,8 +22,8 @@ def posted(monkeypatch):
cfg.get_model_params.return_value = {}
cfg.get_model_for_role.return_value = None
monkeypatch.setattr(pa_mod, "get_config", lambda: cfg)
- for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
- monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None)
+ for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
+ monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {})
configs = []
async def post_agent_config(url, fields, headers=None):
diff --git a/tst/unit/task_step/test_prompt_agent_conversation_close.py b/tst/unit/task_step/test_prompt_agent_conversation_close.py
new file mode 100644
index 000000000..527ea5dc8
--- /dev/null
+++ b/tst/unit/task_step/test_prompt_agent_conversation_close.py
@@ -0,0 +1,276 @@
+"""A prompt step's A2A conversation record: however the step ends, it is closed and off the pending worklist; a closed
+conversation takes no new turn; and each turn records how the agent's reply ended."""
+
+import asyncio
+from contextlib import nullcontext
+from unittest.mock import MagicMock
+
+import pytest
+from a2a.types import TaskState
+
+from agent_env.a2a_agent import conversation_store
+from agent_env.task_step.context import DeployedAgent, TaskStepContext
+from agent_env.task_step.task_steps import prompt_agent as pa_mod
+from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep
+
+HUMAN_URL = "http://human-peer"
+
+
+def _reply(state, text):
+ return {"status": {"state": state, "message": {"parts": [{"kind": "text", "text": text}]}}}
+
+
+@pytest.fixture
+def sent(monkeypatch, local_stores):
+ """Every message the step sends, as (url, text); the store is the real local one."""
+ cfg = MagicMock()
+ cfg.get_model_params.return_value = {}
+ cfg.get_default_human_a2a_url.return_value = HUMAN_URL
+ monkeypatch.setattr(pa_mod, "get_config", lambda: cfg)
+ messages = []
+
+ async def send(url, parts, message_id, context_id, timeout):
+ messages.append((url, parts[0].get("text")))
+ return f"{url}#{len(messages)}", None
+
+ monkeypatch.setattr(pa_mod.protocol, "send_a2a_message", send)
+ return messages
+
+
+def _poll(monkeypatch, poll):
+ monkeypatch.setattr(pa_mod.protocol, "poll_a2a_task", poll)
+
+
+def _context():
+ ctx = TaskStepContext(instance_id="ti-1")
+ ctx.deployed_agents.append(
+ DeployedAgent(agent_name="solver", api_url="http://solver", a2a_url="http://solver", a2a_card={})
+ )
+ return ctx
+
+
+def _conversation(ctx):
+ return conversation_store.get_conversation(ctx.metadata["a2a_conversations"]["solve"])
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("error", [TimeoutError, pytest.param(RuntimeError, id="any-exception")])
+async def test_a_step_that_raises_mid_turn_leaves_its_conversation_closed_and_off_the_worklist(
+ monkeypatch, sent, error):
+ async def poll(url, task_id, timeout, interval, **_):
+ raise error("the agent's turn did not end")
+
+ _poll(monkeypatch, poll)
+ ctx = _context()
+
+ with pytest.raises(error):
+ await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(ctx)
+
+ conversation = _conversation(ctx)
+ assert (conversation["status"], conversation["pending"]) == ("closed", False)
+ assert [t["state"] for t in conversation["a2a_tasks"]] == [TaskState.canceled.value]
+ assert conversation_store.list_pending() == []
+
+
+@pytest.mark.asyncio
+async def test_a_failed_agent_turn_is_recorded_failed_not_completed(monkeypatch, sent):
+ async def poll(url, task_id, timeout, interval, **_):
+ return _reply(TaskState.failed, "it broke")
+
+ _poll(monkeypatch, poll)
+ ctx = _context()
+
+ try:
+ await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(ctx)
+ except Exception:
+ pass # whether a failed turn fails the step is not this test's concern
+
+ assert [t["state"] for t in _conversation(ctx)["a2a_tasks"]] == [TaskState.failed.value]
+
+
+@pytest.mark.asyncio
+async def test_a_conversation_the_human_closes_while_answering_takes_no_further_turn(monkeypatch, sent):
+ ctx = _context()
+
+ async def poll(url, task_id, timeout, interval, **_):
+ if url == HUMAN_URL:
+ conversation_store.mark_closed(ctx.metadata["a2a_conversations"]["solve"])
+ return _reply(TaskState.completed, "one more thing")
+ return _reply(TaskState.completed, "answer")
+
+ _poll(monkeypatch, poll)
+
+ await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver",
+ max_conversation_turns=2).execute(ctx)
+
+ conversation = _conversation(ctx)
+ assert [t["state"] for t in conversation["a2a_tasks"]] == [TaskState.completed.value]
+ assert conversation["pending"] is False
+ assert sent == [("http://solver", "hi"), (HUMAN_URL, "answer")]
+
+
+def test_a_closed_conversation_refuses_a_new_a2a_task(local_stores):
+ conversation_store.create_conversation("conv-1", "ti-1", "human_agent", "solver")
+ conversation_store.mark_closed("conv-1")
+
+ refused = conversation_store.add_a2a_task("conv-1", [{"kind": "text", "text": "late"}], "late-task", "agent")
+
+ conversation = conversation_store.get_conversation("conv-1")
+ assert refused is None
+ assert (conversation["a2a_tasks"], conversation["messages"], conversation["pending"]) == ([], [], False)
+
+
+@pytest.mark.asyncio
+async def test_a_retried_step_gets_its_own_replies_on_its_own_turns(monkeypatch, sent):
+ attempts = iter(["times out", "answers"])
+ attempt = None
+
+ async def poll(url, task_id, timeout, interval, **_):
+ if attempt == "times out":
+ raise TimeoutError("the agent's turn did not end")
+ if url == HUMAN_URL:
+ return _reply(TaskState.completed, "and then?")
+ return _reply(TaskState.completed, "answer")
+
+ _poll(monkeypatch, poll)
+ ctx = _context()
+ step = PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver", context_id="session",
+ max_conversation_turns=2)
+
+ attempt = next(attempts)
+ with pytest.raises(TimeoutError):
+ await step.execute(ctx)
+ attempt = next(attempts)
+ await step.execute(ctx)
+
+ conversation = _conversation(ctx)
+ assert [t["state"] for t in conversation["a2a_tasks"]] == [
+ TaskState.canceled.value, TaskState.completed.value, TaskState.completed.value,
+ ]
+ assert conversation["status"] == "closed"
+ assert [url for url, _ in sent] == ["http://solver", "http://solver", HUMAN_URL, "http://solver"]
+
+
+@pytest.mark.asyncio
+async def test_a_conversation_closed_before_the_first_turn_fails_the_step_and_sends_nothing(monkeypatch, sent):
+ async def poll(url, task_id, timeout, interval, **_):
+ return _reply(TaskState.completed, "answer")
+
+ _poll(monkeypatch, poll)
+ create = conversation_store.create_conversation
+
+ def created_then_closed_by_the_peer(conversation_id, **fields):
+ doc = create(conversation_id=conversation_id, **fields)
+ conversation_store.mark_closed(conversation_id)
+ return doc
+
+ monkeypatch.setattr(conversation_store, "create_conversation", created_then_closed_by_the_peer)
+ ctx = _context()
+
+ with pytest.raises(RuntimeError, match="closed before the first turn"):
+ await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(ctx)
+
+ assert sent == []
+ assert _conversation(ctx)["a2a_tasks"] == []
+
+
+@pytest.mark.asyncio
+async def test_a_retry_after_a_killed_run_cancels_the_task_it_left_and_completes_its_own(monkeypatch, sent):
+ attempt = "killed"
+
+ async def poll(url, task_id, timeout, interval, **_):
+ if attempt == "killed":
+ raise TimeoutError("the process died mid-turn")
+ return _reply(TaskState.completed, "answer")
+
+ _poll(monkeypatch, poll)
+ ctx = _context()
+ step = PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver", context_id="session")
+
+ with monkeypatch.context() as killed_before_its_close:
+ killed_before_its_close.setattr(conversation_store, "mark_closed", lambda conversation_id: None)
+ with pytest.raises(TimeoutError):
+ await step.execute(ctx)
+ assert [t["state"] for t in _conversation(ctx)["a2a_tasks"]] == [TaskState.working.value]
+ attempt = "retried"
+ await step.execute(ctx)
+
+ conversation = _conversation(ctx)
+ left, own = conversation["a2a_tasks"]
+ assert (left["state"], left.get("response_message_idx")) == (TaskState.canceled.value, None)
+ assert own["state"] == TaskState.completed.value
+ assert conversation["messages"][own["response_message_idx"]]["parts"] == [{"kind": "text", "text": "answer"}]
+ assert conversation["status"] == "closed"
+
+
+@pytest.mark.asyncio
+async def test_two_runs_racing_to_create_the_conversation_share_one_record(monkeypatch, sent):
+ async def poll(url, task_id, timeout, interval, **_):
+ return _reply(TaskState.completed, "answer")
+
+ _poll(monkeypatch, poll)
+ conversation_store.ensure_indexes()
+ create = conversation_store.create_conversation
+
+ def the_other_run_creates_it_first(**fields):
+ create(**fields)
+ return create(**fields)
+
+ monkeypatch.setattr(conversation_store, "create_conversation", the_other_run_creates_it_first)
+ ctx = _context()
+
+ await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(ctx)
+
+ conversation = _conversation(ctx)
+ assert [t["state"] for t in conversation["a2a_tasks"]] == [TaskState.completed.value]
+ assert conversation["status"] == "closed"
+
+
+@pytest.mark.asyncio
+async def test_a_close_that_fails_does_not_hide_why_the_step_failed(monkeypatch, sent):
+ async def poll(url, task_id, timeout, interval, **_):
+ raise TimeoutError("the agent's turn did not end")
+
+ def store_unreachable(conversation_id):
+ raise ConnectionError("the store is down")
+
+ _poll(monkeypatch, poll)
+ monkeypatch.setattr(conversation_store, "mark_closed", store_unreachable)
+
+ with pytest.raises(TimeoutError):
+ await PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(_context())
+
+
+@pytest.mark.asyncio
+async def test_a_step_cancelled_while_ending_its_live_trajectory_leaves_its_conversation_closed(monkeypatch, sent):
+ async def poll(url, task_id, timeout, interval, **_):
+ return _reply(TaskState.completed, "answer")
+
+ ending = asyncio.Event()
+
+ class SlowToEndLiveTurns:
+ def __init__(self, *args, **kwargs):
+ pass
+
+ def following(self, turn_id):
+ return nullcontext(None)
+
+ async def end(self):
+ ending.set()
+ await asyncio.Event().wait()
+
+ _poll(monkeypatch, poll)
+ monkeypatch.setattr(PromptAgentTaskStep, "_live_trajectory_target", lambda self, *args: ("live", None, "prefix/"))
+ monkeypatch.setattr(pa_mod, "LiveTurns", SlowToEndLiveTurns)
+ ctx = _context()
+
+ step = asyncio.create_task(
+ PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver").execute(ctx))
+ await asyncio.wait_for(ending.wait(), timeout=5)
+ step.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await step
+
+ conversation = _conversation(ctx)
+ assert (conversation["status"], conversation["pending"]) == ("closed", False)
+ assert conversation_store.list_pending() == []
diff --git a/tst/unit/task_step/test_prompt_agent_conversation_tool_calls.py b/tst/unit/task_step/test_prompt_agent_conversation_tool_calls.py
index 2e42a5fb5..07101dc81 100644
--- a/tst/unit/task_step/test_prompt_agent_conversation_tool_calls.py
+++ b/tst/unit/task_step/test_prompt_agent_conversation_tool_calls.py
@@ -21,8 +21,8 @@ def _wire(monkeypatch, solver_tool_calls: list):
cfg.get_model_params.return_value = {}
cfg.get_default_human_a2a_url.return_value = "http://hub/a2a/human"
monkeypatch.setattr(pa_mod, "get_config", lambda: cfg)
- for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
- monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None)
+ for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
+ monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {})
solver_turns = iter(solver_tool_calls)
async def post_agent_config(url, fields, headers=None):
diff --git a/tst/unit/task_step/test_prompt_agent_human_default.py b/tst/unit/task_step/test_prompt_agent_human_default.py
index a31b10721..8bc66d741 100644
--- a/tst/unit/task_step/test_prompt_agent_human_default.py
+++ b/tst/unit/task_step/test_prompt_agent_human_default.py
@@ -13,9 +13,9 @@
def _wire(monkeypatch, cfg):
monkeypatch.setattr(pa_mod, "get_config", lambda: cfg)
- for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task",
+ for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task",
"mark_closed", "get_conversation"):
- monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None)
+ monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {})
async def send(url, parts, message_id, context_id, timeout):
return "task-1", None
diff --git a/tst/unit/task_step/test_prompt_agent_leaked_conversations.py b/tst/unit/task_step/test_prompt_agent_leaked_conversations.py
new file mode 100644
index 000000000..fe9b6368b
--- /dev/null
+++ b/tst/unit/task_step/test_prompt_agent_leaked_conversations.py
@@ -0,0 +1,111 @@
+"""A re-run of a prompt step closes the conversations an earlier run of it left active, as one whose worker died does,
+unless the step shares its conversation through `context_id`."""
+
+import pytest
+from a2a.types import TaskState
+
+from agent_env.a2a_agent import conversation_store as cs
+from agent_env.store import Filter, get_config
+from agent_env.task_step.context import DeployedAgent, TaskStepContext
+from agent_env.task_step.task_steps import prompt_agent as pa
+from agent_env.task_step.task_steps.prompt_agent import PromptAgentTaskStep
+
+INSTANCE = "ti-1"
+
+
+@pytest.fixture(autouse=True)
+def conversation_indexes(local_stores):
+ """As deployed: the unique conversation id is what makes a shared conversation's re-run reuse it."""
+ cs.ensure_indexes()
+
+
+def _wire(monkeypatch, replies: list) -> None:
+ """The solver's n-th poll returns a completed reply, or raises when ``replies[n]`` is an exception."""
+ turns = iter(replies)
+
+ async def send(url, parts, message_id, context_id, timeout):
+ return f"task-{message_id}", None
+
+ async def poll(url, task_id, timeout, interval, **_):
+ reply = next(turns)
+ if isinstance(reply, BaseException):
+ raise reply
+ return {"status": {"state": TaskState.completed, "message": {"parts": [{"kind": "text", "text": reply}]}}}
+
+ monkeypatch.setattr(pa.protocol, "send_a2a_message", send)
+ monkeypatch.setattr(pa.protocol, "poll_a2a_task", poll)
+
+
+def _context() -> TaskStepContext:
+ ctx = TaskStepContext(instance_id=INSTANCE)
+ ctx.deployed_agents.append(DeployedAgent(agent_name="solver", api_url="http://solver", a2a_url="http://solver",
+ a2a_card={}))
+ return ctx
+
+
+def _step(**kwargs) -> PromptAgentTaskStep:
+ return PromptAgentTaskStep(id="solve", version=None, prompt="hi", agent_name="solver", **kwargs)
+
+
+def _conversations() -> list[dict]:
+ docs = get_config().get_document_store().query(cs._COLLECTION_NAME, Filter.of(task_instance_id=INSTANCE))
+ return sorted(docs, key=lambda d: d["created_at_utc"])
+
+
+async def _dies(monkeypatch, step: PromptAgentTaskStep) -> None:
+ """A run whose worker dies mid-step: nothing it would run on the way out closes its conversation."""
+ with monkeypatch.context() as dying:
+ dying.setattr(pa.conversation_store, "mark_closed", lambda conversation_id: None)
+ with pytest.raises(RuntimeError):
+ await step.execute(_context())
+
+
+@pytest.mark.asyncio
+async def test_a_rerun_closes_the_conversation_a_dead_run_left_active(local_stores, monkeypatch):
+ _wire(monkeypatch, [RuntimeError("worker died"), "done"])
+ await _dies(monkeypatch, _step())
+ [left] = _conversations()
+ assert left["status"] == "active"
+ assert left["step_id"] == "solve"
+
+ ctx = await _step().execute(_context())
+
+ earlier, rerun = _conversations()
+ assert earlier["conversation_id"] == left["conversation_id"]
+ assert earlier["status"] == "closed"
+ assert earlier["a2a_tasks"][0]["state"] == TaskState.canceled.value
+ assert rerun["conversation_id"] == ctx.metadata["a2a_conversations"]["solve"] != earlier["conversation_id"]
+ assert rerun["status"] == "closed"
+ assert ctx.prompt_responses[-1].response == "done"
+
+
+@pytest.mark.asyncio
+async def test_a_rerun_that_fails_before_its_own_conversation_still_closes_the_one_left_active(local_stores,
+ monkeypatch):
+ _wire(monkeypatch, [RuntimeError("worker died")])
+ await _dies(monkeypatch, _step())
+
+ async def agent_unreachable(*args, **kwargs):
+ raise ConnectionError("agent unreachable")
+
+ monkeypatch.setattr(pa, "prescribe_formats", agent_unreachable)
+ with pytest.raises(ConnectionError):
+ await _step().execute(_context())
+
+ [left] = _conversations()
+ assert left["status"] == "closed"
+
+
+@pytest.mark.asyncio
+async def test_a_shared_conversation_is_not_swept_but_taken_back(local_stores, monkeypatch):
+ _wire(monkeypatch, [RuntimeError("worker died"), "done"])
+ await _dies(monkeypatch, _step(context_id="shared"))
+ [shared] = _conversations()
+ assert shared["status"] == "active"
+ assert "step_id" not in shared
+
+ ctx = await _step(context_id="shared").execute(_context())
+
+ [reused] = _conversations()
+ assert reused["conversation_id"] == shared["conversation_id"] == ctx.metadata["a2a_conversations"]["solve"]
+ assert reused["status"] == "closed"
diff --git a/tst/unit/task_step/test_prompt_agent_max_output_tokens.py b/tst/unit/task_step/test_prompt_agent_max_output_tokens.py
index 543a3ff29..ae2510800 100644
--- a/tst/unit/task_step/test_prompt_agent_max_output_tokens.py
+++ b/tst/unit/task_step/test_prompt_agent_max_output_tokens.py
@@ -19,8 +19,8 @@ def posted(monkeypatch):
cfg.get_model_params.return_value = {}
cfg.get_model_for_role.return_value = None
monkeypatch.setattr(pa_mod, "get_config", lambda: cfg)
- for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
- monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None)
+ for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
+ monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {})
configs = []
async def post_agent_config(url, fields, headers=None):
diff --git a/tst/unit/task_step/test_prompt_agent_snapshots.py b/tst/unit/task_step/test_prompt_agent_snapshots.py
index e05c8becf..e17d35efb 100644
--- a/tst/unit/task_step/test_prompt_agent_snapshots.py
+++ b/tst/unit/task_step/test_prompt_agent_snapshots.py
@@ -1259,7 +1259,7 @@ def __init__(self, monkeypatch, *, user_done_at: int | None = None):
self.user_done_at = user_done_at
self.user_turns = 0
- for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task",
+ for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task",
"mark_closed"):
# `*a` too: the loop calls some of these positionally.
monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {})
diff --git a/tst/unit/task_step/test_prompt_agent_unreachable.py b/tst/unit/task_step/test_prompt_agent_unreachable.py
index 52306fcd7..c62e14693 100644
--- a/tst/unit/task_step/test_prompt_agent_unreachable.py
+++ b/tst/unit/task_step/test_prompt_agent_unreachable.py
@@ -24,8 +24,8 @@ def _wire(monkeypatch, poll):
cfg.get_model_params.return_value = {}
cfg.get_default_human_a2a_url.return_value = "http://hub/a2a/human"
monkeypatch.setattr(pa_mod, "get_config", lambda: cfg)
- for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
- monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None)
+ for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
+ monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {})
async def send(url, parts, message_id, context_id, timeout):
return f"{url}#task", None
diff --git a/tst/unit/task_step/test_prompt_agent_usage.py b/tst/unit/task_step/test_prompt_agent_usage.py
index fbda82701..514a54363 100644
--- a/tst/unit/task_step/test_prompt_agent_usage.py
+++ b/tst/unit/task_step/test_prompt_agent_usage.py
@@ -28,8 +28,8 @@ def _wire(monkeypatch, solver_usage: list, user_usage=None):
cfg = MagicMock()
cfg.get_model_params.return_value = {}
monkeypatch.setattr(pa_mod, "get_config", lambda: cfg)
- for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
- monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None)
+ for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
+ monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {})
solver_turns = iter(solver_usage)
async def post_agent_config(url, fields, headers=None):
diff --git a/tst/unit/task_step/test_prompt_agent_user_side.py b/tst/unit/task_step/test_prompt_agent_user_side.py
index 4cd596fba..85e8c1426 100644
--- a/tst/unit/task_step/test_prompt_agent_user_side.py
+++ b/tst/unit/task_step/test_prompt_agent_user_side.py
@@ -366,7 +366,7 @@ async def test_an_agent_failure_ends_the_run_without_asking_the_user_and_fails_t
"status": "closed",
"messages": [{"role": "user", "parts": text("plan my week")}, {"role": "agent", "parts": text("one")},
{"role": "user", "parts": text("again")}, {"role": "agent", "parts": text("boom")}],
- "a2a_tasks": [("", "completed", 0, 1), ("", "completed", 2, 3)],
+ "a2a_tasks": [("", "completed", 0, 1), ("", "failed", 2, 3)],
}
diff --git a/tst/unit/task_step/test_recorded_models.py b/tst/unit/task_step/test_recorded_models.py
index ddb0db813..afadb5787 100644
--- a/tst/unit/task_step/test_recorded_models.py
+++ b/tst/unit/task_step/test_recorded_models.py
@@ -31,8 +31,8 @@ def posted(monkeypatch):
cfg.get_model_params.return_value = {}
cfg.resolve_model.side_effect = lambda role, **layers: resolve_model(role, **layers)
monkeypatch.setattr(pa_mod, "get_config", lambda: cfg)
- for fn in ("create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
- monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: None)
+ for fn in ("reopen", "create_conversation", "add_a2a_task", "complete_a2a_task", "mark_closed", "get_conversation"):
+ monkeypatch.setattr(pa_mod.conversation_store, fn, lambda *a, **kw: {})
configs = {}
async def post_agent_config(url, fields, headers=None):