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

Temporal SDK Deterministic Workflow Sandboxing & State Replay Invariants

Temporal workflows compute state through deterministic event-sourcing replay; any deviation between execution passes results in a catastrophic NonDeterministicWorkflowError. This standard enforces strict isolation against ambient system clocks, unsandboxed asynchronous timers, random number generation, and external I/O operations inside workflow logic.

Prohibited Anti-Pattern: Executing Ambient Node.js/V8 Non-Deterministic APIs and External Side Effects Inside Workflow Code

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Temporal SDK Deterministic Workflow Sandboxing & State Replay Invariants - Temporal workflows compute state through deterministic event-sourcing replay; any deviation between execution passes results in a catastrophic NonDeterministicWorkflowError. This standard enforces strict isolation against ambient system clocks, unsandboxed asynchronous timers, random number generation, and external I/O operations inside workflow logic.
globs: src/workflows/**/*.{ts,js}, packages/**/workflows/**/*.{ts,js}, apps/**/workflows/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/temporal-workflow-determinism-replay-invariants-temporal-sdk-det-180"
---

# Temporal SDK Deterministic Workflow Sandboxing & State Replay Invariants

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Executing Ambient Node.js/V8 Non-Deterministic APIs and External Side Effects Inside Workflow Code

## System Constraints
You are a Principal Engineer enforcing Temporal SDK Deterministic Workflow Sandboxing & State Replay Invariants. You must enforce zero-tolerance for non-deterministic primitives (Date.now(), Math.random(), crypto, global mutable state, native timers) within workflow definitions. Mandate the use of Temporal Workflow APIs for deterministic replacements, verify activity offloading for all side effects, and require AST-level verification via @temporalio/eslint-plugin.

## Strict Guidelines
- Engineers MUST ALWAYS use @temporalio/workflow determinism primitives (such as workflow.now(), workflow.sleep(), workflow.uuid4(), and workflow.condition()) in place of ambient platform APIs.
- Engineers MUST NOT access ambient runtime globals (Date.now(), new Date(), Math.random(), crypto.randomUUID(), setTimeout, setInterval, setImmediate) inside workflow definition files.
- All network calls, database access, disk I/O, and external mutations MUST be strictly encapsulated within Temporal Activities instantiated through proxyActivities.
- Workflows MUST NOT mutate shared module-scoped or global variables across workflow turns; all workflow state MUST be local to the workflow function scope to prevent state corruption across worker cache evictions.
- Workflow definitions MUST NEVER spawn unmanaged concurrent threads or floating Promises that bypass Temporal's microtask tracking and deadlock detection.
- CI/CD pipelines MUST enforce AST linting via @temporalio/eslint-plugin/workflow to fail builds containing disallowed Node/browser global imports in workflow directories.

## Bad vs Good Implementations
### Ambient Clock and Non-Deterministic UUID Generation vs. Temporal Sandboxed APIs

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly invokes Date.now(), crypto.randomUUID(), and native setTimeout within the workflow body. Uses a mutable module-level variable and executes a raw HTTP fetch. During replay, the values will differ from the original execution, throwing a NonDeterministicWorkflowError and halting the workflow.
```typescript
import { proxyActivities } from '@temporalio/workflow';
import crypto from 'node:crypto';

const activities = proxyActivities({ startToCloseTimeout: '1 minute' });
let executionCounter = 0; // Anti-pattern: global mutable state across workflow replays

export async function orderProcessingWorkflow(orderId: string): Promise<void> {
  executionCounter++;
  
  // Non-deterministic: System clock and crypto change on every replay pass
  const timestamp = Date.now();
  const idempotencyKey = crypto.randomUUID();
  
  // Non-deterministic: Native setTimeout breaks the workflow event loop
  await new Promise((resolve) => setTimeout(resolve, 5000));
  
  // Non-deterministic: Direct network or un-proxied I/O within workflow body
  await fetch(`https://api.inventory.internal/reservations/${orderId}`, {
    method: 'POST',
    body: JSON.stringify({ idempotencyKey, timestamp }),
  });
}
```

#### Production Standard (Correct)
> **Standard**: Replaces raw ambient calls with @temporalio/workflow deterministic utilities (uuid4(), sleep(), workflowInfo()). All external I/O and side effects are offloaded to proxyActivities, allowing the workflow to deterministically replay from its history.
```typescript
import {
  proxyActivities,
  sleep,
  workflowInfo,
  uuid4,
} from '@temporalio/workflow';
import type * as activities from '../activities';

const { reserveInventory } = proxyActivities<typeof activities>({
  startToCloseTimeout: '1 minute',
  retry: {
    maximumAttempts: 5,
  },
});

export async function orderProcessingWorkflow(orderId: string): Promise<void> {
  // Deterministic: Provided by Temporal event history during replay
  const idempotencyKey = uuid4();
  const info = workflowInfo();
  
  // Deterministic durable timer: Emits a TimerStarted / TimerFired event
  await sleep('5 seconds');
  
  // Deterministic side effect: Delegated to an external activity
  await reserveInventory({
    orderId,
    idempotencyKey,
    workflowExecutionId: info.workflowId,
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Temporal SDK Deterministic Workflow Sandboxing & State Replay Invariants

Temporal SDK Deterministic Workflow Sandboxing & State Replay Invariants defines an industrial-grade behavioral standard for backend engineering. Temporal workflows compute state through deterministic event-sourcing replay; any deviation between execution passes results in a catastrophic NonDeterministicWorkflowError. This standard enforces strict isolation against ambient system clocks, unsandboxed asynchronous timers, random number generation, and external I/O operations inside workflow logic. 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: Executing Ambient Node.js/V8 Non-Deterministic APIs and External Side Effects Inside Workflow Code 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 DriftExecuting Ambient Node.js/V8 Non-Deterministic APIs and External Side Effects Inside Workflow CodeCritical
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 ALWAYS use @temporalio/workflow determinism primitives (such as workflow.now(), workflow.sleep(), workflow.uuid4(), and workflow.condition()) in place of ambient platform APIs.

Engineers MUST ALWAYS use @temporalio/workflow determinism primitives (such as workflow.now(), workflow.sleep(), workflow.uuid4(), and workflow.condition()) in place of ambient platform APIs.

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 NOT access ambient runtime globals (Date.now(), new Date(), Math.random(), crypto.randomUUID(), setTimeout, setInterval, setImmediate) inside workflow definition files.

Engineers MUST NOT access ambient runtime globals (Date.now(), new Date(), Math.random(), crypto.randomUUID(), setTimeout, setInterval, setImmediate) inside workflow definition files.

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

All network calls, database access, disk I/O, and external mutations MUST be strictly encapsulated within Temporal Activities instantiated through proxyActivities.

All network calls, database access, disk I/O, and external mutations MUST be strictly encapsulated within Temporal Activities instantiated through 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

Workflows MUST NOT mutate shared module-scoped or global variables across workflow turns

Workflows MUST NOT mutate shared module-scoped or global variables across workflow turns; all workflow state MUST be local to the workflow function scope to prevent state corruption across worker cache evictions.

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

Workflow definitions MUST NEVER spawn unmanaged concurrent threads or floating Promises that bypass Temporal's microtask tracking and deadlock detection.

Workflow definitions MUST NEVER spawn unmanaged concurrent threads or floating Promises that bypass Temporal's microtask tracking and deadlock detection.

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

CI/CD pipelines MUST enforce AST linting via @temporalio/eslint-plugin/workflow to fail builds containing disallowed Node/browser global imports in workflow directories.

CI/CD pipelines MUST enforce AST linting via @temporalio/eslint-plugin/workflow to fail builds containing disallowed Node/browser global imports in workflow directories.

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 SDK Deterministic Workflow Sandboxing & State Replay Invariants critical for AI coding assistants?

Temporal workflows compute state through deterministic event-sourcing replay; any deviation between execution passes results in a catastrophic NonDeterministicWorkflowError. This standard enforces strict isolation against ambient system clocks, unsandboxed asynchronous timers, random number generation, and external I/O operations inside workflow logic. 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 (Executing Ambient Node.js/V8 Non-Deterministic APIs and External Side Effects Inside Workflow Code) 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