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

Svelte 5 Universal Runes Encapsulation & Reactivity Boundary Standard

Enforces strict fine-grained reactivity boundaries in Svelte 5 by restricting universal runes ($state, $derived, $effect) to component contexts and explicit .svelte.ts module encapsulations. Prohibits global state mutation leaks, naked reactive primitives across module boundaries, and unencapsulated reactive destructuring that triggers unintended render cascades and memory retention.

Prohibited Anti-Pattern: Exposing Raw Runes Across Shared TS Modules Causing Reactivity Bleed and Infinite Update Cycles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Universal Runes Encapsulation & Reactivity Boundary Standard - Enforces strict fine-grained reactivity boundaries in Svelte 5 by restricting universal runes ($state, $derived, $effect) to component contexts and explicit .svelte.ts module encapsulations. Prohibits global state mutation leaks, naked reactive primitives across module boundaries, and unencapsulated reactive destructuring that triggers unintended render cascades and memory retention.
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-universal-runes-encapsulation-standard"
---

# Svelte 5 Universal Runes Encapsulation & Reactivity Boundary Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Exposing Raw Runes Across Shared TS Modules Causing Reactivity Bleed and Infinite Update Cycles

## System Constraints
You are a Principal Frontend Architect enforcing the Svelte 5 Universal Runes Encapsulation Standard. You must mandate strict state isolation, require class-based or closure-encapsulated runes in '.svelte.ts' files, forbid destructuring of reactive state that severs reactive tracking, and eradicate uncontrolled effects or legacy Svelte 4 store patterns.

## Strict Guidelines
- Engineers MUST ALWAYS isolate universal runes ($state, $derived) within '.svelte' components or '.svelte.ts' modules; runes are invalid and prohibited in standard '.ts' files.
- Engineers MUST encapsulate shared state within explicit TypeScript classes or factory functions exposing getters and immutable/action methods, rather than exporting raw '$state' bindings.
- Engineers MUST NOT destructure properties directly from '$state' objects or class instances, as destructuring tears the reactive reference and produces dead, non-updating local variables.
- Components NEVER use '$effect' for derived state calculations; engineers MUST use '$derived' or '$derived.by' to maintain synchronous, memoized reactive DAG integrity without cascading microtask renders.
- Engineers MUST explicitly clean up side effects created inside '$effect' by returning a teardown function, and MUST NOT instantiate top-level '$effect' within root module scopes.
- Engineers MUST use '$state.raw()' when handling large immutable datasets, external libraries, or complex third-party class instances to bypass deep proxy overhead.

## Bad vs Good Implementations
### Module State Encapsulation: Naked State Export vs. Encapsulated Class Model

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exporting raw $state variables from a module exposes mutable internals, enables uncontrolled mutations across disconnected boundaries, and causes reactivity loss if imported via aliasing or destructuring.
```typescript
// counter.svelte.ts - Anti-pattern: Exporting raw mutable runes
export let count = $state(0);

export function increment() {
  count += 1;
}

// ConsumerComponent.svelte
// <script lang="ts">
//   import { count, increment } from './counter.svelte';
//   // Destructuring breaks reactivity; raw binding can be reassigned externally
//   let myCount = count;
// </script>
```

#### Production Standard (Correct)
> **Standard**: Encapsulating rune state within a class with private fields (#count) guarantees encapsulation, preserves accessor-driven fine-grained reactivity, and prevents callers from severing proxy boundaries.
```typescript
// counter.svelte.ts - Production standard: Class-based reactive boundary
export class CounterState {
  #count = $state<number>(0);
  readonly step: number;

  constructor(initial = 0, step = 1) {
    this.#count = initial;
    this.step = step;
  }

  get value(): number {
    return this.#count;
  }

  get isDoubled(): number {
    return this.#count * 2;
  }

  increment(): void {
    this.#count += this.step;
  }

  reset(): void {
    this.#count = 0;
  }
}

export const counter = new CounterState();
```

### Derived Computations: Side-Effect Cascades vs. Synchronous $derived.by

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using $effect to synchronize reactive values causes layout thrashing, secondary tick mutations, and unpredictable ordering in Svelte 5's push-pull reactivity model.
```typescript
// ProfileViewer.svelte - Anti-pattern: Using $effect for derived computations
let users = $state<Array<{ id: string; active: boolean; score: number }>>([]);
let topActiveScore = $state<number>(0);

// Triggers extra render cycle, risks infinite loop on self-invalidation
$effect(() => {
  const activeScores = users.filter((u) => u.active).map((u) => u.score);
  topActiveScore = activeScores.length > 0 ? Math.max(...activeScores) : 0;
});
```

#### Production Standard (Correct)
> **Standard**: The $derived.by rune evaluates synchronously within the reactive dependency graph, executes only when upstream dependencies alter, and emits zero additional render ticks.
```typescript
// ProfileViewer.svelte - Production standard: Synchronous $derived.by
interface User {
  id: string;
  active: boolean;
  score: number;
}

let users = $state<User[]>([]);

const topActiveScore = $derived.by<number>(() => {
  const activeScores = users.filter((u) => u.active).map((u) => u.score);
  return activeScores.length > 0 ? Math.max(...activeScores) : 0;
});
```

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 Universal Runes Encapsulation & Reactivity Boundary Standard

Svelte 5 Universal Runes Encapsulation & Reactivity Boundary Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces strict fine-grained reactivity boundaries in Svelte 5 by restricting universal runes ($state, $derived, $effect) to component contexts and explicit .svelte.ts module encapsulations. Prohibits global state mutation leaks, naked reactive primitives across module boundaries, and unencapsulated reactive destructuring that triggers unintended render cascades and memory retention. 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: Exposing Raw Runes Across Shared TS Modules Causing Reactivity Bleed and Infinite Update Cycles 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 DriftExposing Raw Runes Across Shared TS Modules Causing Reactivity Bleed and Infinite Update CyclesCritical
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 isolate universal runes ($state, $derived) within '.svelte' components or '.svelte.ts' modules

Engineers MUST ALWAYS isolate universal runes ($state, $derived) within '.svelte' components or '.svelte.ts' modules; runes are invalid and prohibited in standard '.ts' 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.
2

Engineers MUST encapsulate shared state within explicit TypeScript classes or factory functions exposing getters and immutable/action methods, rather than exporting raw '$state' bindings.

Engineers MUST encapsulate shared state within explicit TypeScript classes or factory functions exposing getters and immutable/action methods, rather than exporting raw '$state' bindings.

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 destructure properties directly from '$state' objects or class instances, as destructuring tears the reactive reference and produces dead, non-updating local variables.

Engineers MUST NOT destructure properties directly from '$state' objects or class instances, as destructuring tears the reactive reference and produces dead, non-updating local variables.

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

Components NEVER use '$effect' for derived state calculations

Components NEVER use '$effect' for derived state calculations; engineers MUST use '$derived' or '$derived.by' to maintain synchronous, memoized reactive DAG integrity without cascading microtask renders.

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

Engineers MUST explicitly clean up side effects created inside '$effect' by returning a teardown function, and MUST NOT instantiate top-level '$effect' within root module scopes.

Engineers MUST explicitly clean up side effects created inside '$effect' by returning a teardown function, and MUST NOT instantiate top-level '$effect' within root module scopes.

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

Engineers MUST use '$state.raw()' when handling large immutable datasets, external libraries, or complex third-party class instances to bypass deep proxy overhead.

Engineers MUST use '$state.raw()' when handling large immutable datasets, external libraries, or complex third-party class instances to bypass deep proxy overhead.

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 Universal Runes Encapsulation & Reactivity Boundary Standard critical for AI coding assistants?

Enforces strict fine-grained reactivity boundaries in Svelte 5 by restricting universal runes ($state, $derived, $effect) to component contexts and explicit .svelte.ts module encapsulations. Prohibits global state mutation leaks, naked reactive primitives across module boundaries, and unencapsulated reactive destructuring that triggers unintended render cascades and memory retention. 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 (Exposing Raw Runes Across Shared TS Modules Causing Reactivity Bleed and Infinite Update Cycles) 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