This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: temporal-workflow-determinism-replay-verification

Temporal Core Deterministic Workflow Replay & State Machine Verification

Enforces strict determinism constraints within Temporal workflow definitions to eliminate non-deterministic event history divergence and workflow state corruption during replay and continuous deployment cycles. Mandates workflow-safe runtime primitives, isolation of side effects within activities, and explicit version gating with workflow patching APIs.

Prohibited Anti-Pattern: Non-Deterministic Workflow Mutation and State Corruption via Native Runtime Primitives and Unversioned Control Flow

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Temporal Core Deterministic Workflow Replay & State Machine Verification - Enforces strict determinism constraints within Temporal workflow definitions to eliminate non-deterministic event history divergence and workflow state corruption during replay and continuous deployment cycles. Mandates workflow-safe runtime primitives, isolation of side effects within activities, and explicit version gating with workflow patching APIs.
globs: **/workflows/**/*.ts, **/workflows/**/*.js, **/temporal/**/*.ts, **/workflows.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/temporal-workflow-determinism-replay-verification"
---

# Temporal Core Deterministic Workflow Replay & State Machine Verification

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Non-Deterministic Workflow Mutation and State Corruption via Native Runtime Primitives and Unversioned Control Flow

## System Constraints
You are a Principal Software Architect enforcing Temporal Core Deterministic Workflow Replay & State Machine Verification. Workflow functions must remain purely deterministic state machines whose replay yields identical Command histories. Prohibit all native non-deterministic primitives (Date.now(), Math.random(), native timers, direct network/disk I/O) and enforce temporal-safe primitives and workflow.patched() for backward-compatible continuous deployments.

## Strict Guidelines
- Engineers MUST NEVER invoke native runtime I/O, native system clocks (Date.now(), new Date()), native timers (setTimeout, setInterval), or native randomness (Math.random(), crypto.randomUUID()) inside workflow definitions.
- Engineers MUST ALWAYS utilize Temporal SDK workflow-safe primitives (@temporalio/workflow: now(), sleep(), condition(), uuid4()) for time tracking, pausing, and deterministic generation.
- Engineers MUST ALWAYS isolate all network requests, database queries, disk operations, and external API mutations within Temporal Activities, invoking them via proxyActivities.
- Engineers MUST ALWAYS gate any control-flow alterations, activity additions, parameter schema shifts, or sequence reorderings within existing workflow definitions using workflow.patched() or workflow.deprecatePatch().
- Services MUST validate modified workflow definitions against exported production workflow history JSON files using the Temporal Replayer in CI pipelines prior to container promotion.
- Components NEVER mutate shared global or process-level state across workflow instances to prevent cross-workflow contamination during multi-tenant worker execution.

## Bad vs Good Implementations
### Non-Deterministic Primitives vs. Temporal Workflow APIs and Patching

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using unversioned new activities, native Date.now(), native setTimeout, and direct network I/O causes immediate event history divergence (NonDeterministicWorkflowError) when workers replay past execution histories, permanently stalling in-flight executions.
```typescript
import { proxyActivities } from '@temporalio/workflow';
import type * as activities from './activities';

const { chargeCard, sendReceipt, fraudCheck } = proxyActivities<typeof activities>({
  startToCloseTimeout: '1 minute',
});

// ANTI-PATTERN: Direct I/O, native clocks/timers, and unversioned structural changes
export async function checkoutWorkflow(cartId: string, amount: number): Promise<void> {
  // Flaw 1: Unversioned new step causes NonDeterministicWorkflowError during replay of historical workflows
  await fraudCheck(cartId);

  // Flaw 2: Native Date.now() produces different timestamps on replay
  const timestamp = Date.now();

  // Flaw 3: Native setTimeout breaks the deterministic virtual event loop
  await new Promise((resolve) => setTimeout(resolve, 5000));

  // Flaw 4: Direct network call inside workflow
  await fetch(`https://metrics.internal/checkout?time=${timestamp}`);

  await chargeCard(cartId, amount);
  await sendReceipt(cartId);
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to Temporal deterministic invariants by using workflow.patched() to branch safely for past executions, workflow.now() for time consistency, workflow.sleep() for durable timers, and offloading all external I/O into activities.
```typescript
import { proxyActivities, patched, sleep, now } from '@temporalio/workflow';
import type * as activities from './activities';

const { chargeCard, sendReceipt, fraudCheck, recordMetric } = proxyActivities<typeof activities>({
  startToCloseTimeout: '1 minute',
});

// PRODUCTION FIX: Deterministic primitives, versioned patching, and activity isolation
export async function checkoutWorkflow(cartId: string, amount: number): Promise<void> {
  // Invariant 1: Gate structural workflow changes with patched() for replay safety
  if (patched('add-fraud-check-v1')) {
    await fraudCheck(cartId);
  }

  // Invariant 2: Deterministic timestamp retrieved from the Workflow execution context
  const deterministicTimestamp = now();

  // Invariant 3: Durable, replay-safe Temporal timer
  await sleep('5 seconds');

  // Invariant 4: Offload side effects and metrics to activities
  await recordMetric({ event: 'checkout', timestamp: deterministicTimestamp });

  await chargeCard(cartId, amount);
  await sendReceipt(cartId);
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Temporal Core Deterministic Workflow Replay & State Machine Verification

Temporal Core Deterministic Workflow Replay & State Machine Verification defines an industrial-grade behavioral standard for backend engineering. Enforces strict determinism constraints within Temporal workflow definitions to eliminate non-deterministic event history divergence and workflow state corruption during replay and continuous deployment cycles. Mandates workflow-safe runtime primitives, isolation of side effects within activities, and explicit version gating with workflow patching APIs. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Non-Deterministic Workflow Mutation and State Corruption via Native Runtime Primitives and Unversioned Control Flow Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftNon-Deterministic Workflow Mutation and State Corruption via Native Runtime Primitives and Unversioned Control FlowCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST NEVER invoke native runtime I/O, native system clocks (Date.now(), new Date()), native timers (setTimeout, setInterval), or native randomness (Math.random(), crypto.randomUUID()) inside workflow definitions.

Engineers MUST NEVER invoke native runtime I/O, native system clocks (Date.now(), new Date()), native timers (setTimeout, setInterval), or native randomness (Math.random(), crypto.randomUUID()) inside workflow definitions.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST ALWAYS utilize Temporal SDK workflow-safe primitives (@temporalio/workflow

Engineers MUST ALWAYS utilize Temporal SDK workflow-safe primitives (@temporalio/workflow: now(), sleep(), condition(), uuid4()) for time tracking, pausing, and deterministic generation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST ALWAYS isolate all network requests, database queries, disk operations, and external API mutations within Temporal Activities, invoking them via proxyActivities.

Engineers MUST ALWAYS isolate all network requests, database queries, disk operations, and external API mutations within Temporal Activities, invoking them via proxyActivities.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Engineers MUST ALWAYS gate any control-flow alterations, activity additions, parameter schema shifts, or sequence reorderings within existing workflow definitions using workflow.patched() or workflow.deprecatePatch().

Engineers MUST ALWAYS gate any control-flow alterations, activity additions, parameter schema shifts, or sequence reorderings within existing workflow definitions using workflow.patched() or workflow.deprecatePatch().

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Services MUST validate modified workflow definitions against exported production workflow history JSON files using the Temporal Replayer in CI pipelines prior to container promotion.

Services MUST validate modified workflow definitions against exported production workflow history JSON files using the Temporal Replayer in CI pipelines prior to container promotion.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Components NEVER mutate shared global or process-level state across workflow instances to prevent cross-workflow contamination during multi-tenant worker execution.

Components NEVER mutate shared global or process-level state across workflow instances to prevent cross-workflow contamination during multi-tenant worker execution.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Temporal Core Deterministic Workflow Replay & State Machine Verification critical for AI coding assistants?

Enforces strict determinism constraints within Temporal workflow definitions to eliminate non-deterministic event history divergence and workflow state corruption during replay and continuous deployment cycles. Mandates workflow-safe runtime primitives, isolation of side effects within activities, and explicit version gating with workflow patching APIs. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Non-Deterministic Workflow Mutation and State Corruption via Native Runtime Primitives and Unversioned Control Flow) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Temporal