The Complete Production SOP: How to Deploy and Run Temporal Workflow Orchestration & Durable Execution in Autonomous AI Agents
Production SOP to install and run the Temporal Workflow skill in Codex, Claude Code, and Cursor. Write deterministic workflows with verified retries.
Technical Overview & Architectural Context
Autonomous coding agents frequently fail when generating distributed systems code—specifically Temporal workflows—because LLMs inherently default to standard procedural paradigms. Left unguided, agents import standard time utilities (`time.sleep` or `datetime.now()`), spawn raw threads, execute direct HTTP queries inside workflow methods, or make un-versioned signature modifications. During Temporal event replay, these non-deterministic behaviors trigger fatal `WorkflowTaskFailed` exceptions, corrupting execution histories and deadlocking critical workflows in production. The `temporal-workflow-deterministic-state` skill injects deterministic procedural guardrails into the agent runtime (Codex Desktop, Claude Code, Cursor, and Windsurf). It forces the agent to isolate side-effects within `@activity.defn` handlers, mandate explicit `RetryPolicy` structures with exponential backoffs and non-retryable error blocks, handle dynamic event routing with `@workflow.signal`, and govern breaking state evolutions through `workflow.patched()`. By anchoring the agent to a verifiable SOP, distributed workflows remain durable, multi-day executions survive orchestrator crashes, and replay checks pass automatically.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local agent skill manifest directory and inject verified procedural rules into your workspace.
Autonomous runtimes like Claude Code, Cursor, and Codex detect project-level or user-level SOP instructions via canonical agent skill paths. Mounting the `temporal-workflow-deterministic-state` SKILL.md into `.agents/skills` allows the agent runtime parser to register trigger phrases such as 'write temporal workflow' or 'configure temporal activity retry', bounding its code-generation graph to deterministic rules.
mkdir -p .agents/skills/temporal-workflow-deterministic-state && curl -fsSL https://askills.dev/api/skills/temporal-workflow-deterministic-state/raw -o .agents/skills/temporal-workflow-deterministic-state/SKILL.md---
name: "temporal-workflow-deterministic-state"
description: "Write resilient, multi-day distributed workflows with automatic retries and durable state."
metadata:
author: "Temporal Technologies"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "write temporal workflow"
- "configure temporal activity retry"
- "handle temporal workflow signal"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: false
net_access: false
---
# Temporal Workflow Orchestration & Durable Execution
## Execution SOP & Rules
1. Keep workflow functions strictly deterministic; never invoke network I/O, file systems, or random numbers in workflows.
2. Wrap side-effects and external API calls inside @activity.defn functions with retry policies.
3. Handle external events using @workflow.signal and expose read state using @workflow.query.
4. Use workflow.patched('change-id') when evolving running workflow definitions to prevent replay mismatches.Keep the SKILL.md scoped to procedural boundaries. By keeping frontmatter triggers concise, agents index the capability into memory using under 150 prompt tokens.
Do not grant `shell_exec: true` or broad network permissions to this skill; workflow generation requires pure workspace file updates. The safety score of 98/100 depends on sandboxed filesystem boundaries.
Environment Secrets & Dependency Validation
Install the required Temporal SDK dependencies and verify environment definitions without hardcoding credentials.
Temporal workers require connection parameters to namespaces and orchestrator endpoints. Ensure your development environment has the official Temporal SDK installed, and reference environment variables via configuration files rather than hardcoded string literals inside workflow scripts.
poetry add temporalio || pip install temporalioimport os
from dataclasses import dataclass
@dataclass(frozen=True)
class TemporalSettings:
target_host: str = os.getenv("TEMPORAL_TARGET_HOST", "localhost:7233")
namespace: str = os.getenv("TEMPORAL_NAMESPACE", "default")
task_queue: str = os.getenv("TEMPORAL_TASK_QUEUE", "order-fulfillment-v1")
settings = TemporalSettings()Never allow your agent to inject `os.getenv` directly within the body of `@workflow.defn` methods. Environment variables must be parsed during Worker initialization or inside `@activity.defn` scopes.
Calling `os.environ` inside `@workflow.run` causes non-deterministic failures across distributed workers running on heterogeneous environments.
Intent Matching & Trigger Invocation
Trigger the agent using precise intent phrases to generate compliant Temporal workflow and activity architectures.
Provide the agent with a prompt matching the exact frontmatter trigger phrase: 'write temporal workflow'. When the runtime encounters this trigger, it applies the deterministic checklist: isolating activities, setting start-to-close timeouts, binding retry policies, and establishing signals.
from datetime import timedelta
from temporalio import workflow
from temporalio.common import RetryPolicy
with workflow.unsafe.imports_passed_through():
from activities.payment import process_payment, PaymentInput
@workflow.defn
class OrderFulfillmentWorkflow:
def __init__(self) -> None:
self._payment_approved: bool = False
self._cancelled: bool = False
@workflow.signal
def cancel_order(self) -> None:
self._cancelled = True
@workflow.query
def is_approved(self) -> bool:
return self._payment_approved
@workflow.run
async def run(self, order_id: str, amount_cents: int) -> str:
if self._cancelled:
return "CANCELLED_BEFORE_PAYMENT"
retry_policy = RetryPolicy(
initial_interval=timedelta(seconds=1),
backoff_coefficient=2.0,
maximum_interval=timedelta(seconds=30),
maximum_attempts=5,
non_retryable_error_types=["InvalidCreditCardError"]
)
payment_result = await workflow.execute_activity(
process_payment,
PaymentInput(order_id=order_id, amount_cents=amount_cents),
start_to_close_timeout=timedelta(seconds=10),
retry_policy=retry_policy,
)
self._payment_approved = payment_result.success
return f"ORDER_COMPLETED: {order_id}"Use `workflow.unsafe.imports_passed_through()` when importing activity type definitions to prevent static analyzers and linter replay sandboxes from throwing duplicate module load warnings.
Never use `asyncio.sleep()` inside Temporal workflow code; always call `await workflow.sleep()` to ensure the orchestrator advances virtual timers deterministically.
Deterministic Verification & Workflow Replay Testing
Execute local workflow replay validation tests to ensure complete determinism against production execution histories.
The skill mandates testing workflow changes against the `WorkflowReplayer`. This step loads existing workflow execution histories (JSON) and replays the updated code against past events. If an agent introduced a non-deterministic operation or modified workflow history without `workflow.patched()`, the test runner halts immediately.
pytest tests/test_replay.py -vimport pytest
from temporalio.worker import WorkflowReplayer
from workflows.order_workflow import OrderFulfillmentWorkflow
@pytest.mark.asyncio
async def test_order_workflow_replay():
replayer = WorkflowReplayer(workflows=[OrderFulfillmentWorkflow])
# Validates deterministic replay without side-effects or network calls
await replayer.replay_workflow(
WorkflowReplayer.WorkflowHistory.from_json("order-101", open("tests/fixtures/order_101_history.json").read())
)Store representative JSON execution histories in your test suite. Whenever modifying a workflow, ask the agent: 'run replay test against order_101_history.json to ensure determinism'.
Running pytest directly against an actual Temporal server rather than using `WorkflowReplayer` or `WorkflowEnvironment.start_time_skipping()` will cause long wait times and flaky CI timeouts.
Real-World Scenario: Customer Subscription Billing with Asynchronous Cancellation Signal
“write temporal workflow for subscription billing that sleeps for 30 days between renewals, processes credit card charges with an exponential backoff activity retry policy, and handles temporal workflow signal for immediate cancellation.”
Runtime Troubleshooting & Failure Modes
Root Cause: The agent introduced a standard Python library non-deterministic call (e.g., `uuid.uuid4()`, `datetime.now()`, or an raw I/O call) directly inside `@workflow.run` instead of delegating to an activity or using `workflow.now()` / `workflow.uuid4()`.
# Replace non-deterministic call:
# BAD: current_time = datetime.datetime.now()
# BAD: random_id = str(uuid.uuid4())
# GOOD:
current_time = workflow.now()
random_id = str(workflow.uuid4())Root Cause: A modification was made to an active workflow execution path (such as adding or removing an activity call) without wrapping the logic in `workflow.patched('change-id')`, violating backward compatibility.
# Update the workflow logic using workflow.patched:
if workflow.patched("add-fraud-check-v2"):
await workflow.execute_activity(fraud_check, order_id, start_to_close_timeout=timedelta(seconds=5))
else:
# Historical path for in-flight workflows prior to v2
passFrequently Asked Questions (Temporal Workflow Orchestration & Durable Execution SOP)
Q:Can I use Temporal Workflow Orchestration & Durable Execution across Codex, Claude Code, and Cursor simultaneously?
Yes. The skill conforms to the open SKILL.md specification. By mounting the directory at `.agents/skills/temporal-workflow-deterministic-state` or referencing it in your workspace settings, Codex Desktop, Claude Code, Cursor, and Windsurf can load and enforce the exact same deterministic orchestration constraints.
Q:How does Temporal Workflow Orchestration & Durable Execution prevent context window overflow during long agent sessions?
Instead of filling the agent system prompt with thousands of lines of Temporal SDK documentation, this skill encapsulates procedural SOPs into targeted trigger phrases. The agent only loads detailed determinism and retry policies when an explicit workflow authoring trigger is detected.
Q:Does this skill require escalated root or container permissions?
No. The skill is audited with a security score of 98/100. It requires read access and workspace-scoped file write permissions, operating without root privileges or unauthorized shell commands.
Ready to equip your autonomous agent with Temporal Workflow Orchestration & Durable Execution?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.