This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: svelte-5-runes-cyclic-mutation-fence

Svelte 5 Runes Reactive Graph Cyclic Mutation Fence

Enforces strict computation purity within Svelte 5 `$derived` and `$derived.by` runes to safeguard the push-pull reactive graph. Unbatched signal mutations, deep object state writes, and implicit side effects within derived calculations cause dependency graph thrashing, non-deterministic re-evaluations, and catastrophic circular update loops in complex single-page architectures. Computations must remain referentially transparent projections of state, offloading mutations exclusively to explicit user event handlers or untracked `$effect` fences.

Prohibited Anti-Pattern: Mutating Root or Proxied $state Signals Directly Inside $derived Computations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Reactive Graph Cyclic Mutation Fence - Enforces strict computation purity within Svelte 5 `$derived` and `$derived.by` runes to safeguard the push-pull reactive graph. Unbatched signal mutations, deep object state writes, and implicit side effects within derived calculations cause dependency graph thrashing, non-deterministic re-evaluations, and catastrophic circular update loops in complex single-page architectures. Computations must remain referentially transparent projections of state, offloading mutations exclusively to explicit user event handlers or untracked `$effect` fences.
globs: src/**/*.{svelte,svelte.ts,svelte.js,ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/svelte-5-runes-cyclic-mutation-fence"
---

# Svelte 5 Runes Reactive Graph Cyclic Mutation Fence

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Mutating Root or Proxied $state Signals Directly Inside $derived Computations

## System Constraints
You are a Principal Frontend Architect enforcing the Svelte 5 Runes Reactive Graph Cyclic Mutation Fence. Svelte 5 introduces fine-grained reactive primitives ($state, $derived, $effect) governed by a directed acyclic graph (DAG). You must enforce zero-tolerance for state mutation inside `$derived` or `$derived.by` scopes. Derived computations must be purely functional, synchronous, and side-effect free. Reject any pull-phase mutation that invalidates dependencies during graph traversal, and guarantee state transition boundaries are kept inside discrete, untracked effects or synchronous user dispatchers.

## Strict Guidelines
- Engineers MUST ALWAYS keep `$derived` and `$derived.by` expressions completely pure, deterministic, and free of side effects.
- Engineers MUST NOT write to `$state` primitives, proxy fields, arrays, or deep reactive maps within a `$derived` evaluation context.
- Engineers MUST NOT trigger functions from within `$derived` that modify global, module-level, or contextual reactive states.
- Code SHOULD leverage `$derived.by` strictly for multi-step synchronous transformations that return newly computed values without modifying source signals.
- Services MUST isolate telemetry logging, external synchronizations, and dependent mutations inside `$effect` blocks, utilizing `untrack()` when reading volatile signals that must not register as dependencies.
- Components NEVER execute asynchronous operations, cache write-backs, or DOM mutations inside derived runes.

## Bad vs Good Implementations
### Anti-Pattern: Mutating Reactive State Inside $derived.by Generating Cyclic Graph Thrashing

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating `totalSelectedCount` inside `$derived.by` directly invalidates a reactive signal while the graph is executing a pull-based derived computation. If another derived rune or effect depends on both `cartSummary` and `totalSelectedCount`, Svelte throws a cyclic dependency error (ERR_SVELTE_REACTIVE_CYCLE) or enters an infinite microtask thrashing cycle.
```typescript
import { untrack } from 'svelte';

// Anti-pattern: Modifying $state inside derived calculation
let items = $state<Array<{ id: string; price: number; selected: boolean }>>([
  { id: '1', price: 100, selected: false }
]);
let totalSelectedCount = $state(0);

// CRITICAL FLAW: Writing to totalSelectedCount inside $derived triggers graph churn
export const cartSummary = $derived.by(() => {
  let subtotal = 0;
  let selectedCount = 0;

  for (const item of items) {
    if (item.selected) {
      subtotal += item.price;
      selectedCount++;
    }
  }

  // Mutating signal during DAG pull phase triggers cyclic updates
  totalSelectedCount = selectedCount;

  return {
    subtotal,
    itemCount: items.length,
    tax: subtotal * 0.1
  };
});
```

#### Production Standard (Correct)
> **Standard**: Derived state is computed as a pure projection of the canonical `items` signal. `totalSelectedCount` is modeled as a secondary pure derivation rather than a mutated signal. The DAG remains strictly acyclic, free of side effects and redundant recalculations.
```typescript
import { untrack } from 'svelte';

// Invariant Compliant: Derivations project state without side-effects
let items = $state<Array<{ id: string; price: number; selected: boolean }>>([
  { id: '1', price: 100, selected: false }
]);

// Project both metrics derived purely from the source state
export const cartMetrics = $derived.by(() => {
  let subtotal = 0;
  let selectedCount = 0;

  for (const item of items) {
    if (item.selected) {
      subtotal += item.price;
      selectedCount++;
    }
  }

  return {
    subtotal,
    selectedCount,
    itemCount: items.length,
    tax: Number((subtotal * 0.1).toFixed(2))
  };
});

// Explicit accessor prevents downstream signal churn
export const totalSelectedCount = $derived(cartMetrics.selectedCount);
```

### Anti-Pattern: In-Place Deep Mutation of Proxied Collection During Filtering

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Modifying properties on `row` (which is tracked by Svelte 5's fine-grained proxy runtime) inside `$derived.by` invalidates the collection mid-traversal. This dirties `this.data`, immediately scheduling another evaluation of `visibleRows` and causing an infinite execution loop.
```typescript
class TableStore {
  data = $state<Array<{ id: string; tags: string[]; normalized?: boolean }>>([]);
  filterTag = $state('active');

  // Anti-pattern: In-place deep mutation of proxy target inside derived computation
  visibleRows = $derived.by(() => {
    return this.data.filter((row) => {
      if (!row.normalized) {
        // Deep signal mutation inside read graph traversal
        row.normalized = true;
        row.tags.push('audited');
      }
      return row.tags.includes(this.filterTag);
    });
  });
}
```

#### Production Standard (Correct)
> **Standard**: The store enforces immutable read semantics using TypeScript readonly constraints. The derivation produces clean structural clones for unnormalized rows without modifying existing reactive proxy nodes, preserving DAG stability.
```typescript
class TableStore {
  data = $state<ReadonlyArray<{ readonly id: string; readonly tags: readonly string[]; readonly normalized?: boolean }>>([]);
  filterTag = $state('active');

  // Invariant Compliant: Pure structural mapping with immutable projections
  visibleRows = $derived.by(() => {
    const activeFilter = this.filterTag;
    return this.data
      .map((row) => {
        if (!row.normalized) {
          return {
            ...row,
            normalized: true,
            tags: [...row.tags, 'audited']
          };
        }
        return row;
      })
      .filter((row) => row.tags.includes(activeFilter));
  });
}
```

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: Svelte 5 Runes Reactive Graph Cyclic Mutation Fence

Svelte 5 Runes Reactive Graph Cyclic Mutation Fence defines an industrial-grade behavioral standard for frontend engineering. Enforces strict computation purity within Svelte 5 `$derived` and `$derived.by` runes to safeguard the push-pull reactive graph. Unbatched signal mutations, deep object state writes, and implicit side effects within derived calculations cause dependency graph thrashing, non-deterministic re-evaluations, and catastrophic circular update loops in complex single-page architectures. Computations must remain referentially transparent projections of state, offloading mutations exclusively to explicit user event handlers or untracked `$effect` fences. 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: Mutating Root or Proxied $state Signals Directly Inside $derived Computations 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 DriftMutating Root or Proxied $state Signals Directly Inside $derived ComputationsCritical
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 keep `$derived` and `$derived.by` expressions completely pure, deterministic, and free of side effects.

Engineers MUST ALWAYS keep `$derived` and `$derived.by` expressions completely pure, deterministic, and free of side effects.

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 write to `$state` primitives, proxy fields, arrays, or deep reactive maps within a `$derived` evaluation context.

Engineers MUST NOT write to `$state` primitives, proxy fields, arrays, or deep reactive maps within a `$derived` evaluation context.

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 NOT trigger functions from within `$derived` that modify global, module-level, or contextual reactive states.

Engineers MUST NOT trigger functions from within `$derived` that modify global, module-level, or contextual reactive states.

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

Code SHOULD leverage `$derived.by` strictly for multi-step synchronous transformations that return newly computed values without modifying source signals.

Code SHOULD leverage `$derived.by` strictly for multi-step synchronous transformations that return newly computed values without modifying source signals.

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 isolate telemetry logging, external synchronizations, and dependent mutations inside `$effect` blocks, utilizing `untrack()` when reading volatile signals that must not register as dependencies.

Services MUST isolate telemetry logging, external synchronizations, and dependent mutations inside `$effect` blocks, utilizing `untrack()` when reading volatile signals that must not register as dependencies.

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 execute asynchronous operations, cache write-backs, or DOM mutations inside derived runes.

Components NEVER execute asynchronous operations, cache write-backs, or DOM mutations inside derived runes.

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 Svelte 5 Runes Reactive Graph Cyclic Mutation Fence critical for AI coding assistants?

Enforces strict computation purity within Svelte 5 `$derived` and `$derived.by` runes to safeguard the push-pull reactive graph. Unbatched signal mutations, deep object state writes, and implicit side effects within derived calculations cause dependency graph thrashing, non-deterministic re-evaluations, and catastrophic circular update loops in complex single-page architectures. Computations must remain referentially transparent projections of state, offloading mutations exclusively to explicit user event handlers or untracked `$effect` fences. 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 (Mutating Root or Proxied $state Signals Directly Inside $derived Computations) 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.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

Svelte