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

Svelte 5 Runes Reactive Isolation & High-Frequency State Invariant

Enforces deterministic boundaries between fine-grained reactive state ($state) and high-frequency or deeply nested external datasets ($state.raw). Prevents infinite cross-component render loops, memory exhaustion from recursive Proxy wrapping, and cascading downstream recalculations.

Prohibited Anti-Pattern: Wrapping High-Frequency Telemetry in Deep $state Proxies with Bidirectional Effect Feedback

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Reactive Isolation & High-Frequency State Invariant - Enforces deterministic boundaries between fine-grained reactive state ($state) and high-frequency or deeply nested external datasets ($state.raw). Prevents infinite cross-component render loops, memory exhaustion from recursive Proxy wrapping, and cascading downstream recalculations.
globs: src/**/*.svelte, src/**/*.svelte.ts, src/**/*.svelte.js
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/svelte-5-runes-reactive-isolation-standard"
---

# Svelte 5 Runes Reactive Isolation & High-Frequency State Invariant

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Wrapping High-Frequency Telemetry in Deep $state Proxies with Bidirectional Effect Feedback

## System Constraints
You are a Principal Engineer enforcing the Svelte 5 Runes Reactive Isolation Standard. Svelte 5 replaces stores with explicit compiler runes ($state, $state.raw, $derived, $effect). Deep reactive proxies created by $state introduce unacceptable GC overhead and circular trigger hazards when exposed to high-frequency streaming (e.g., WebSockets, Canvas/WebGL loops, telemetry). You must enforce $state.raw for high-frequency or external payloads, strict reference-replacement semantics, and non-reactive reads via untrack() to prevent infinite cascade loops.

## Strict Guidelines
- Engineers MUST ALWAYS use $state.raw() instead of $state() for high-frequency streaming payloads (e.g., WebSockets, sensors, WebRTC, animation frames) to prevent recursive Proxy wrapping.
- Engineers MUST NEVER mutate nested properties of a $state.raw() object; updates MUST be applied via atomic reference reassignment (e.g., state = Object.freeze({ ...state, update })).
- Engineers MUST ALWAYS isolate cyclical reads within $effect or $effect.pre using untrack() when synchronizing local state with upstream rune-based properties.
- Code SHOULD prefer $derived.by() for expensive transformations, isolating volatile reference updates from invariant sub-branches of the component tree.
- Services MUST NEVER expose deeply mutable $state instances directly to consuming components; wrap mutations in explicit command methods or emit immutable snapshots via $state.raw.
- Components NEVER bind two-way ($bindable) to non-primitive leaves of deep $state structures across architectural boundaries.

## Bad vs Good Implementations
### High-Frequency Stream Synchronization: Deep $state vs. $state.raw with untrack

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using $state on high-frequency stream targets creates a deep tree of reactive Proxies. Mutating nested arrays pushes change notifications through all proxy levels on every tick. Inside $effect, mutating tracked dependencies causes an immediate infinite re-render loop.
```typescript
import { $state, $effect } from 'svelte';

// ANTI-PATTERN: Wrapping 60Hz telemetry in deep reactive proxy
// and mutating in an unshielded effect loop
interface Telemetry { id: string; metrics: { cpu: number[]; memory: number } }

export class TelemetryBridge {
  // Anti-pattern: Deep proxy created on complex, rapidly changing object
  data = $state<Telemetry>({ id: 'node-1', metrics: { cpu: [], memory: 0 } });

  constructor(socket: WebSocket) {
    socket.onmessage = (event) => {
      const payload = JSON.parse(event.data);
      // Anti-pattern: In-place mutation triggers recursive proxy traps on every frame
      this.data.metrics.cpu.push(payload.cpu);
      this.data.metrics.memory = payload.memory;
    };
  }
}

export function syncTelemetry(bridge: TelemetryBridge, onThreshold: (val: number) => void) {
  $effect(() => {
    // Anti-pattern: Reading deep properties creates an implicit dependency
    // Mutating bridge data here creates an immediate circular cascade
    if (bridge.data.metrics.memory > 90) {
      onThreshold(bridge.data.metrics.memory);
      bridge.data.id = 'warning-' + bridge.data.id; // Triggers infinite effect cycle
    }
  });
}
```

#### Production Standard (Correct)
> **Standard**: $state.raw creates a zero-proxy-overhead shallow reactive signal. High-frequency payloads are updated via full object reference replacement. Reading the snapshot inside $effect and isolating operational callbacks via untrack() avoids infinite cyclical reactive invalidations.
```typescript
import { untrack } from 'svelte';

interface Telemetry { readonly id: string; readonly metrics: { readonly cpu: readonly number[]; readonly memory: number } }

export class TelemetryBridge {
  // Invariant: Use $state.raw for high-frequency or reference-swapped state
  data = $state.raw<Telemetry>({ id: 'node-1', metrics: { cpu: [], memory: 0 } });

  constructor(socket: WebSocket) {
    socket.onmessage = (event) => {
      const payload = JSON.parse(event.data);
      // Invariant: Atomic immutable replacement; bypasses proxy traversal
      this.data = {
        id: this.data.id,
        metrics: {
          cpu: [...this.data.metrics.cpu.slice(-50), payload.cpu],
          memory: payload.memory
        }
      };
    };
  }
}

export function syncTelemetry(bridge: TelemetryBridge, onThreshold: (val: number) => void) {
  $effect(() => {
    // Invariant: Read only what determines reactivity
    const current = bridge.data;

    // Invariant: Isolate side-effects and subsequent reads using untrack()
    untrack(() => {
      if (current.metrics.memory > 90) {
        onThreshold(current.metrics.memory);
      }
    });
  });
}
```

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 Isolation & High-Frequency State Invariant

Svelte 5 Runes Reactive Isolation & High-Frequency State Invariant defines an industrial-grade behavioral standard for frontend engineering. Enforces deterministic boundaries between fine-grained reactive state ($state) and high-frequency or deeply nested external datasets ($state.raw). Prevents infinite cross-component render loops, memory exhaustion from recursive Proxy wrapping, and cascading downstream recalculations. 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: Wrapping High-Frequency Telemetry in Deep $state Proxies with Bidirectional Effect Feedback 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 DriftWrapping High-Frequency Telemetry in Deep $state Proxies with Bidirectional Effect FeedbackCritical
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 $state.raw() instead of $state() for high-frequency streaming payloads (e.g., WebSockets, sensors, WebRTC, animation frames) to prevent recursive Proxy wrapping.

Engineers MUST ALWAYS use $state.raw() instead of $state() for high-frequency streaming payloads (e.g., WebSockets, sensors, WebRTC, animation frames) to prevent recursive Proxy wrapping.

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 NEVER mutate nested properties of a $state.raw() object

Engineers MUST NEVER mutate nested properties of a $state.raw() object; updates MUST be applied via atomic reference reassignment (e.g., state = Object.freeze({ ...state, update })).

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 cyclical reads within $effect or $effect.pre using untrack() when synchronizing local state with upstream rune-based properties.

Engineers MUST ALWAYS isolate cyclical reads within $effect or $effect.pre using untrack() when synchronizing local state with upstream rune-based properties.

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 prefer $derived.by() for expensive transformations, isolating volatile reference updates from invariant sub-branches of the component tree.

Code SHOULD prefer $derived.by() for expensive transformations, isolating volatile reference updates from invariant sub-branches of the component tree.

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 NEVER expose deeply mutable $state instances directly to consuming components

Services MUST NEVER expose deeply mutable $state instances directly to consuming components; wrap mutations in explicit command methods or emit immutable snapshots via $state.raw.

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 bind two-way ($bindable) to non-primitive leaves of deep $state structures across architectural boundaries.

Components NEVER bind two-way ($bindable) to non-primitive leaves of deep $state structures across architectural boundaries.

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 Isolation & High-Frequency State Invariant critical for AI coding assistants?

Enforces deterministic boundaries between fine-grained reactive state ($state) and high-frequency or deeply nested external datasets ($state.raw). Prevents infinite cross-component render loops, memory exhaustion from recursive Proxy wrapping, and cascading downstream recalculations. 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 (Wrapping High-Frequency Telemetry in Deep $state Proxies with Bidirectional Effect Feedback) 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