Skip to content

Self-improving AI Employees for everyone

feat(temporal): a chat turn waits for the owner and runs the allowed call (RFC-0007 AP.4b)

trohitgdfdff73ba409
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.md
index 393a7e51..c5f3ea07 100644
--- a/docs-internal/TEMPORAL_ARCHITECTURE.md
+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md
@@ -814,9 +814,11 @@ keep that release's command identities:
`test_workflow_identity_golden.py` fails when:
- commands change without a reviewed patch entry: one in `patch_entries`
- whose `before` and `after` digests match, with a `reason`, naming either
- the live `patch` marker that guards the change or the `new_types` it
- adds (a new type has no recorded history to break);
+ whose `before` and `after` digests match, with a `reason`, naming the
+ live `patch` marker that guards the change, or the `new_types` it adds
+ (a new type has no recorded history to break), or the generation
+ `flags` (`workflow.GENERATION_FLAGS`) that gate it for new generations
+ only;
- a patched marker vanishes before a release has shipped it as
`deprecate_patch` (RFC-0005 §24.3);
- a handler is renamed or removed;
@@ -856,13 +858,21 @@ unsandboxed like the other framework workflows):
- `approvals.record_outcome` records `sent`, `not_sent` (the node said it did not go) or `unknown` (the activity
broke off, so it may have gone), and leaves the employee an `[update]` note for its next chat turn.
-A held call its agent's turn waits on (`runtime: turn`, RFC-0007 §4.6) waits instead in `ApprovalWorkflow`
-(`services/temporal/approval_workflow.py`, id `approval-<approval id>`, unsandboxed): it reads the row
-(`approvals.read`, which ends it `expired` past its expiry) and, while it is pending, waits for a `nudge` Signal or the
-row's expiry, then reads again, and returns the owner's answer. Every change to such a row nudges it
+In a generation admitted with `approval_wait_version` 1 (a generation flag: frozen at Start through
+`freeze_generation_harness`, kept by `_frozen_routing_from_input`, put on node and agent contexts by MachinaWorkflow and
+carried to tool calls by `_INHERITED_SCOPE_KEYS`), the agent answering a chat run marks its tool calls
+`approval_wait`, and a held one becomes a row its turn waits on (`runtime: turn`, RFC-0007 §4.6). AgentWorkflow ends
+the call's admitted action and waits in `ApprovalWorkflow` (`services/temporal/approval_workflow.py`, id
+`approval-<approval id>`, unsandboxed, TERMINATE with its parent): it reads the row (`approvals.read`, which ends it
+`expired` past its expiry) and, while it is pending, waits for a `nudge` Signal or the row's expiry, then reads again,
+and returns the owner's answer. Allowed, the turn waits for Resume, then claims, runs and records the call itself with
+`run_approved_call` (the helper `ApprovedToolCallWorkflow` uses too), under the tool's own activity with one attempt
+and ids `approval-claim-<id>`, `approval-send-<id>` and `approval-record-<id>`; the model reads the call's real result.
+Declined, expired or cancelled, it reads why nothing ran. Every change to such a row nudges it
(`services/approvals/waiting.py`, an approval listener), and the chat watchdog's round nudges again a decided row its
wait has not read while the generation runs (`reconcile.renudge_turns`). A cancelled wait ends a pending row
-`cancelled`. It takes no part in generation control, so Stop's tree walk leaves it out
+`cancelled`; a Reset terminates the waits with their turns and cancels the rows they waited on
+(`waiting.cancel_waits`). It takes no part in generation control, so Stop's tree walk leaves it out
(`execution_control.NON_PARTICIPANTS`).
A send that broke off midway outside `ApprovedToolCallWorkflow` leaves a card the same way (`outcome: unknown`, see
diff --git a/server/services/approvals/store.py b/server/services/approvals/store.py
index 3c96ab3c..cbc60936 100644
--- a/server/services/approvals/store.py
+++ b/server/services/approvals/store.py
@@ -216,10 +216,12 @@ async def cancel_open(
generation: Optional[int] = None,
run_ids: Optional[Iterable[str]] = None,
failed: bool = False,
+ runtime: Optional[str] = None,
) -> List[ApprovalRequest]:
"""Cancel a workflow's drafts that still wait (all generations, one, or
- those of some chat runs): waiting, approved but not handed on yet, or
- discarded and restorable; with ``failed``, failed sends as well."""
+ those of some chat runs; only those of one ``runtime``, when given):
+ waiting, approved but not handed on yet, or discarded and restorable;
+ with ``failed``, failed sends as well."""
statuses = ("pending", "approved", "discarded", "failed") if failed else ("pending", "approved", "discarded")
async with database.get_session() as session:
query = select(ApprovalRequest).where(
@@ -228,6 +230,8 @@ async def cancel_open(
)
if generation is not None:
query = query.where(ApprovalRequest.generation == generation)
+ if runtime is not None:
+ query = query.where(ApprovalRequest.runtime == runtime)
if run_ids is not None:
ids = [run_id for run_id in run_ids if run_id]
if not ids:
diff --git a/server/services/approvals/waiting.py b/server/services/approvals/waiting.py
index 72cced4f..93390745 100644
--- a/server/services/approvals/waiting.py
+++ b/server/services/approvals/waiting.py
@@ -75,6 +75,18 @@ async def nudge_on_change(change: ApprovalChange) -> None:
await nudge(change.approval_id, client)
+async def cancel_waits(database: Any, workflow_id: str, generation: int) -> int:
+ """End the open rows a generation's turns wait on: a Reset terminated
+ those turns, and their waits with them (the approval gate's own rows
+ are its node's to end)."""
+ cancelled = await store.cancel_open(database, workflow_id=workflow_id, generation=generation, runtime=TURN)
+ for row in cancelled:
+ await notify_approval_changed(change_of(row, "cancelled"))
+ if cancelled:
+ logger.info("Cancelled the calls a reset turn waited on", workflow_id=workflow_id, count=len(cancelled))
+ return len(cancelled)
+
+
async def mark_read(database: Any, approval_id: str) -> None:
"""The wait took the row's answer, or nothing waits for it any more:
nothing nudges it again."""
@@ -115,4 +127,4 @@ async def read(database: Any, approval_id: str, *, cancel: bool = False) -> Dict
return {"status": row.status, "revision": row.revision, **({"note": row.note} if row.note else {})}
-__all__ = ["TURN", "WORKFLOW_NAME", "engine", "mark_read", "nudge", "nudge_on_change", "read", "wait_workflow_id"]
+__all__ = ["TURN", "WORKFLOW_NAME", "cancel_waits", "engine", "mark_read", "nudge", "nudge_on_change", "read", "wait_workflow_id"]
diff --git a/server/services/coding_agent_runtime.py b/server/services/coding_agent_runtime.py
index 55217e1a..bbd24ce5 100644
--- a/server/services/coding_agent_runtime.py
+++ b/server/services/coding_agent_runtime.py
@@ -3,6 +3,10 @@
Absence of the marker is intentional: histories and generations admitted before
Pi was installed keep the native v1 implementation, including later firings.
This module contains no settings reads or IO and is safe in workflow code.
+
+:func:`freeze_generation_harness` also freezes whether held calls wait for
+the owner (``approval_wait_version``, RFC-0007), a generation flag the same
+way.
"""
from typing import Any, Mapping
@@ -11,6 +15,7 @@ PI_HARNESS_VERSION = 1
PI_PACKAGE_VERSION = "1.1.0"
PI_HARNESS_KEY = "pi_harness_version"
PI_WORKFLOW_NAME = "PiCodingAgentWorkflow"
+APPROVAL_WAIT_KEY = "approval_wait_version"
def uses_pi(node_type: str, context: Mapping[str, Any]) -> bool:
@@ -37,23 +42,28 @@ def freeze_pi_local_control(payload: dict) -> None:
payload["pi_local_control_version"] = 1
+def _freeze(payload: dict, key: str, value: Any) -> None:
+ """Set ``key`` to ``value`` (None: absent) on the payload and its routing."""
+ routing = payload.get("_temporal_routing_v1")
+ routing = dict(routing) if isinstance(routing, dict) else None
+ for target in (payload, routing):
+ if target is None:
+ continue
+ if value is None:
+ target.pop(key, None)
+ else:
+ target[key] = value
+ if routing is not None:
+ payload["_temporal_routing_v1"] = routing
+
+
def freeze_generation_harness(payload: dict, manifest: Mapping[str, Any] | None) -> None:
"""Replace a starter's defaults with the admitted generation's selection."""
version = (manifest or {}).get(PI_HARNESS_KEY)
if version not in {None, PI_HARNESS_VERSION}:
raise ValueError("Unsupported recorded Coding Agent harness version")
- if version == PI_HARNESS_VERSION:
- payload[PI_HARNESS_KEY] = version
- else:
- payload.pop(PI_HARNESS_KEY, None)
- routing = payload.get("_temporal_routing_v1")
- if isinstance(routing, dict):
- routing = dict(routing)
- if version == PI_HARNESS_VERSION:
- routing[PI_HARNESS_KEY] = version
- else:
- routing.pop(PI_HARNESS_KEY, None)
- payload["_temporal_routing_v1"] = routing
+ _freeze(payload, PI_HARNESS_KEY, version)
+ _freeze(payload, APPROVAL_WAIT_KEY, 1 if (manifest or {}).get(APPROVAL_WAIT_KEY) == 1 else None)
def enabled_coding_agents(nodes: list[dict]) -> bool:
diff --git a/server/services/deployment/handlers.py b/server/services/deployment/handlers.py
index 444ed6fc..7d69d054 100644
--- a/server/services/deployment/handlers.py
+++ b/server/services/deployment/handlers.py
@@ -2600,6 +2600,8 @@ async def handle_reset_workflow(data: Dict[str, Any], websocket: WebSocket) -> D
# Controller, cron, and legacy local admission paths are now closed. This
# final strict sweep therefore observes a fixed set of generation runs.
terminated = await _terminate_generation_workflows(current, strict=True)
+ from services.approvals.waiting import cancel_waits
+ await cancel_waits(service.database, workflow_id, current.generation)
from core.container import container
from services.browser_reset import cleanup_generation_browser_tasks
wrapper = container.temporal_client()
diff --git a/server/services/plugin/base.py b/server/services/plugin/base.py
index 3e5840d2..5b2a743d 100644
--- a/server/services/plugin/base.py
+++ b/server/services/plugin/base.py
@@ -1175,11 +1175,13 @@ class BaseNode:
return result
# Chat (services/chat/steps.py): a tool call of a run the owner
- # stopped is answered without running; a tool call of the agent
- # answering a chat run shows as a working step.
+ # stopped is answered without running, unless the owner allowed
+ # it and it is claimed (it must run or be recorded as not run);
+ # a tool call of the agent answering a chat run shows as a
+ # working step.
from services.chat import steps as chat_steps
- if await chat_steps.run_stopped(context):
+ if context.get("approval_execution") is None and await chat_steps.run_stopped(context):
result = {
"success": True,
"node_id": node_id,
diff --git a/server/services/temporal/agent_workflow.py b/server/services/temporal/agent_workflow.py
index b3679a78..9317987c 100644
--- a/server/services/temporal/agent_workflow.py
+++ b/server/services/temporal/agent_workflow.py
@@ -53,8 +53,8 @@ from datetime import timedelta
from typing import Any, Dict, List, Optional
from temporalio import workflow
-from temporalio.common import RetryPolicy # kept for type hints
-from temporalio.workflow import ActivityCancellationType, ParentClosePolicy
+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy # RetryPolicy kept for type hints
+from temporalio.workflow import ActivityCancellationType, ChildWorkflowCancellationType, ParentClosePolicy
from services.agent_bindings import unique_node_bindings
from services.coding_agent_runtime import agent_workflow_name, uses_pi
@@ -322,6 +322,9 @@ _INHERITED_SCOPE_KEYS = (
"browser_runtime_version",
"browser_bindings",
"_browser_task_id",
+ # What asks is the mode and the class, and the agent answering a chat
+ # run waits for the owner (RFC-0007): frozen per generation.
+ "approval_wait_version",
)
@@ -412,6 +415,39 @@ def _trusted_tool_scope(context: Dict[str, Any]) -> Dict[str, Any]:
return {**_inherited_scope(context), "outputs": context.get("outputs") or context.get("inputs") or {}}
+def _held_for_owner(result: Any) -> Optional[str]:
+ """The approval a call was held for (services/approvals/tool_calls.py),
+ else None."""
+ held = result.get("result") if isinstance(result, dict) else None
+ if not isinstance(held, dict) or held.get("status") != "waiting_for_owner":
+ return None
+ approval_id = result.get("approval_id") or held.get("approval_id")
+ return str(approval_id) if approval_id else None
+
+
+def _owner_answer(answer: Dict[str, Any]) -> Dict[str, Any]:
+ """What the model reads when the owner's answer ran nothing (RFC-0007
+ §4.5). Never ``requires_user_action``: the turn goes on."""
+ status = answer.get("status")
+ if status == "discarded":
+ note = answer.get("note")
+ tail = f" Their note: {note}" if note else " Don't try to get the same outcome another way."
+ return {"success": False, "status": "declined", "error": "The owner declined this; nothing happened." + tail}
+ if status == "expired":
+ return {"success": False, "status": "expired", "error": "The owner did not answer in time; nothing happened."}
+ return {"success": False, "status": "not_run", "error": "It was cancelled before it ran; nothing happened."}
+
+
+def _allowed_call_result(sent: Dict[str, Any]) -> Dict[str, Any]:
+ """What the model reads once the owner allowed a call: its own result,
+ or why it did not run, or that it broke off midway."""
+ if not sent.get("claimed"):
+ return {"success": False, "status": "not_run", "error": "It changed before it could run; nothing happened."}
+ if sent.get("error"):
+ return {"success": False, "status": "unknown", "error": f"It broke off midway, so it may or may not have happened: {sent['error']}"}
+ return sent.get("result") or {"success": True}
+
+
def _tool_call_metadata(
*,
agent_node_id: str,
@@ -791,6 +827,66 @@ class AgentWorkflow:
if self._control_paused:
await workflow.wait_condition(lambda: not self._control_paused)
+ async def _await_owner(self, approval_id: str) -> Dict[str, Any]:
+ """Wait in ``ApprovalWorkflow`` for the owner's answer to a held call
+ (RFC-0007 §4.6): ``{status, revision, note?}``. The caller holds no
+ admitted action meanwhile, so Stop completes while the owner decides;
+ only the child's start is fenced."""
+ async with self._execution_control.child_start():
+ waiter = await workflow.start_child_workflow(
+ "ApprovalWorkflow",
+ {"approval_id": approval_id},
+ id=f"approval-{approval_id}",
+ parent_close_policy=ParentClosePolicy.TERMINATE,
+ cancellation_type=ChildWorkflowCancellationType.WAIT_CANCELLATION_COMPLETED,
+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
+ )
+ return await waiter
+
+ async def _run_allowed_call(
+ self,
+ approval_id: str,
+ revision: int,
+ tool_activity_name: str,
+ tool_payload: Dict[str, Any],
+ context: Dict[str, Any],
+ tool_info: Dict[str, Any],
+ ) -> Dict[str, Any]:
+ """Run a call the owner allowed, once, under its claim, with the
+ owner's edits (``run_approved_call``), and return what the model
+ reads. A cancel that broke it off is recorded, then goes on."""
+ from .approved_tool_call_workflow import SEND_ONCE, run_approved_call
+
+ policy = tool_info.get("activity_policy")
+ if policy:
+ options = {**_frozen_tool_activity_options(policy, context), "retry_policy": SEND_ONCE}
+ else:
+ options = {"start_to_close_timeout": TOOL_STEP_TIMEOUT, "heartbeat_timeout": TOOL_HEARTBEAT_TIMEOUT, "retry_policy": SEND_ONCE}
+ base = {**tool_payload, **_inherited_scope(context), "user_id": str(context.get("user_id") or "owner")}
+
+ def as_allowed(claimed: Dict[str, Any]) -> Dict[str, Any]:
+ return {
+ **base,
+ "node_data": claimed.get("node_data") or {},
+ "tool_args": claimed.get("tool_args") or {},
+ "approval_execution": claimed["approval_execution"],
+ }
+
+ info = workflow.info()
+ token = hashlib.sha256(f"{info.workflow_id}:{info.run_id}:{approval_id}".encode()).hexdigest()[:32]
+ sent = await run_approved_call(
+ approval_id,
+ revision,
+ token,
+ activity=tool_activity_name,
+ overlay=as_allowed,
+ options=options,
+ ids=(f"approval-claim-{approval_id}", f"approval-send-{approval_id}", f"approval-record-{approval_id}"),
+ )
+ if sent.get("cancelled"):
+ raise asyncio.CancelledError()
+ return _allowed_call_result(sent)
+
async def _claim_browser_tools(self, context: dict, tools: list[dict]) -> None:
context.setdefault("_browser_task_id", workflow.info().workflow_id)
seen_profiles = {binding["profile_id"] for binding in self._browser_claims}
@@ -2225,6 +2321,16 @@ class AgentWorkflow:
tool_payload.update(_browser_owner=binding, _browser_task_id=context["_browser_task_id"])
if workflow.patched("employee-task-manager-tool-scope-v2"):
tool_payload = {**_trusted_tool_scope(context), **tool_payload}
+ # The agent answering a chat run, in a generation that waits,
+ # waits in its turn for a call held for the owner (RFC-0007
+ # §4.6); every other held call is a draft. Activity input only.
+ waits_for_owner = (
+ context.get("approval_wait_version") == 1
+ and self._execution_control.enabled
+ and bool(payload.get("chat_stream"))
+ )
+ if waits_for_owner:
+ tool_payload["approval_wait"] = True
tool_activity_name = (
tool_info["activity_name"] if tool_info.get("virtual_workspace") else "agent.skill.invoke"
@@ -2367,6 +2473,29 @@ class AgentWorkflow:
context,
tool_info,
)
+ held_for = _held_for_owner(tool_result) if waits_for_owner else None
+ if held_for:
+ # Outside any admitted action, so Stop
+ # completes while the owner decides.
+ if tool_action_active:
+ self._execution_control.end_action()
+ tool_action_active = False
+ answer = await self._await_owner(held_for)
+ if answer.get("status") == "approved":
+ # Allowed while stopped: it runs after Resume.
+ await self._wait_until_resumed()
+ await self._execution_control.begin_action()
+ tool_action_active = self._execution_control.enabled
+ tool_result = await self._run_allowed_call(
+ held_for,
+ int(answer.get("revision") or 0),
+ tool_activity_name,
+ tool_payload,
+ context,
+ tool_info,
+ )
+ else:
+ tool_result = _owner_answer(answer)
if (
tool_info["node_type"] == "taskManager"
and isinstance(tool_result, dict)
diff --git a/server/services/temporal/approved_tool_call_workflow.py b/server/services/temporal/approved_tool_call_workflow.py
index 8cf85c19..c0ac01da 100644
--- a/server/services/temporal/approved_tool_call_workflow.py
+++ b/server/services/temporal/approved_tool_call_workflow.py
@@ -8,18 +8,22 @@ message must never go twice, and records how it went: ``sent``, ``not_sent``
(the node said it did not go out) or ``unknown`` (the activity broke off,
so it may have).
+The claim, the run and the record are :func:`run_approved_call`, which an
+agent's turn that waited for the owner uses too (RFC-0007 §4.6).
+
``payload_version`` 1: ``{approval_id, revision, grace_until}``.
"""
from __future__ import annotations
+import asyncio
import hashlib
from datetime import datetime, timedelta
-from typing import Any, Dict
+from typing import Any, Callable, Dict, Optional, Tuple
from temporalio import workflow
from temporalio.common import RetryPolicy
-from temporalio.exceptions import ActivityError
+from temporalio.exceptions import ActivityError, is_cancelled_exception
BOOKKEEPING_TIMEOUT = timedelta(seconds=30)
#: Bookkeeping retries until it lands: the row must not stay "sending".
@@ -28,6 +32,73 @@ SEND_TIMEOUT = timedelta(minutes=10)
SEND_HEARTBEAT = timedelta(minutes=2)
#: Never retried: a retry could send it twice.
SEND_ONCE = RetryPolicy(maximum_attempts=1)
+#: How the node's own activity runs when the caller names nothing else.
+SEND_OPTIONS: Dict[str, Any] = {"start_to_close_timeout": SEND_TIMEOUT, "heartbeat_timeout": SEND_HEARTBEAT, "retry_policy": SEND_ONCE}
+
+
+async def run_approved_call(
+ approval_id: str,
+ revision: int,
+ token: str,
+ *,
+ activity: Optional[str] = None,
+ overlay: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None,
+ options: Optional[Dict[str, Any]] = None,
+ ids: Tuple[Optional[str], Optional[str], Optional[str]] = (None, None, None),
+) -> Dict[str, Any]:
+ """Claim the row at ``revision``, run the call once, record how it went.
+
+ Returns ``{claimed: False, reason}`` when the claim was refused (the row
+ moved), else ``{claimed: True, result, outcome, error?, cancelled?}``:
+ the node's own result, ``sent`` / ``not_sent`` / ``unknown``, and, when
+ the call broke off, why and whether a cancel broke it. The record is
+ shielded, so a cancel never leaves the row sending.
+
+ By default it runs the activity and input the claim names
+ (``ApprovedToolCallWorkflow``). An agent's turn passes its tool's own
+ ``activity``, an ``overlay`` that lays the claim's input over the call's
+ payload, its tool ``options`` with one attempt, and ``ids`` (claim, run,
+ record) that name the approval."""
+ claim_id, run_id, record_id = ids
+ claim = await workflow.execute_activity(
+ "approvals.claim_send",
+ {"approval_id": approval_id, "revision": revision, "claim_token": token},
+ activity_id=claim_id,
+ start_to_close_timeout=BOOKKEEPING_TIMEOUT,
+ retry_policy=BOOKKEEPING_RETRY,
+ )
+ if not claim.get("claimed"):
+ return {"claimed": False, "reason": claim.get("reason")}
+
+ report: Dict[str, Any] = {"approval_id": approval_id, "claim_token": token}
+ answer: Dict[str, Any] = {"claimed": True, "result": None}
+ try:
+ result = await workflow.execute_activity(
+ activity or str(claim["activity"]),
+ overlay(claim["context"]) if overlay is not None else claim["context"],
+ activity_id=run_id,
+ **(options or SEND_OPTIONS),
+ )
+ answer["result"] = result
+ if isinstance(result, dict) and result.get("success") is False:
+ report.update(success=False, error=str(result.get("error") or "It did not go out."))
+ else:
+ report.update(success=True)
+ except ActivityError as exc:
+ cause = exc.cause if exc.cause is not None else exc
+ report.update(broke_off=True, error=f"{type(cause).__name__}: {cause}")
+ answer.update(error=report["error"], cancelled=is_cancelled_exception(exc))
+
+ recorded = await asyncio.shield(
+ workflow.execute_activity(
+ "approvals.record_outcome",
+ report,
+ activity_id=record_id,
+ start_to_close_timeout=BOOKKEEPING_TIMEOUT,
+ retry_policy=BOOKKEEPING_RETRY,
+ )
+ )
+ return {**answer, "status": recorded.get("status"), "outcome": recorded.get("outcome")}
@workflow.defn(name="ApprovedToolCallWorkflow", sandboxed=False)
@@ -45,39 +116,10 @@ class ApprovedToolCallWorkflow:
if wait > 0:
await workflow.sleep(timedelta(seconds=wait))
- claim = await workflow.execute_activity(
- "approvals.claim_send",
- {"approval_id": approval_id, "revision": int(payload.get("revision") or 0), "claim_token": token},
- start_to_close_timeout=BOOKKEEPING_TIMEOUT,
- retry_policy=BOOKKEEPING_RETRY,
- )
- if not claim.get("claimed"):
- return {"sent": False, "reason": claim.get("reason")}
-
- report: Dict[str, Any] = {"approval_id": approval_id, "claim_token": token}
- try:
- result = await workflow.execute_activity(
- str(claim["activity"]),
- claim["context"],
- start_to_close_timeout=SEND_TIMEOUT,
- heartbeat_timeout=SEND_HEARTBEAT,
- retry_policy=SEND_ONCE,
- )
- if isinstance(result, dict) and result.get("success") is False:
- report.update(success=False, error=str(result.get("error") or "It did not go out."))
- else:
- report.update(success=True)
- except ActivityError as exc:
- cause = exc.cause if exc.cause is not None else exc
- report.update(broke_off=True, error=f"{type(cause).__name__}: {cause}")
-
- recorded = await workflow.execute_activity(
- "approvals.record_outcome",
- report,
- start_to_close_timeout=BOOKKEEPING_TIMEOUT,
- retry_policy=BOOKKEEPING_RETRY,
- )
- return {"sent": recorded.get("status") == "sent", "outcome": recorded.get("outcome")}
+ sent = await run_approved_call(approval_id, int(payload.get("revision") or 0), token)
+ if not sent["claimed"]:
+ return {"sent": False, "reason": sent["reason"]}
+ return {"sent": sent["status"] == "sent", "outcome": sent["outcome"]}
-__all__ = ["ApprovedToolCallWorkflow"]
+__all__ = ["ApprovedToolCallWorkflow", "run_approved_call"]
diff --git a/server/services/temporal/workflow.py b/server/services/temporal/workflow.py
index 9e369f67..fc44a82e 100644
--- a/server/services/temporal/workflow.py
+++ b/server/services/temporal/workflow.py
@@ -172,6 +172,15 @@ def _agent_child_workflow_id(root_workflow_id: str, agent_node_id: str) -> str:
return f"{root_workflow_id}-agent-{agent_node_id}"
+#: Selections frozen per generation at Start (RFC-0005 §24.1 rule 2): the
+#: workflow code branches on these, never on live settings, so a change
+#: behind one replays older histories without a patch marker
+#: (tests/temporal/test_workflow_identity_golden.py). ``approval_wait_version``:
+#: what asks is the mode and the class, and the agent answering a chat run
+#: waits for the owner (RFC-0007).
+GENERATION_FLAGS = ("pi_harness_version", "approval_wait_version")
+
+
def _frozen_routing_from_input(
workflow_data: Dict[str, Any],
) -> Dict[str, Any]:
@@ -191,7 +200,7 @@ def _frozen_routing_from_input(
raw.get("per_type_dispatch_enabled") is True
),
"worker_pool_enabled": raw.get("worker_pool_enabled") is True,
- **({"pi_harness_version": 1} if raw.get("pi_harness_version") == 1 else {}),
+ **{flag: 1 for flag in GENERATION_FLAGS if raw.get(flag) == 1},
}
@@ -764,6 +773,8 @@ class MachinaWorkflow:
for key in ("pi_local_control_version", "pi_local_control_state", "pi_local_control_revision"):
if key in workflow_data:
context[key] = workflow_data[key]
+ if frozen_routing.get("approval_wait_version") == 1:
+ context["approval_wait_version"] = 1
if workflow_data.get("browser_routing_version") == 1:
context.update(browser_routing_version=1, browser_bindings=workflow_data.get("browser_bindings") or {})
binding = context["browser_bindings"].get(node_id)
diff --git a/server/tests/services/approvals/test_held_activity.py b/server/tests/services/approvals/test_held_activity.py
index ed7560e0..4653e8b4 100644
--- a/server/tests/services/approvals/test_held_activity.py
+++ b/server/tests/services/approvals/test_held_activity.py
@@ -96,6 +96,27 @@ async def test_an_approved_send_runs_only_under_its_claim(harness, service):
service.execute_node.assert_awaited_once()
+async def test_a_claimed_call_runs_though_its_chat_run_reads_as_stopped(harness, service, monkeypatch):
+ # A turn that waited runs the allowed call with its chat run's scope
+ # (RFC-0007 §4.6): the claim is the owner's, so it runs or is recorded
+ # as not run, never answered "stopped" and recorded as sent.
+ from services.approvals.execution import node_context
+ from services.chat import steps
+
+ await rules.set_ask_first(harness.database, "wf", True)
+ activity_fn = get_node_class("whatsappSend").as_activity()
+ await ActivityEnvironment().run(activity_fn, context())
+ monkeypatch.setattr(steps, "run_stopped", AsyncMock(return_value=True))
+ (row,) = await store.list_approvals(harness.database, status="pending")
+ approved = await store.transition(harness.database, row.id, expected_revision=row.revision, from_statuses=("pending",), status="approved")
+ sending = await store.transition(
+ harness.database, row.id, expected_revision=approved.revision, from_statuses=("approved",), status="sending", values={"claim_token": "t1"}
+ )
+ result = await ActivityEnvironment().run(activity_fn, {**node_context(sending, "t1"), "chat_run_id": "r_1"})
+ service.execute_node.assert_awaited_once()
+ assert result["success"] is True
+
+
def attempt(number: int) -> ActivityEnvironment:
env = ActivityEnvironment()
env.info = dataclasses.replace(env.info, attempt=number)
diff --git a/server/tests/services/approvals/test_waiting.py b/server/tests/services/approvals/test_waiting.py
index f6ab2bed..0379a305 100644
--- a/server/tests/services/approvals/test_waiting.py
+++ b/server/tests/services/approvals/test_waiting.py
@@ -109,6 +109,32 @@ async def test_a_cancelled_wait_cancels_its_pending_row(harness):
assert await waiting.read(harness.database, "gone") == {"status": "cancelled", "revision": 0}
+async def test_a_reset_cancels_what_its_turns_waited_on(harness):
+ waited, allowed = await held(harness), await held(harness, "call_2")
+ await decide(allowed, "send", "s1")
+ await rules.set_mode(harness.database, "wf", "outside")
+ draft_context = {
+ "node_id": "wf:whatsappSend:1",
+ "workflow_id": "wf",
+ "execution_id": "wf:execution:1",
+ "generation": 1,
+ "user_id": "owner",
+ "parent_node_id": "wf:aiAgent:1",
+ "tool_call_id": "call_3",
+ "node_data": {"message_type": "text", **WHATSAPP},
+ "tool_args": WHATSAPP,
+ "approval_wait_version": 1,
+ }
+ await tool_calls.check(draft_context, get_node_class("whatsappSend"))
+ assert await waiting.cancel_waits(harness.database, "wf", 2) == 0
+ assert await waiting.cancel_waits(harness.database, "wf", 1) == 2
+ assert (await store.get(harness.database, waited.id)).status == "cancelled"
+ assert (await store.get(harness.database, allowed.id)).status == "cancelled"
+ # A draft is not a turn's: the Reset leaves it to the rest of its cleanup.
+ draft = next(row for row in await store.list_approvals(harness.database, status="pending") if row.tool_call_id == "call_3")
+ assert draft.runtime != waiting.TURN
+
+
async def test_a_decision_nudges_the_wait(harness, monkeypatch):
row = await held(harness)
client = FakeClient([row.id])
diff --git a/server/tests/services/test_pi_inline_adapters.py b/server/tests/services/test_pi_inline_adapters.py
index 716d59c4..35fb3c69 100644
--- a/server/tests/services/test_pi_inline_adapters.py
+++ b/server/tests/services/test_pi_inline_adapters.py
@@ -19,7 +19,7 @@ def scope():
"execution_id": "run", "workflow_slug": "saved", "generation": 2, "graphVersion": 3,
"parameter_snapshot": {"coding": {"model": "model"}}, "execution_control_version": 1,
"controller_workflow_id": "controller", "execution_control_revision": 8,
- "nodes": [{"id": "coding", "type": "coding_agent"}], "edges": []}
+ "nodes": [{"id": "coding", "type": "coding_agent"}], "edges": [], "approval_wait_version": 1}
@pytest.mark.asyncio
@@ -46,6 +46,9 @@ async def test_claude_mcp_uses_authenticated_request_identity_and_trusted_princi
assert config["tool_call_id"] == "mcp:" + canonical_digest({"session": "session-1", "request": "rpc-23"})
assert config["user_id"] == "alice" and config["root_execution_id"] == "root"
assert config["execution_control_revision"] == 8
+ # What asks rides the same scope (RFC-0007 §4.9): Start admits every
+ # generation with the Pi flag, so a generation that waits forwards it.
+ assert config["approval_wait_version"] == 1
assert execute.await_args.args[1] == {"task": "edit"}
# Independent clients can both call request 1 in the same admitted batch.
@@ -89,4 +92,5 @@ async def test_rlm_exposes_only_marked_coding_and_records_source_position(monkey
config = execute.await_args.args[2]
assert config["tool_call_id"].startswith("rlm:")
assert config["root_execution_id"] == "root" and config["controller_workflow_id"] == "controller"
+ assert config["approval_wait_version"] == 1
assert execute.await_args.args[1] == {"task": "edit"}
diff --git a/server/tests/services/test_versioned_workflow_control.py b/server/tests/services/test_versioned_workflow_control.py
index d7a8d8ed..85e8164c 100644
--- a/server/tests/services/test_versioned_workflow_control.py
+++ b/server/tests/services/test_versioned_workflow_control.py
@@ -159,6 +159,7 @@ def lifecycle(monkeypatch, state="running"):
monkeypatch.setattr(handlers, "_delete_cron_schedules", AsyncMock(return_value=1))
monkeypatch.setattr(handlers, "_signal_controller", AsyncMock())
monkeypatch.setattr(handlers, "_terminate_generation_workflows", AsyncMock(return_value=3))
+ monkeypatch.setattr("services.approvals.waiting.cancel_waits", AsyncMock(return_value=0))
monkeypatch.setattr(handlers, "_reset_workspace_tasks", AsyncMock(return_value={"cancelled": 0}))
monkeypatch.setattr(handlers, "handle_cancel_deployment", AsyncMock(return_value={"success": True}))
monkeypatch.setattr(handlers, "_clear_failure_streak", AsyncMock())
diff --git a/server/tests/services/test_workflow_control_handlers.py b/server/tests/services/test_workflow_control_handlers.py
index ec1203b8..1168bdb4 100644
--- a/server/tests/services/test_workflow_control_handlers.py
+++ b/server/tests/services/test_workflow_control_handlers.py
@@ -1069,6 +1069,9 @@ async def test_reset_retry_resumes_cleanup_before_marking_ready(monkeypatch):
"_terminate_generation_workflows",
terminate,
)
+ # The calls the reset turns waited on end cancelled (RFC-0007 §4.6).
+ cancel_waits = AsyncMock(return_value=0)
+ monkeypatch.setattr("services.approvals.waiting.cancel_waits", cancel_waits)
monkeypatch.setattr(
handlers,
"_delete_cron_schedules",
@@ -1098,6 +1101,8 @@ async def test_reset_retry_resumes_cleanup_before_marking_ready(monkeypatch):
assert result["success"] is True
assert result["state"] == "ready"
assert result["revision"] == 4
+ cancel_waits.assert_awaited_once()
+ assert cancel_waits.await_args.args[1:] == ("wf", resetting.generation)
assert result["terminated_executions"] == 2
assert result["deleted_schedules"] == 3
assert result["local_cleanup_completed"] is False
diff --git a/server/tests/services/test_workspace_task_reset.py b/server/tests/services/test_workspace_task_reset.py
index 1c7eff1d..767be52e 100644
--- a/server/tests/services/test_workspace_task_reset.py
+++ b/server/tests/services/test_workspace_task_reset.py
@@ -145,6 +145,7 @@ async def test_generation_reset_waits_for_workspace_before_archive_and_final_res
monkeypatch.setattr(handlers, "_delete_cron_schedules", AsyncMock(return_value=1))
monkeypatch.setattr(handlers, "handle_cancel_deployment", AsyncMock(return_value={"success": True}))
monkeypatch.setattr(handlers, "_terminate_generation_workflows", AsyncMock(side_effect=terminate))
+ monkeypatch.setattr("services.approvals.waiting.cancel_waits", AsyncMock(return_value=0))
monkeypatch.setattr(handlers, "_reset_workspace_tasks", workspace)
monkeypatch.setattr(runtime_state, "archive_and_reset_node_state", archive)
notices = broadcaster(monkeypatch, order)
diff --git a/server/tests/temporal/fixtures/workflow_identities.json b/server/tests/temporal/fixtures/workflow_identities.json
index 03e114ee..8a8d2275 100644
--- a/server/tests/temporal/fixtures/workflow_identities.json
+++ b/server/tests/temporal/fixtures/workflow_identities.json
@@ -942,11 +942,14 @@
"patch_entries": [
{
"before": "b00b963e489ffe4822ef7d2386562dc99f0d611b07c482c7f10d8539872f15c8",
- "after": "721e9e1f3b778a6b30da3fb69ca5b2738de7699ac5fc24e35712cb4527cef6b2",
+ "after": "d294a50b9a99c1837d7af5ad7ecbce1e8a4ead39117ec12af35596df4ff36ab5",
"new_types": [
"ApprovalWorkflow"
],
- "reason": "RFC-0007 AP.4a: ApprovalWorkflow is a new type (services/temporal/approval_workflow.py), so no recorded history runs it."
+ "flags": [
+ "approval_wait_version"
+ ],
+ "reason": "RFC-0007 AP.4a/AP.4b: ApprovalWorkflow is a new type, so no recorded history runs it; AgentWorkflow starts it, and claims, runs and records an allowed call, only in generations admitted with approval_wait_version 1; ApprovedToolCallWorkflow's commands moved into run_approved_call with no ids, so they replay as recorded (the approved_tool_call fixture)."
}
],
"handlers": {
diff --git a/server/tests/temporal/test_agent_approval_wait_integration.py b/server/tests/temporal/test_agent_approval_wait_integration.py
new file mode 100644
index 00000000..57bcc87b
--- /dev/null
+++ b/server/tests/temporal/test_agent_approval_wait_integration.py
@@ -0,0 +1,308 @@
+"""The agent answering a chat run waits in its turn for a held call
+(RFC-0007 §4.6), on the real SDK with stub activities: Allow runs the call
+once under its claim and the model's next step reads the real result;
+Decline gives it the owner's note; Stop completes while the call waits, and
+a call allowed while stopped runs only after Resume. Every history
+replays."""
+
+from __future__ import annotations
+
+import asyncio
+import subprocess
+import sys
+from collections import Counter
+from pathlib import Path
+from uuid import uuid4
+
+from temporalio import activity
+from temporalio.api.enums.v1 import EventType
+from temporalio.client import WorkflowHistory
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Replayer, Worker
+
+from services.llm.protocol import Message, ToolCall, message_to_wire
+from services.temporal.agent_workflow import AgentWorkflow
+from services.temporal.approval_workflow import ApprovalWorkflow
+
+QUEUE = "agent-approval-wait-gate"
+COUNTS: Counter = Counter()
+LLM_INPUTS: list[dict] = []
+SENT: list[dict] = []
+READS: list[dict] = []
+ROWS: dict[str, dict] = {}
+
+
+def _tool() -> dict:
+ return {
+ "name": "send",
+ "node_type": "fake_send",
+ "version": 1,
+ "tool_node_id": "send",
+ "parameters": {},
+ "tool_info": {},
+ "definition": {"name": "send", "description": "send", "parameters": {"type": "object", "properties": {}}},
+ "activity_policy": {
+ "start_to_close_seconds": 60,
+ "heartbeat_seconds": 10,
+ "task_queue": QUEUE,
+ "retry_policy": {
+ "initial_interval_seconds": 1,
+ "maximum_interval_seconds": 5,
+ "backoff_coefficient": 2,
+ "maximum_attempts": 3,
+ "non_retryable_error_types": [],
+ },
+ },
+ }
+
+
[email protected](name="agent.prepare_payload")
+async def _prepare(context: dict) -> dict:
+ return {
+ "node_id": "agent",
+ "node_type": "aiAgent",
+ "provider": "openai",
+ "model": "stub",
+ "workflow_id": "wf",
+ "session_id": "wf",
+ "system_message": "Keep working",
+ "user_prompt": "Tell Ana",
+ "tools": [_tool()],
+ "max_iterations": 4,
+ "memory_node_id": "",
+ "compaction_threshold": None,
+ "chat_run_id": "r1",
+ "chat_stream": {"run_id": "r1", "session_id": "wf", "workflow_id": "wf"},
+ }
+
+
[email protected](name="agent.execute_llm_step")
+async def _llm(payload: dict) -> dict:
+ LLM_INPUTS.append(payload)
+ if payload["iteration"] >= 1:
+ return {
+ "kind": "final",
+ "content": "done",
+ "assistant_message": message_to_wire(Message(role="assistant", content="done")),
+ "usage": {"total_tokens": 3},
+ }
+ calls = [{"id": "call_1", "name": "send", "args": {"message": "On my way."}}]
+ return {
+ "kind": "tool_calls",
+ "calls": calls,
+ "assistant_message": message_to_wire(Message(role="assistant", tool_calls=[ToolCall(**call) for call in calls])),
+ "usage": {"total_tokens": 3},
+ }
+
+
[email protected](name="node.fake_send.v1")
+async def _send(payload: dict) -> dict:
+ if payload.get("approval_execution"):
+ SENT.append(payload)
+ return {"success": True, "result": {"sent_to": payload["tool_args"].get("to")}}
+ COUNTS["held"] += 1
+ assert payload.get("approval_wait") is True
+ return {
+ "success": True,
+ "approval_id": "ap1",
+ "result": {"status": "waiting_for_owner", "approval_id": "ap1", "message": "Waiting for the owner."},
+ }
+
+
[email protected](name="approvals.read")
+async def _read(payload: dict) -> dict:
+ READS.append(payload)
+ row = ROWS[payload["approval_id"]]
+ if row["status"] == "pending":
+ return {"status": "pending", "revision": row["revision"], "expires_at": "2100-01-01T00:00:00+00:00"}
+ return {key: row[key] for key in ("status", "revision", "note") if key in row}
+
+
[email protected](name="approvals.claim_send")
+async def _claim(payload: dict) -> dict:
+ COUNTS["claim"] += 1
+ assert payload["revision"] == ROWS[payload["approval_id"]]["revision"]
+ return {
+ "claimed": True,
+ "activity": "node.fake_send.v1",
+ "context": {
+ "node_data": {"message": "On my way!"},
+ "tool_args": {"message": "On my way!", "to": "Ana"},
+ "approval_execution": {"approval_id": payload["approval_id"], "claim_token": payload["claim_token"]},
+ },
+ }
+
+
[email protected](name="approvals.record_outcome")
+async def _record(payload: dict) -> dict:
+ COUNTS["record"] += 1
+ return {"recorded": True, "status": "sent", "outcome": "sent"}
+
+
[email protected](name="agent.broadcast_progress")
+async def _broadcast(payload: dict) -> dict:
+ return {}
+
+
[email protected](name="agent.store_output")
+async def _store(payload: dict) -> dict:
+ return {}
+
+
[email protected](name="agent.skill.clear")
+async def _clear(payload: dict) -> dict:
+ return {}
+
+
[email protected](name="execution_control.register")
+async def _register(payload: dict) -> dict:
+ return {"participant_state": "running", "participant_revision": 0}
+
+
[email protected](name="execution_control.unregister")
+async def _unregister(payload: dict) -> dict:
+ return {}
+
+
+ACTIVITIES = [_prepare, _llm, _send, _read, _claim, _record, _broadcast, _store, _clear, _register, _unregister]
+WORKFLOWS = [AgentWorkflow, ApprovalWorkflow]
+
+
+def _input() -> dict:
+ return {
+ "node_id": "agent",
+ "execution_control_version": 1,
+ "controller_workflow_id": "controller",
+ "generation": 1,
+ "execution_control_revision": 0,
+ "approval_wait_version": 1,
+ }
+
+
+def _reset() -> None:
+ for bucket in (COUNTS, ROWS):
+ bucket.clear()
+ for items in (LLM_INPUTS, SENT, READS):
+ items.clear()
+ ROWS["ap1"] = {"status": "pending", "revision": 1}
+
+
+async def _waiting(environment: WorkflowEnvironment) -> None:
+ """Until the wait has read its row once."""
+ for _ in range(500):
+ if READS:
+ return
+ await asyncio.sleep(0.01)
+ raise AssertionError("the turn never waited on the held call")
+
+
+def _tool_messages() -> list[dict]:
+ return [message for message in LLM_INPUTS[-1]["messages"] if message["role"] == "tool"]
+
+
+async def _replay(history: WorkflowHistory) -> None:
+ result = await Replayer(workflows=WORKFLOWS).replay_workflow(WorkflowHistory.from_json(history.workflow_id, history.to_json()))
+ assert result.replay_failure is None
+
+
+async def _allow(environment: WorkflowEnvironment) -> None:
+ _reset()
+ async with Worker(environment.client, task_queue=QUEUE, workflows=WORKFLOWS, activities=ACTIVITIES, max_cached_workflows=0):
+ handle = await environment.client.start_workflow("AgentWorkflow", _input(), id=f"allow-{uuid4()}", task_queue=QUEUE)
+ await _waiting(environment)
+ assert COUNTS["claim"] == 0 and len(LLM_INPUTS) == 1
+ ROWS["ap1"].update(status="approved", revision=2)
+ await environment.client.get_workflow_handle("approval-ap1").signal("nudge")
+ result = await asyncio.wait_for(handle.result(), 10)
+ history = await handle.fetch_history()
+ assert result["success"] is True
+ assert COUNTS["held"] == COUNTS["claim"] == COUNTS["record"] == 1 and len(SENT) == 1
+ # The call ran as the owner allowed it, under its claim.
+ assert SENT[0]["tool_args"] == {"message": "On my way!", "to": "Ana"}
+ assert SENT[0]["approval_execution"]["approval_id"] == "ap1"
+ # The model's next step reads the real result.
+ assert [message["content"] for message in _tool_messages()] == ['{"sent_to": "Ana"}']
+ scheduled = {
+ event.activity_task_scheduled_event_attributes.activity_id
+ for event in history.events
+ if event.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED
+ }
+ assert {"approval-claim-ap1", "approval-send-ap1", "approval-record-ap1"} <= scheduled
+ await _replay(history)
+
+
+async def _decline(environment: WorkflowEnvironment) -> None:
+ _reset()
+ async with Worker(environment.client, task_queue=QUEUE, workflows=WORKFLOWS, activities=ACTIVITIES, max_cached_workflows=0):
+ handle = await environment.client.start_workflow("AgentWorkflow", _input(), id=f"decline-{uuid4()}", task_queue=QUEUE)
+ await _waiting(environment)
+ ROWS["ap1"].update(status="discarded", revision=2, note="Call her instead.")
+ await environment.client.get_workflow_handle("approval-ap1").signal("nudge")
+ result = await asyncio.wait_for(handle.result(), 10)
+ history = await handle.fetch_history()
+ assert result["success"] is True and COUNTS["claim"] == 0 and SENT == []
+ [message] = _tool_messages()
+ assert "The owner declined this; nothing happened. Their note: Call her instead." in message["content"]
+ await _replay(history)
+
+
+async def _stop_while_waiting(environment: WorkflowEnvironment) -> None:
+ _reset()
+ async with Worker(environment.client, task_queue=QUEUE, workflows=WORKFLOWS, activities=ACTIVITIES, max_cached_workflows=0):
+ handle = await environment.client.start_workflow("AgentWorkflow", _input(), id=f"stop-{uuid4()}", task_queue=QUEUE)
+ await _waiting(environment)
+ stop = {"state": "paused", "revision": 1, "generation": 1}
+ assert (await handle.execute_update("set_control_state", stop))["state"] == "paused"
+ # Stop completes while the call waits: the wait is no action.
+ drained = await asyncio.wait_for(handle.execute_update("wait_for_checkpoint", stop), 10)
+ assert drained["checkpoint"] and drained["active_actions"] == 0
+ # Allowed while stopped: it runs only after Resume.
+ ROWS["ap1"].update(status="approved", revision=2)
+ await environment.client.get_workflow_handle("approval-ap1").signal("nudge")
+ await asyncio.sleep(0.3)
+ assert COUNTS["claim"] == 0 and SENT == []
+ await handle.execute_update("set_control_state", {"state": "running", "revision": 2, "generation": 1, "producers_held": False})
+ result = await asyncio.wait_for(handle.result(), 10)
+ history = await handle.fetch_history()
+ assert result["success"] is True and COUNTS["claim"] == 1 and len(SENT) == 1
+ await _replay(history)
+
+
+async def _main() -> None:
+ async with await WorkflowEnvironment.start_time_skipping() as environment:
+ with environment.auto_time_skipping_disabled():
+ await _allow(environment)
+ await _decline(environment)
+ await _stop_while_waiting(environment)
+
+
+def test_the_flag_rides_a_generation_from_start_to_its_tool_calls() -> None:
+ from services.coding_agent_runtime import freeze_generation_harness
+ from services.temporal.agent_workflow import _INHERITED_SCOPE_KEYS
+ from services.temporal.workflow import TEMPORAL_ROUTING_INPUT_KEY, TEMPORAL_ROUTING_INPUT_VERSION, _frozen_routing_from_input
+
+ payload = {TEMPORAL_ROUTING_INPUT_KEY: {"version": TEMPORAL_ROUTING_INPUT_VERSION}}
+ freeze_generation_harness(payload, {"execution_control_version": 1, "approval_wait_version": 1})
+ assert payload["approval_wait_version"] == payload[TEMPORAL_ROUTING_INPUT_KEY]["approval_wait_version"] == 1
+ assert _frozen_routing_from_input(payload)["approval_wait_version"] == 1
+ # A generation admitted without it keeps today's drafts.
+ freeze_generation_harness(payload, {"execution_control_version": 1})
+ assert "approval_wait_version" not in payload and "approval_wait_version" not in _frozen_routing_from_input(payload)
+ assert "approval_wait_version" in _INHERITED_SCOPE_KEYS
+
+
+def test_a_turn_waits_for_the_owner_and_runs_the_allowed_call() -> None:
+ result = subprocess.run(
+ [sys.executable, "-m", "tests.temporal.test_agent_approval_wait_integration"],
+ cwd=Path(__file__).parents[2],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT,
+ timeout=120,
+ check=False,
+ )
+ assert result.returncode == 0, result.stdout.decode(errors="replace")[-12000:]
+
+
+if __name__ == "__main__":
+ asyncio.run(_main())
diff --git a/server/tests/temporal/test_workflow_identity_golden.py b/server/tests/temporal/test_workflow_identity_golden.py
index 0338f4eb..80140dbd 100644
--- a/server/tests/temporal/test_workflow_identity_golden.py
+++ b/server/tests/temporal/test_workflow_identity_golden.py
@@ -43,6 +43,8 @@ def test_workflow_command_identities_match_release_or_explicit_patch_entry():
before, after = digest(golden["identities"]), digest(current)
entries = [entry for entry in golden.get("patch_entries", []) if entry["before"] == before and entry["after"] == after]
assert entries, "Temporal activity names/child IDs/markers changed: add a reviewed versioning patch entry and replay N-1 histories"
+ from services.temporal.workflow import GENERATION_FLAGS
+
markers = _markers(current, "patched") | _markers(current, "deprecate_patch")
registered = set(_registered_types())
for entry in entries:
@@ -50,7 +52,11 @@ def test_workflow_command_identities_match_release_or_explicit_patch_entry():
added = set(entry.get("new_types", []))
# A new type must be registered and absent from the release.
assert added <= registered and not added & set(golden["workflow_types"]), entry
- assert entry.get("patch") in markers or (added and "patch" not in entry), entry
+ # A flag frozen per generation gates the change for new generations
+ # only (RFC-0005 §24.1 rule 2).
+ flags = set(entry.get("flags", []))
+ assert flags <= set(GENERATION_FLAGS), entry
+ assert entry.get("patch") in markers or ((added or flags) and "patch" not in entry), entry
def test_patch_markers_move_to_deprecated_before_they_vanish():