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

Svelte 5 Runes Fine-Grained Reactive Proxy Isolation and Boundary Enforcement

Enforces strict boundary encapsulation for Svelte 5 reactive proxies created by $state() in complex, state-driven dashboards. Eliminates cross-component mutable proxy leaks, unbounded deep dependency graph traversal in effects, and memory leaks by mandating $state.raw(), $state.snapshot(), and encapsulated domain stores.

Prohibited Anti-Pattern: Uncontained Cross-Component Reactive Proxy Passing and Deep Effect Signal Pollution

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Fine-Grained Reactive Proxy Isolation and Boundary Enforcement - Enforces strict boundary encapsulation for Svelte 5 reactive proxies created by $state() in complex, state-driven dashboards. Eliminates cross-component mutable proxy leaks, unbounded deep dependency graph traversal in effects, and memory leaks by mandating $state.raw(), $state.snapshot(), and encapsulated domain stores.
globs: src/**/*.{svelte,svelte.ts,svelte.js,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/svelte-5-runes-reactive-proxy-isolation"
---

# Svelte 5 Runes Fine-Grained Reactive Proxy Isolation and Boundary Enforcement

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Uncontained Cross-Component Reactive Proxy Passing and Deep Effect Signal Pollution

## System Constraints
You are a Principal Software Architect enforcing Svelte 5 Runes Fine-Grained Reactive Proxy Isolation. Svelte 5 replaces compile-time top-level invalidations with runtime fine-grained signal proxies. Unrestricted propagation of `$state()` deep proxies across component hierarchies creates hidden two-way coupling, uncollected deep dependency tracking in `$effect` blocks, and severe frame-rate degradation in analytical dashboards. You must enforce strict architectural boundaries between reactive state ownership, read-only consumer projections, and non-reactive external consumers.

## Strict Guidelines
- Engineers MUST ALWAYS wrap bulk metrics, geoJSON, chart data, or immutable tabular datasets in `$state.raw()` rather than `$state()` to eliminate recursive reactive proxy creation overhead.
- Engineers MUST NOT pass raw mutable `$state()` proxies to child components as props where direct property mutation is possible; consumer updates must be mediated through unidirectional callbacks or domain store methods.
- Code MUST use `$state.snapshot()` when passing reactive data to third-party imperative APIs (e.g., ECharts, D3, Canvas renderers, Web Workers) to sever proxy interception and eliminate memory leaks caused by lingering signal references.
- Stores MUST encapsulate internal `$state()` properties within private class fields (`#state`) or closures, exposing only read-only projections or explicit updater methods to consumers.
- Components NEVER reference top-level proxy roots inside `$effect` when only specific scalar fields are required; dependencies MUST be narrowed using `$derived` projections to prevent cascading effect thrashing.

## Bad vs Good Implementations
### Cross-Component State Leak and External Consumer Signal Contamination

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exporting bare mutable proxies via `$state()` allows consumers to perform out-of-band mutations. Passing reactive proxy arrays into external DOM/Canvas libraries like ECharts establishes hidden signal tracking that breaks garbage collection, and referencing the whole proxy array in `$effect` triggers O(N) dependency re-calculations whenever any point changes.
```typescript
// stores/dashboard.svelte.ts
export interface MetricPoint {
  timestamp: number;
  value: number;
}

// ANTI-PATTERN: Deep reactive proxy exported globally without encapsulation.
// Allows external components to mutate nested values directly, corrupting state history.
export const dashboardState = $state({
  metrics: [] as MetricPoint[],
  selectedWindow: '24h'
});

// components/MetricChart.svelte
// <script lang="ts">
// import { dashboardState } from '../stores/dashboard.svelte';
// import * as echarts from 'echarts';
// let chartInstance: echarts.ECharts;

// ANTI-PATTERN 1: Reading entire reactive proxy inside an effect creates deep dependency tracking
// for every metric point, triggering complete re-renders on arbitrary single-item edits.
// ANTI-PATTERN 2: Passing raw reactive proxy into external charting engine leaks Svelte proxies 
// into canvas render loops, causing memory retention.
// $effect(() => {
//   chartInstance.setOption({
//     series: [{ data: dashboardState.metrics }]
//   });
// });
// </script>
```

#### Production Standard (Correct)
> **Standard**: Encapsulating state in a class store with `#metrics = $state.raw(...)` eliminates recursive proxy overhead for telemetry. Mutations are strictly controlled through domain methods. `$state.snapshot()` strips all Svelte runtime signals before data enters the third-party library, preventing memory leaks and uncollected subscriptions.
```typescript
// stores/dashboard.svelte.ts
export interface MetricPoint {
  readonly timestamp: number;
  readonly value: number;
}

export class DashboardStore {
  // Invariant 1: Large telemetry datasets are raw; skip deep proxy wrapping
  #metrics = $state.raw<readonly MetricPoint[]>([]);
  #selectedWindow = $state<string>('24h');

  // Invariant 2: Expose state via read-only accessors
  get metrics(): readonly MetricPoint[] {
    return this.#metrics;
  }

  get selectedWindow(): string {
    return this.#selectedWindow;
  }

  // Invariant 3: Explicit transactional mutations
  setWindow(window: string): void {
    this.#selectedWindow = window;
  }

  updateTelemetry(batch: MetricPoint[]): void {
    // Replace reference cleanly without deep proxy diffing overhead
    this.#metrics = Object.freeze([...batch]);
  }
}

export const dashboardStore = new DashboardStore();

// components/MetricChart.svelte
// <script lang="ts">
// import { dashboardStore } from '../stores/dashboard.svelte';
// import * as echarts from 'echarts';
// let chartInstance: echarts.ECharts;

// Invariant 4: Derive explicit primitive or clean array projections
// Invariant 5: Sever reactive tracking before external library ingestion using $state.snapshot
// $effect(() => {
//   const snapshotData = $state.snapshot(dashboardStore.metrics);
//   chartInstance.setOption({
//     series: [{ data: snapshotData }]
//   });
// });
// </script>
```

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 Fine-Grained Reactive Proxy Isolation and Boundary Enforcement

Svelte 5 Runes Fine-Grained Reactive Proxy Isolation and Boundary Enforcement defines an industrial-grade behavioral standard for frontend engineering. Enforces strict boundary encapsulation for Svelte 5 reactive proxies created by $state() in complex, state-driven dashboards. Eliminates cross-component mutable proxy leaks, unbounded deep dependency graph traversal in effects, and memory leaks by mandating $state.raw(), $state.snapshot(), and encapsulated domain stores. 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: Uncontained Cross-Component Reactive Proxy Passing and Deep Effect Signal Pollution 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 DriftUncontained Cross-Component Reactive Proxy Passing and Deep Effect Signal PollutionCritical
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 wrap bulk metrics, geoJSON, chart data, or immutable tabular datasets in `$state.raw()` rather than `$state()` to eliminate recursive reactive proxy creation overhead.

Engineers MUST ALWAYS wrap bulk metrics, geoJSON, chart data, or immutable tabular datasets in `$state.raw()` rather than `$state()` to eliminate recursive reactive proxy creation 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.
2

Engineers MUST NOT pass raw mutable `$state()` proxies to child components as props where direct property mutation is possible

Engineers MUST NOT pass raw mutable `$state()` proxies to child components as props where direct property mutation is possible; consumer updates must be mediated through unidirectional callbacks or domain store methods.

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

Code MUST use `$state.snapshot()` when passing reactive data to third-party imperative APIs (e.g., ECharts, D3, Canvas renderers, Web Workers) to sever proxy interception and eliminate memory leaks caused by lingering signal references.

Code MUST use `$state.snapshot()` when passing reactive data to third-party imperative APIs (e.g., ECharts, D3, Canvas renderers, Web Workers) to sever proxy interception and eliminate memory leaks caused by lingering signal references.

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

Stores MUST encapsulate internal `$state()` properties within private class fields (`#state`) or closures, exposing only read-only projections or explicit updater methods to consumers.

Stores MUST encapsulate internal `$state()` properties within private class fields (`#state`) or closures, exposing only read-only projections or explicit updater methods to consumers.

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

Components NEVER reference top-level proxy roots inside `$effect` when only specific scalar fields are required

Components NEVER reference top-level proxy roots inside `$effect` when only specific scalar fields are required; dependencies MUST be narrowed using `$derived` projections to prevent cascading effect thrashing.

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 Fine-Grained Reactive Proxy Isolation and Boundary Enforcement critical for AI coding assistants?

Enforces strict boundary encapsulation for Svelte 5 reactive proxies created by $state() in complex, state-driven dashboards. Eliminates cross-component mutable proxy leaks, unbounded deep dependency graph traversal in effects, and memory leaks by mandating $state.raw(), $state.snapshot(), and encapsulated domain stores. 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 (Uncontained Cross-Component Reactive Proxy Passing and Deep Effect Signal Pollution) 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