Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(temporal): ApprovalWorkflow, where a turn waits for the owner (RFC-0007 AP.4a)
trohitg0374b5b77219
diff --git a/docs-internal/TEMPORAL_ARCHITECTURE.md b/docs-internal/TEMPORAL_ARCHITECTURE.mdindex d9f02305..393a7e51 100644--- a/docs-internal/TEMPORAL_ARCHITECTURE.md+++ b/docs-internal/TEMPORAL_ARCHITECTURE.md@@ -802,7 +802,7 @@ keep that release's command identities:imported by `worker.py` as `_framework_workflows`) plus the plugin workflowsfrom the same plugin registry. It checks each workflow module's source hashagainst the set's origin commit, and fails when a production type has no- history.+ history, unless the golden names it as new since the release (below).- **Golden identities.** `server/tests/temporal/fixtures/workflow_identities.json`holds the release's:- workflow types;@@ -813,7 +813,10 @@ keep that release's command identities:- plugin task queues.`test_workflow_identity_golden.py` fails when:- - commands change without a reviewed patch entry;+ - 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);- a patched marker vanishes before a release has shipped it as`deprecate_patch` (RFC-0005 §24.3);- a handler is renamed or removed;@@ -853,8 +856,17 @@ unsandboxed like the other framework workflows):- `approvals.record_outcome` records `sent`, `not_sent` (the node said it did not go) or `unknown` (the activitybroke off, so it may have gone), and leaves the employee an `[update]` note for its next chat turn.-A send that broke off midway outside this workflow leaves a card the same way (`outcome: unknown`, see "Worker crashes-mid-execution" below). A graph node's card keeps what the node sent, its templates resolved and its secrets left out;+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+(`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+(`execution_control.NON_PARTICIPANTS`).++A send that broke off midway outside `ApprovedToolCallWorkflow` leaves a card the same way (`outcome: unknown`, see+"Worker crashes mid-execution" below). A graph node's card keeps what the node sent, its templates resolved and its secrets left out;its Send again runs the node with no graph and no tool arguments (`approvals.execution.node_context`), so nothingresolves again and the node's saved settings put the secrets back.@@ -959,6 +971,7 @@ server/services/temporal/├── workspace_tasks_workflow.py # WorkspaceTaskControllerWorkflow (per-workflow admission + Reset for direct Workspace tasks)├── node_invocation.py # NodeInvocationWorkflow (one direct Workspace task)├── approved_tool_call_workflow.py # ApprovedToolCallWorkflow (sends a held tool call once the owner approved it)+├── approval_workflow.py # ApprovalWorkflow (a turn waits here for the owner's answer to a held call)├── workspace_task_activities.py # reset_workspace_task_runtime (activity workspace_tasks.reset_runtime)├── schedules.py # Temporal Schedule creation for cronScheduler├── search_attributes.py # EVENT_SEARCH_ATTRIBUTES (7 custom SAs, incl. ControlEventTypes)diff --git a/server/services/approvals/__init__.py b/server/services/approvals/__init__.pyindex b8edba09..4dddf1ab 100644--- a/server/services/approvals/__init__.py+++ b/server/services/approvals/__init__.py@@ -9,6 +9,8 @@- ``repeats``: which node calls may run again after an attempt broke off.- ``execution`` / ``activities``: sending a held call once the ownerpressed Send (``ApprovedToolCallWorkflow``).+- ``waiting``: a held call its agent's turn waits on (``ApprovalWorkflow``):+ nudged on every change to its row.- ``waiter``: wakes a waiting approval gate at once.- ``reconcile``: ends what nothing waits for any more, and restarts sendsthat never started.@@ -19,8 +21,8 @@The ``approvalGate`` node that waits on a row lives in``nodes/workflow/approval_gate``; this package never imports ``nodes/``.-Importing the package registers the WebSocket commands, the broadcast and-the cleanup that runs when a workflow is deleted.+Importing the package registers the WebSocket commands, the broadcast, the+nudge and the cleanup that runs when a workflow is deleted."""from __future__ import annotations@@ -32,9 +34,11 @@ from .events import broadcast_approval_change as _broadcast_approval_changefrom .handlers import WS_HANDLERS as _APPROVAL_WS_HANDLERSfrom .handlers import on_workflow_deleted as _on_workflow_deletedfrom .listeners import register_approval_listener as _register_approval_listener+from .waiting import nudge_on_change as _nudge_on_change_register_ws_handlers(_APPROVAL_WS_HANDLERS)_register_approval_listener(_broadcast_approval_change)+_register_approval_listener(_nudge_on_change)_register_workflow_deleted_hook(_on_workflow_deleted)__all__ = [@@ -51,4 +55,5 @@ __all__ = ["store","tool_calls","waiter",+ "waiting",]diff --git a/server/services/approvals/activities.py b/server/services/approvals/activities.pyindex 40a4b728..08409b52 100644--- a/server/services/approvals/activities.py+++ b/server/services/approvals/activities.py@@ -1,9 +1,11 @@"""The Temporal activities ``ApprovedToolCallWorkflow`` sends a held tool call-through (services/approvals/execution.py).+through (services/approvals/execution.py), and the one ``ApprovalWorkflow``+reads the row a turn waits on with (services/approvals/waiting.py).-Both are safe to retry: a claim retried by the same workflow run finds its-own claim (the token is the run's), and an outcome is recorded once (only a-row still ``sending`` under that claim moves).+All are safe to retry: a claim retried by the same workflow run finds its+own claim (the token is the run's), an outcome is recorded once (only a+row still ``sending`` under that claim moves), and a read moves a row only+from pending."""from __future__ import annotations@@ -49,6 +51,16 @@ async def record_outcome_activity(payload: Dict[str, Any]) -> Dict[str, Any]:return {"recorded": settled is not None, "status": getattr(settled, "status", None), "outcome": outcome["outcome"]}-APPROVAL_ACTIVITIES = [claim_send_activity, record_outcome_activity][email protected](name="approvals.read")+async def read_activity(payload: Dict[str, Any]) -> Dict[str, Any]:+ """Payload ``{approval_id, cancel?}``. Returns ``{status, revision,+ expires_at?, note?}`` (``waiting.read``)."""+ from core.container import container+ from services.approvals.waiting import read++ return await read(container.database(), str(payload.get("approval_id") or ""), cancel=payload.get("cancel") is True)+++APPROVAL_ACTIVITIES = [claim_send_activity, record_outcome_activity, read_activity]-__all__ = ["APPROVAL_ACTIVITIES", "claim_send_activity", "record_outcome_activity"]+__all__ = ["APPROVAL_ACTIVITIES", "claim_send_activity", "read_activity", "record_outcome_activity"]diff --git a/server/services/approvals/listeners.py b/server/services/approvals/listeners.pyindex 15bfffb1..3e013753 100644--- a/server/services/approvals/listeners.py+++ b/server/services/approvals/listeners.py@@ -28,6 +28,9 @@ class ApprovalChange:revision: int#: The chat run a held tool call was made in.run_id: Optional[str] = None+ #: ``turn`` when its agent's turn waits on it (services/approvals/+ #: waiting.py).+ runtime: Optional[str] = NoneApprovalListener = Callable[[ApprovalChange], Any]@@ -57,6 +60,7 @@ def change_of(row: Any, stage: str) -> ApprovalChange:status=row.status,revision=row.revision,run_id=getattr(row, "run_id", None) or None,+ runtime=getattr(row, "runtime", None) or None,)diff --git a/server/services/approvals/reconcile.py b/server/services/approvals/reconcile.pyindex 042423b4..1b47de8f 100644--- a/server/services/approvals/reconcile.py+++ b/server/services/approvals/reconcile.py@@ -23,6 +23,10 @@ created by this process are never touched.Expiry: a held call waits on nothing, so the chat watchdog ends one pastits expiry every round (:func:`expire_due`). Rows are kept until theirworkflow is deleted.++Waits: a decided row a turn waits on is nudged again from the same round+when its wait has not read it (:func:`renudge_turns`), in case the nudge+the decision sent was lost (services/approvals/waiting.py)."""from __future__ import annotations@@ -42,7 +46,11 @@ _LIVE_STATUSES = frozenset({"starting", "running", "pausing", "paused", "resumin_START_GRACE = timedelta(seconds=60)#: How long a claimed send may run before it counts as broken off._SEND_DEADLINE = timedelta(minutes=30)+#: How long a decision's own nudge may take before the round nudges again.+_RENUDGE_AFTER = timedelta(seconds=10)_done = False+#: Approved rows whose wait had ended: their turn takes them on itself.+_ended: set = set()def _aware(moment: datetime) -> datetime:@@ -141,9 +149,45 @@ async def reconcile_once(database: Any) -> None:logger.warning("Could not reconcile waiting drafts", exc_info=True)+async def renudge_turns(database: Any, *, now: datetime | None = None) -> List[str]:+ """Nudge again the waits whose decided rows they have not read, while+ the row's generation runs (a stopped employee's turns go on after+ Resume). A row whose wait has ended is left: one nothing will read is+ marked read, an approved one is its turn's to take on."""+ from services.approvals import waiting++ client = waiting.engine()+ if client is None:+ return []+ now = now or datetime.now(timezone.utc)+ nudged: List[str] = []+ for row in await store.list_unread_waits(database):+ decided = store.aware(row.decided_at) or store.aware(row.updated_at)+ if row.id in _ended or decided is None or now - decided < _RENUDGE_AFTER:+ continue+ control = await database.get_latest_workflow_control(row.workflow_id)+ if control is None or control.generation != row.generation or control.status != "running":+ continue+ try:+ reached = await waiting.nudge(row.id, client)+ except Exception:+ logger.warning("Could not nudge an approval wait", approval_id=row.id, exc_info=True)+ continue+ if reached:+ nudged.append(row.id)+ elif row.status == "approved":+ _ended.add(row.id)+ else:+ await waiting.mark_read(database, row.id)+ if nudged:+ logger.info("Nudged approval waits again", count=len(nudged))+ return nudged++def reset_for_tests() -> None:global _done_done = False+ _ended.clear()-__all__ = ["PROCESS_STARTED", "cancel_orphaned_pending", "expire_due", "reconcile_once", "recover_sends"]+__all__ = ["PROCESS_STARTED", "cancel_orphaned_pending", "expire_due", "reconcile_once", "recover_sends", "renudge_turns"]diff --git a/server/services/approvals/store.py b/server/services/approvals/store.pyindex f7be300e..3c96ab3c 100644--- a/server/services/approvals/store.py+++ b/server/services/approvals/store.py@@ -320,6 +320,20 @@ async def list_pending(database: Any) -> List[ApprovalRequest]:return list(result.scalars().all())+async def list_unread_waits(database: Any) -> List[ApprovalRequest]:+ """Decided rows a turn waits on whose wait has not taken the answer yet+ (services/approvals/waiting.py)."""+ async with database.get_session() as session:+ result = await session.execute(+ select(ApprovalRequest).where(+ ApprovalRequest.runtime == "turn",+ ApprovalRequest.status != "pending",+ ApprovalRequest.consumed_at.is_(None),+ )+ )+ return list(result.scalars().all())++async def list_unfinished_sends(database: Any) -> List[ApprovalRequest]:"""Approved held calls not handed on, and sends that never reported."""async with database.get_session() as session:diff --git a/server/services/approvals/waiting.py b/server/services/approvals/waiting.pynew file mode 100644index 00000000..72cced4f--- /dev/null+++ b/server/services/approvals/waiting.py@@ -0,0 +1,118 @@+"""A held tool call its agent's turn waits on (``runtime: turn``, RFC-0007+§4.6).++The turn waits in ``ApprovalWorkflow`` (services/temporal/approval_workflow.py),+one per call, id ``approval-<approval_id>``. It reads the row+(:func:`read`, the ``approvals.read`` activity) and, while the row is+pending, waits for a ``nudge`` Signal or the row's expiry, then reads again.++- :func:`nudge_on_change`, an approval listener: every change to a turn row+ (a decision, an expiry, a cancel) nudges its wait.+- ``reconcile.renudge_turns``, from the chat watchdog's round: a decided+ row its wait has not read yet is nudged again, in case the first nudge+ was lost.++A nudge to a wait that has ended, or with no workflow engine, is dropped:+the wait reads the row at its expiry in any case. Never imports ``nodes/``.+"""++from __future__ import annotations++from datetime import datetime, timedelta, timezone+from typing import Any, Dict++from sqlalchemy import update++from core.logging import get_logger+from models.approvals import ApprovalRequest+from services.approvals import store+from services.approvals.contract import DEFAULT_TIMEOUT_HOURS+from services.approvals.listeners import ApprovalChange, change_of, notify_approval_changed++logger = get_logger(__name__)++WORKFLOW_NAME = "ApprovalWorkflow"+#: The row's ``runtime`` when its turn waits on it.+TURN = "turn"+++def _utcnow() -> datetime:+ return datetime.now(timezone.utc)+++def wait_workflow_id(approval_id: str) -> str:+ return f"approval-{approval_id}"+++def engine() -> Any:+ """The connected Temporal client, or None."""+ from core.container import container++ wrapper = container.temporal_client()+ return getattr(wrapper, "client", None) if wrapper is not None else None+++async def nudge(approval_id: str, client: Any) -> bool:+ """Wake the wait on ``approval_id`` to read its row again. False when+ that wait has ended."""+ from temporalio.service import RPCError, RPCStatusCode++ try:+ await client.get_workflow_handle(wait_workflow_id(approval_id)).signal("nudge")+ except RPCError as exc:+ if exc.status != RPCStatusCode.NOT_FOUND:+ raise+ logger.debug("The approval wait had ended", approval_id=approval_id)+ return False+ return True+++async def nudge_on_change(change: ApprovalChange) -> None:+ if change.runtime != TURN or change.status == "pending":+ return+ client = engine()+ if client is not None:+ await nudge(change.approval_id, client)+++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."""+ async with database.get_session() as session:+ await session.execute(+ update(ApprovalRequest)+ .where(ApprovalRequest.id == approval_id, ApprovalRequest.consumed_at.is_(None))+ .values(consumed_at=_utcnow())+ )+ await session.commit()+++async def read(database: Any, approval_id: str, *, cancel: bool = False) -> Dict[str, Any]:+ """The answer a wait gets: ``{status, revision, expires_at}`` while the+ row is pending, else ``{status, revision, note?}``. A row past its expiry+ ends ``expired`` first; with ``cancel`` (the wait was cancelled) a+ pending row ends ``cancelled``. A row that is gone reads as cancelled.+ An answer other than ``approved`` marks the row read; a claim marks an+ approved one when its call runs."""+ from services.approvals.decisions import expire_if_due++ row = await store.get(database, approval_id)+ if row is None:+ return {"status": "cancelled", "revision": 0}+ if row.status == "pending" and cancel:+ try:+ row = await store.settle(database, row.id, expected_revision=row.revision, status="cancelled")+ await notify_approval_changed(change_of(row, "cancelled"))+ except store.ApprovalConflict:+ row = await store.get(database, approval_id) or row+ elif row.status == "pending":+ row = await expire_if_due(database, row, _utcnow())+ if row.status == "pending":+ expires = store.aware(row.expires_at) or store.aware(row.created_at) + timedelta(hours=DEFAULT_TIMEOUT_HOURS)+ return {"status": "pending", "revision": row.revision, "expires_at": expires.isoformat()}+ if row.status != "approved":+ await mark_read(database, row.id)+ 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"]diff --git a/server/services/chat/watchdog.py b/server/services/chat/watchdog.pyindex fce9313f..13c4be6f 100644--- a/server/services/chat/watchdog.py+++ b/server/services/chat/watchdog.py@@ -114,15 +114,17 @@ class ChatRunWatchdog:except Exception: # noqa: BLE001 - the next sweep tries againlogger.warning("Chat run sweep failed", exc_info=True)try:- # Drafts held for the owner wait on nothing, so they end here- # once past their expiry (services/approvals/reconcile.py).- from services.approvals.reconcile import expire_due+ # Drafts held for the owner end here once past their expiry,+ # and a turn's wait whose nudge was lost is nudged again+ # (services/approvals/reconcile.py).+ from services.approvals.reconcile import expire_due, renudge_turnsawait expire_due(self.database)+ await renudge_turns(self.database)except asyncio.CancelledError:raiseexcept Exception: # noqa: BLE001 - the next round tries again- logger.warning("Held draft expiry failed", exc_info=True)+ logger.warning("Held draft expiry or nudge failed", exc_info=True)await asyncio.sleep(self.interval)diff --git a/server/services/deployment/execution_control.py b/server/services/deployment/execution_control.pyindex e317740c..bd3aa2e3 100644--- a/server/services/deployment/execution_control.py+++ b/server/services/deployment/execution_control.py@@ -22,6 +22,17 @@ class GenerationTransitionSuperseded(RuntimeError):"""A newer durable control intent owns this generation."""+#: Children that take no part in generation control: they admit no actions+#: and answer no control Updates or Queries. An approval wait+#: (services/temporal/approval_workflow.py) waits for the owner, so Stop+#: completes around it.+NON_PARTICIPANTS = frozenset({"ApprovalWorkflow"})+++def _participants(desc: Any) -> list:+ return [child for child in desc.raw_description.pending_children if child.workflow_type_name not in NON_PARTICIPANTS]++async def count_generation_actions(client: Any, controller_id: str, status: dict) -> int:"""A read-only UI count; transition verification uses acknowledgements."""queue = [controller_id, *(status.get("live_roots") or {})]@@ -38,7 +49,7 @@ async def count_generation_actions(client: Any, controller_id: str, status: dictcontinueparticipant = await handle.query("execution_control_status")count += int(participant.get("active_actions", 0))- queue.extend(child.workflow_id for child in desc.raw_description.pending_children)+ queue.extend(child.workflow_id for child in _participants(desc))return count@@ -132,8 +143,7 @@ async def transition_generation(client: Any, control: Any, *, paused: bool, on_a# describe, so pending_children is a complete direct-child fence.desc = await describe(workflow_id, current_chain)if desc is not None:- queue.extend((child.workflow_id, child.run_id)- for child in desc.raw_description.pending_children)+ queue.extend((child.workflow_id, child.run_id) for child in _participants(desc))logger.info("Generation admission acknowledged", workflow_id=control.workflow_id,revision=revision, latency_seconds=time.monotonic() - started,diff --git a/server/services/temporal/approval_workflow.py b/server/services/temporal/approval_workflow.pynew file mode 100644index 00000000..60f03bbe--- /dev/null+++ b/server/services/temporal/approval_workflow.py@@ -0,0 +1,74 @@+"""Wait for the owner's answer to a held tool call its turn waits on+(RFC-0007 §4.6; services/approvals/waiting.py).++AgentWorkflow starts one per waiting call, id ``approval-<approval_id>``,+and awaits it outside any admitted action, so Stop completes while it+waits. It reads the row (``approvals.read``, which ends it ``expired`` past+its expiry) and, while the row is pending, waits for a ``nudge`` Signal (the+row changed) or the row's expiry, then reads again. It returns the row's+answer: ``{status, revision, note?}``. Cancelled, it ends a still pending+row ``cancelled`` before the cancel goes on.++It admits no actions and answers no control Updates, so Stop's tree walk+leaves it out (services/deployment/execution_control.py). Unsandboxed, like+every type in this package (its ``__init__`` has import side effects).++``payload_version`` 1: ``{approval_id}``.+"""++from __future__ import annotations++import asyncio+from datetime import datetime, timedelta+from typing import Any, Dict++from temporalio import workflow++from services.temporal.approved_tool_call_workflow import BOOKKEEPING_RETRY, BOOKKEEPING_TIMEOUT++#: The shortest wait between two reads.+MIN_WAIT = timedelta(seconds=1)++[email protected](name="ApprovalWorkflow", sandboxed=False)+class ApprovalWorkflow:+ def __init__(self) -> None:+ self._nudged = False++ @workflow.signal+ def nudge(self) -> None:+ self._nudged = True++ @workflow.run+ async def run(self, payload: Dict[str, Any]) -> Dict[str, Any]:+ approval_id = str(payload.get("approval_id") or "")+ try:+ while True:+ # Before the read, so a nudge during it is not lost.+ self._nudged = False+ row = await workflow.execute_activity(+ "approvals.read",+ {"approval_id": approval_id},+ start_to_close_timeout=BOOKKEEPING_TIMEOUT,+ retry_policy=BOOKKEEPING_RETRY,+ )+ if row.get("status") != "pending":+ return row+ due = datetime.fromisoformat(str(row["expires_at"]))+ try:+ await workflow.wait_condition(lambda: self._nudged, timeout=max(due - workflow.now(), MIN_WAIT))+ except asyncio.TimeoutError:+ pass # the next read ends it expired, unless a decision got there first+ except asyncio.CancelledError:+ await asyncio.shield(+ workflow.execute_activity(+ "approvals.read",+ {"approval_id": approval_id, "cancel": True},+ start_to_close_timeout=BOOKKEEPING_TIMEOUT,+ retry_policy=BOOKKEEPING_RETRY,+ )+ )+ raise+++__all__ = ["ApprovalWorkflow"]diff --git a/server/services/temporal/workflow_registry.py b/server/services/temporal/workflow_registry.pyindex 02de3efe..286043cf 100644--- a/server/services/temporal/workflow_registry.py+++ b/server/services/temporal/workflow_registry.py@@ -15,14 +15,15 @@ def framework_workflows() -> list:from services.temporal.node_invocation import NodeInvocationWorkflowfrom services.temporal.workspace_tasks_workflow import WorkspaceTaskControllerWorkflowfrom services.temporal.approved_tool_call_workflow import ApprovedToolCallWorkflow+ from services.temporal.approval_workflow import ApprovalWorkflowfrom services.temporal.employee_job_workflow import EmployeeJobWorkflow, EmployeeJobDeliveryWorkflowreturn [EmployeeJobWorkflow, EmployeeJobDeliveryWorkflow, ApprovedToolCallWorkflow,- NodeInvocationWorkflow, WorkspaceTaskControllerWorkflow, MachinaWorkflow,- AgentWorkflow, PiCodingAgentWorkflow, PiInlineDelegationWorkflow,- DelegatedTaskWorkflow, TriggerListenerWorkflow, PollingTriggerWorkflow,- WorkflowControlWorkflow,+ ApprovalWorkflow, NodeInvocationWorkflow, WorkspaceTaskControllerWorkflow,+ MachinaWorkflow, AgentWorkflow, PiCodingAgentWorkflow,+ PiInlineDelegationWorkflow, DelegatedTaskWorkflow, TriggerListenerWorkflow,+ PollingTriggerWorkflow, WorkflowControlWorkflow,]diff --git a/server/tests/services/approvals/conftest.py b/server/tests/services/approvals/conftest.pyindex 328c53df..7eaeb22a 100644--- a/server/tests/services/approvals/conftest.py+++ b/server/tests/services/approvals/conftest.py@@ -61,7 +61,8 @@ def harness(monkeypatch, real_database):import nodes.workflow.approval_gate as gatebroadcaster = FakeBroadcaster()- monkeypatch.setattr(container_module, "container", SimpleNamespace(database=lambda: real_database))+ # No workflow engine: nudges to a turn's wait go nowhere.+ monkeypatch.setattr(container_module, "container", SimpleNamespace(database=lambda: real_database, temporal_client=lambda: None))monkeypatch.setattr(status_broadcaster, "get_status_broadcaster", lambda: broadcaster)monkeypatch.setattr(gate, "POLL_SECONDS", 0.02)# Undo and Restore windows short enough for a test to wait them out.diff --git a/server/tests/services/approvals/test_waiting.py b/server/tests/services/approvals/test_waiting.pynew file mode 100644index 00000000..f6ab2bed--- /dev/null+++ b/server/tests/services/approvals/test_waiting.py@@ -0,0 +1,170 @@+"""A held call its turn waits on (RFC-0007 §4.6): its wait reads the row+(ending it expired once due, cancelled when the wait was cancelled), every+change to a turn row nudges the wait, and the chat watchdog's round nudges+again a decided row the wait has not read, while its generation runs."""++from __future__ import annotations++from datetime import datetime, timedelta, timezone+from types import SimpleNamespace++import pytest+from temporalio.service import RPCError, RPCStatusCode++import nodes # noqa: F401 -- populate plugin registry+from services.approvals import handlers, reconcile, rules, store, tool_calls, waiting+from services.node_registry import get_node_class++pytestmark = pytest.mark.asyncio++SOCKET = SimpleNamespace(scope={"path": "/ws/status"}, state=SimpleNamespace(user_id="owner"))+WHATSAPP = {"recipient_type": "phone", "phone": "447700900123", "message": "On my way."}+++class FakeClient:+ """Signals the waits it was given; any other wait has ended."""++ def __init__(self, waiting_ids=()):+ self.waiting = {waiting.wait_workflow_id(approval_id) for approval_id in waiting_ids}+ self.signals = []++ def get_workflow_handle(self, workflow_id):+ client = self++ class Handle:+ async def signal(self, name):+ if workflow_id not in client.waiting:+ raise RPCError("not found", RPCStatusCode.NOT_FOUND, b"")+ client.signals.append((workflow_id, name))++ return Handle()+++async def held(harness, call_id="call_1"):+ await rules.set_mode(harness.database, "wf", "outside")+ 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_id,+ "node_data": {"message_type": "text", **WHATSAPP},+ "tool_args": WHATSAPP,+ "approval_wait_version": 1,+ "approval_wait": True,+ }+ await tool_calls.check(context, get_node_class("whatsappSend"))+ return next(row for row in await store.list_approvals(harness.database, status="pending") if row.tool_call_id == call_id)+++async def decide(row, decision, key, **extra):+ return await handlers.handle_decide_approval({"approval_id": row.id, "decision": decision, "decision_key": key, **extra}, SOCKET)+++def engine(monkeypatch, client):+ monkeypatch.setattr(waiting, "engine", lambda: client)+++async def test_a_wait_reads_a_pending_row_until_it_is_decided(harness):+ row = await held(harness)+ answer = await waiting.read(harness.database, row.id)+ assert answer["status"] == "pending" and answer["revision"] == row.revision+ assert datetime.fromisoformat(answer["expires_at"]) == store.aware(row.expires_at)+ await decide(row, "discard", "d1", note="Call her instead.")+ assert await waiting.read(harness.database, row.id) == {+ "status": "discarded",+ "revision": row.revision + 1,+ "note": "Call her instead.",+ }+ # Read: nothing nudges it again.+ assert (await store.get(harness.database, row.id)).consumed_at is not None+++async def test_an_approved_row_is_left_for_its_claim(harness):+ row = await held(harness)+ await decide(row, "send", "s1")+ assert (await waiting.read(harness.database, row.id))["status"] == "approved"+ assert (await store.get(harness.database, row.id)).consumed_at is None+++async def test_a_wait_past_the_expiry_ends_the_row_expired(harness):+ row = await held(harness)+ await store.transition(+ harness.database,+ row.id,+ expected_revision=row.revision,+ from_statuses=("pending",),+ status="pending",+ values={"expires_at": datetime.now(timezone.utc) - timedelta(minutes=1)},+ )+ assert (await waiting.read(harness.database, row.id))["status"] == "expired"+++async def test_a_cancelled_wait_cancels_its_pending_row(harness):+ row = await held(harness)+ assert (await waiting.read(harness.database, row.id, cancel=True))["status"] == "cancelled"+ assert (await store.get(harness.database, row.id)).status == "cancelled"+ assert await waiting.read(harness.database, "gone") == {"status": "cancelled", "revision": 0}+++async def test_a_decision_nudges_the_wait(harness, monkeypatch):+ row = await held(harness)+ client = FakeClient([row.id])+ engine(monkeypatch, client)+ await decide(row, "send", "s1")+ assert client.signals == [(f"approval-{row.id}", "nudge")]+++async def test_a_draft_nudges_nothing(harness, monkeypatch):+ client = FakeClient()+ engine(monkeypatch, client)+ await rules.set_mode(harness.database, "wf", "outside")+ context = {+ "node_id": "wf:whatsappSend:1",+ "workflow_id": "wf",+ "execution_id": "wf:execution:1",+ "user_id": "owner",+ "parent_node_id": "wf:aiAgent:1",+ "tool_call_id": "call_1",+ "node_data": {"message_type": "text", **WHATSAPP},+ "tool_args": WHATSAPP,+ "approval_wait_version": 1,+ }+ await tool_calls.check(context, get_node_class("whatsappSend"))+ (row,) = await store.list_approvals(harness.database, status="pending")+ await decide(row, "discard", "d1")+ assert client.signals == []+++async def test_the_round_nudges_again_what_the_wait_has_not_read(harness, monkeypatch):+ first, second, gone = await held(harness), await held(harness, "call_2"), await held(harness, "call_3")+ engine(monkeypatch, None) # the decisions' own nudges are lost+ await decide(first, "send", "s1")+ await decide(second, "discard", "d2")+ await decide(gone, "discard", "d3")+ later = datetime.now(timezone.utc) + timedelta(seconds=30)++ async def control(workflow_id):+ return SimpleNamespace(generation=1, status=state["status"])++ state = {"status": "paused"}+ monkeypatch.setattr(harness.database, "get_latest_workflow_control", control)+ client = FakeClient([first.id, second.id])+ engine(monkeypatch, client)+ # A stopped employee's waits go on after Resume.+ assert await reconcile.renudge_turns(harness.database, now=later) == []+ state["status"] = "running"+ # Not yet: the decision's own nudge may still be on its way.+ assert await reconcile.renudge_turns(harness.database, now=datetime.now(timezone.utc)) == []+ assert sorted(await reconcile.renudge_turns(harness.database, now=later)) == sorted([first.id, second.id])+ # A declined row whose wait has ended is never read: it is marked read.+ assert (await store.get(harness.database, gone.id)).consumed_at is not None+ client.waiting.clear()+ assert await reconcile.renudge_turns(harness.database, now=later) == []+ # Ended too: the approved one is its turn's to take on, the declined one+ # is marked read, and neither is nudged again.+ assert (await store.get(harness.database, second.id)).consumed_at is not None+ client.waiting.update({waiting.wait_workflow_id(first.id), waiting.wait_workflow_id(second.id)})+ assert await reconcile.renudge_turns(harness.database, now=later) == []diff --git a/server/tests/temporal/fixtures/workflow_identities.json b/server/tests/temporal/fixtures/workflow_identities.jsonindex 9b030467..03e114ee 100644--- a/server/tests/temporal/fixtures/workflow_identities.json+++ b/server/tests/temporal/fixtures/workflow_identities.json@@ -939,7 +939,16 @@]}},- "patch_entries": [],+ "patch_entries": [+ {+ "before": "b00b963e489ffe4822ef7d2386562dc99f0d611b07c482c7f10d8539872f15c8",+ "after": "721e9e1f3b778a6b30da3fb69ca5b2738de7699ac5fc24e35712cb4527cef6b2",+ "new_types": [+ "ApprovalWorkflow"+ ],+ "reason": "RFC-0007 AP.4a: ApprovalWorkflow is a new type (services/temporal/approval_workflow.py), so no recorded history runs it."+ }+ ],"handlers": {"DelegatedTaskWorkflow": ["query:execution_control_status",diff --git a/server/tests/temporal/test_approval_workflow.py b/server/tests/temporal/test_approval_workflow.pynew file mode 100644index 00000000..de3b87f9--- /dev/null+++ b/server/tests/temporal/test_approval_workflow.py@@ -0,0 +1,129 @@+"""``ApprovalWorkflow`` on Temporal's time-skipping test server: it reads the+row again when nudged, returns the owner's answer, reads again at the row's+expiry, and a cancel ends a pending row before it goes on.++Runs in a clean process (valid Windows I/O handles), like the other SDK+gates."""++from __future__ import annotations++import asyncio+import subprocess+import sys+from datetime import timedelta+from pathlib import Path+from typing import Any, Dict, List+from uuid import uuid4++TASK_QUEUE = "approval-wait-test"+++async def _scenarios() -> None:+ from temporalio import activity+ from temporalio.client import WorkflowFailureError+ from temporalio.testing import WorkflowEnvironment+ from temporalio.worker import Worker++ from services.temporal.approval_workflow import ApprovalWorkflow++ reads: List[Dict[str, Any]] = []+ rows: Dict[str, Dict[str, Any]] = {}++ @activity.defn(name="approvals.read")+ async def read(payload: Dict[str, Any]) -> Dict[str, Any]:+ reads.append(payload)+ row = rows[payload["approval_id"]]+ if payload.get("cancel") and row["status"] == "pending":+ row["status"] = "cancelled"+ if row["status"] == "pending":+ return {"status": "pending", "revision": row["revision"], "expires_at": row["expires_at"]}+ return {"status": row["status"], "revision": row["revision"], **({"note": row["note"]} if row.get("note") else {})}++ async with await WorkflowEnvironment.start_time_skipping() as environment:+ async with Worker(environment.client, task_queue=TASK_QUEUE, workflows=[ApprovalWorkflow], activities=[read]):++ async def wait(approval_id: str, expires_in: timedelta):+ now = await environment.get_current_time()+ rows[approval_id] = {"status": "pending", "revision": 1, "expires_at": (now + expires_in).isoformat()}+ return await environment.client.start_workflow(+ ApprovalWorkflow.run, {"approval_id": approval_id}, id=f"approval-{approval_id}-{uuid4()}", task_queue=TASK_QUEUE+ )++ async def settled(approval_id: str) -> None:+ # The wait has read its row once and waits for a nudge.+ for _ in range(500):+ if any(entry["approval_id"] == approval_id for entry in reads):+ return+ await asyncio.sleep(0.01)+ raise AssertionError(f"the wait on {approval_id} never read its row")++ # A decision, then its nudge: the owner's answer comes back.+ handle = await wait("a1", timedelta(days=7))+ await settled("a1")+ rows["a1"].update(status="discarded", revision=2, note="Call her instead.")+ await handle.signal(ApprovalWorkflow.nudge)+ assert await handle.result() == {"status": "discarded", "revision": 2, "note": "Call her instead."}+ assert [entry for entry in reads if entry["approval_id"] == "a1"] == [{"approval_id": "a1"}] * 2++ # No nudge: it reads again at the expiry, where the row ended.+ handle = await wait("a2", timedelta(hours=1))+ await settled("a2")+ rows["a2"].update(status="expired", revision=2)+ assert (await handle.result())["status"] == "expired"++ # Cancelled while it waits: the pending row ends cancelled first.+ handle = await wait("a3", timedelta(days=7))+ await settled("a3")+ await handle.cancel()+ try:+ await handle.result()+ raise AssertionError("a cancelled wait should not complete")+ except WorkflowFailureError:+ pass+ assert {"approval_id": "a3", "cancel": True} in reads+ assert rows["a3"]["status"] == "cancelled"+++def test_every_worker_registers_the_wait() -> None:+ from services.approvals.activities import APPROVAL_ACTIVITIES+ from services.temporal import worker+ from services.temporal.approval_workflow import ApprovalWorkflow++ assert ApprovalWorkflow in worker._framework_workflows()+ assert "approvals.read" in {getattr(fn, "__temporal_activity_definition").name for fn in APPROVAL_ACTIVITIES}+++def test_stop_leaves_the_wait_out_of_its_tree_walk() -> None:+ from types import SimpleNamespace++ from services.deployment.execution_control import _participants++ def child(name: str, workflow_type: str):+ return SimpleNamespace(workflow_id=name, run_id="r", workflow_type_name=workflow_type)++ desc = SimpleNamespace(+ raw_description=SimpleNamespace(+ pending_children=[+ child("agent", "AgentWorkflow"),+ child("approval-a1", "ApprovalWorkflow"),+ ]+ )+ )+ assert [item.workflow_id for item in _participants(desc)] == ["agent"]+++def test_the_wait_on_temporal() -> None:+ completed = subprocess.run(+ [sys.executable, "-m", "tests.temporal.test_approval_workflow"],+ cwd=Path(__file__).parents[2],+ stdin=subprocess.DEVNULL,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ timeout=180,+ check=False,+ )+ assert completed.returncode == 0, completed.stdout.decode(errors="replace")[-3000:]+++if __name__ == "__main__":+ asyncio.run(_scenarios())diff --git a/server/tests/temporal/test_approved_tool_call_workflow.py b/server/tests/temporal/test_approved_tool_call_workflow.pyindex 939ce412..a83d5ef2 100644--- a/server/tests/temporal/test_approved_tool_call_workflow.py+++ b/server/tests/temporal/test_approved_tool_call_workflow.py@@ -110,7 +110,7 @@ def test_every_worker_registers_the_workflow_and_its_activities() -> None:source = (Path(__file__).parents[2] / "services" / "temporal" / "worker.py").read_text(encoding="utf-8")assert source.count("*APPROVAL_ACTIVITIES") == 3names = sorted(getattr(fn, "__temporal_activity_definition").name for fn in APPROVAL_ACTIVITIES)- assert names == ["approvals.claim_send", "approvals.record_outcome"]+ assert names == ["approvals.claim_send", "approvals.read", "approvals.record_outcome"]def test_an_approved_send_has_one_attempt() -> None:diff --git a/server/tests/temporal/test_replay_corpus.py b/server/tests/temporal/test_replay_corpus.pyindex e078029b..e6f40619 100644--- a/server/tests/temporal/test_replay_corpus.py+++ b/server/tests/temporal/test_replay_corpus.py@@ -66,7 +66,11 @@ async def replay() -> None:result = await Replayer(workflows=workflows).replay_workflow(history)assert result.replay_failure is None, (scenario, result.replay_failure)count += 1- assert names <= covered, f"Production workflow types missing N-1 histories: {sorted(names - covered)}"+ # A type added since the release has no release history yet; the golden+ # names it in a reviewed entry (test_workflow_identity_golden.py).+ golden = json.loads((FIXTURES / "workflow_identities.json").read_text(encoding="utf-8"))+ added = {name for entry in golden.get("patch_entries", []) for name in entry.get("new_types", [])}+ assert names - added <= covered, f"Production workflow types missing N-1 histories: {sorted(names - added - covered)}"print(f"Replayed {count} real N-1 histories covering {len(covered)} production workflow types")diff --git a/server/tests/temporal/test_workflow_identity_golden.py b/server/tests/temporal/test_workflow_identity_golden.pyindex df5cb923..0338f4eb 100644--- a/server/tests/temporal/test_workflow_identity_golden.py+++ b/server/tests/temporal/test_workflow_identity_golden.py@@ -23,6 +23,18 @@ def _missing_handlers(release: dict, current: dict) -> dict[str, list[str]]:return {name: handlers for name, handlers in missing.items() if handlers}+def _registered_types() -> list[str]:+ from services.temporal.workflow_registry import replay_workflows++ return [item.__temporal_workflow_definition.name for item in replay_workflows()]+++def _new_types(golden: dict) -> set[str]:+ """Workflow types added since the release, named in reviewed entries:+ no recorded history runs them, so they need no patch marker."""+ return {name for entry in golden.get("patch_entries", []) for name in entry.get("new_types", [])}++def test_workflow_command_identities_match_release_or_explicit_patch_entry():golden = json.loads(GOLDEN.read_text(encoding="utf-8"))current = identity_snapshot()@@ -32,7 +44,13 @@ def test_workflow_command_identities_match_release_or_explicit_patch_entry():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"markers = _markers(current, "patched") | _markers(current, "deprecate_patch")- assert all(entry.get("patch") in markers and entry.get("reason") for entry in entries)+ registered = set(_registered_types())+ for entry in entries:+ assert entry.get("reason"), 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), entrydef test_patch_markers_move_to_deprecated_before_they_vanish():@@ -101,12 +119,12 @@ def test_the_handler_inventory_reads_names_from_the_decorators(tmp_path):def test_worker_and_replayer_use_the_shared_production_registry():from services.temporal.worker import _framework_workflows- from services.temporal.workflow_registry import framework_workflows, replay_workflows+ from services.temporal.workflow_registry import framework_workflowsassert _framework_workflows is framework_workflows- names = [item.__temporal_workflow_definition.name for item in replay_workflows()]+ names = _registered_types()golden = json.loads(GOLDEN.read_text(encoding="utf-8"))- assert sorted(names) == golden["workflow_types"]+ assert sorted(names) == sorted([*golden["workflow_types"], *_new_types(golden)])assert len(names) == len(set(names)), "Duplicate workflow registrations"