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

Svelte 5 Runes State Boundary Proxy Isolation Guardrail

Enforces deterministic state boundary serialization when passing Svelte 5 reactive proxies across Web Workers, micro-frontends, or cross-runtime message channels. Deep signal-backed state created via $state() must be explicitly un-proxied using $state.snapshot() before boundary traversal to prevent DataCloneError exceptions, memory retention leaks, and cross-runtime reactive feedback loops.

Prohibited Anti-Pattern: Passing Raw Svelte 5 $state Proxies Across Worker Message Ports or Micro-Frontend Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes State Boundary Proxy Isolation Guardrail - Enforces deterministic state boundary serialization when passing Svelte 5 reactive proxies across Web Workers, micro-frontends, or cross-runtime message channels. Deep signal-backed state created via $state() must be explicitly un-proxied using $state.snapshot() before boundary traversal to prevent DataCloneError exceptions, memory retention leaks, and cross-runtime reactive feedback loops.
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-boundary-proxy-isolation"
---

# Svelte 5 Runes State Boundary Proxy Isolation Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Passing Raw Svelte 5 $state Proxies Across Worker Message Ports or Micro-Frontend Boundaries

## System Constraints
You are a Principal Engineer enforcing architectural boundaries and memory-safe reactivity in Svelte 5 applications. You must enforce that raw reactive proxies generated by Svelte 5 runes ($state, $state.raw) are NEVER transmitted across micro-frontend event buses, Dynamic Web Worker postMessage calls, or broadcast channels. Mandate explicit extraction using $state.snapshot() and strict boundary sanitization.

## Strict Guidelines
- Engineers MUST ALWAYS invoke $state.snapshot(proxyObject) prior to transmitting reactive rune state through postMessage, Worker ports, or CustomEvent details.
- Engineers MUST NOT pass raw $state-derived Proxies directly to dynamic Web Workers, BroadcastChannel, or window.dispatchEvent to avoid DOMException DataCloneError and uncollectable cross-context references.
- Engineers MUST wrap bidirectional cross-micro-frontend event subscribers in untrack() if reading local rune state during boundary event synthesis to prevent accidental reactive cascade loops.
- Services MUST implement explicit Data Transfer Object (DTO) schema validation (e.g., Zod, Valibot, or ArkType) at the boundary receiver before hydrating foreign payloads back into local $state.
- Components NEVER retain references to external micro-frontend mutable models within local $effect scopes without deterministic teardown returning an unregister callback.

## Bad vs Good Implementations
### Passing Runes State to Web Worker via postMessage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Passing `this.state` directly forwards the Svelte 5 signal-backed reactive proxy. In many runtimes, structured clone will fail with DataCloneError due to non-serializable signal metadata and internal getters/setters. If partially cloned, downstream mutations cannot be observed, or will cause cyclic feedback loops if the worker echoes the state back into another reactive setter.
```typescript
import { workerPool } from './worker-pool';

interface TaskState {
  id: string;
  items: Array<{ name: string; priority: number }>;
}

export class TaskCoordinator {
  state = $state<TaskState>({
    id: 'tx-101',
    items: [{ name: 'Compile', priority: 1 }]
  });

  dispatchToWorker(worker: Worker) {
    // ANTI-PATTERN: Passing raw reactive Proxy directly to worker.
    // Throws DataCloneError in strict engines or leaks reactive proxy references
    // that trigger infinite synchronization cycles upon worker response.
    worker.postMessage({
      type: 'EXECUTE',
      payload: this.state
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: `$state.snapshot()` strips all reactive traps, signal dependencies, and internal Svelte 5 metadata, returning an immutable structured-clone-safe deep snapshot that transitions cleanly over Worker message boundaries without side effects or memory retention.
```typescript
import { workerPool } from './worker-pool';

interface TaskState {
  id: string;
  items: Array<{ name: string; priority: number }>;
}

export class TaskCoordinator {
  state = $state<TaskState>({
    id: 'tx-101',
    items: [{ name: 'Compile', priority: 1 }]
  });

  dispatchToWorker(worker: Worker) {
    // PRODUCTION FIX: Un-proxy state using $state.snapshot() to generate
    // a pristine, non-reactive, deep-cloned plain JavaScript object.
    const cleanPayload: TaskState = $state.snapshot(this.state);

    worker.postMessage({
      type: 'EXECUTE',
      payload: cleanPayload
    });
  }
}
```

### Cross-Micro-Frontend Event Dispatch and Synchronization

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exporting the reactive proxy inside a CustomEvent exposes internal signals to foreign runtimes. Additionally, running this inside `$effect` without untrack guarantees that any echo from external micro-frontends triggers continuous bidirectional feedback loops and keeps obsolete DOM nodes alive.
```typescript
import { untrack } from 'svelte';

export function setupMfeSync(bus: EventTarget) {
  let shared = $state({ count: 0, origin: 'mfe-a' });

  $effect(() => {
    // ANTI-PATTERN: Direct dispatch inside $effect without untrack or snapshot
    // creates an infinite cross-app sync storm when MFE-B responds to this event.
    bus.dispatchEvent(new CustomEvent('sync:state', {
      detail: shared
    }));
  });
}
```

#### Production Standard (Correct)
> **Standard**: Using `$state.snapshot()` produces a detached DTO for the event detail, `untrack()` decouples boundary message emissions from reactive tracking contexts, and origin validation prevents bidirectional re-entrant feedback loops while guaranteeing full event listener teardown.
```typescript
import { untrack } from 'svelte';

interface SyncPayload {
  count: number;
  origin: string;
}

export function setupMfeSync(bus: EventTarget) {
  let shared = $state<SyncPayload>({ count: 0, origin: 'mfe-a' });

  $effect(() => {
    // Depend explicitly only on the local state change
    const currentCount = shared.count;

    untrack(() => {
      const payload = $state.snapshot(shared);
      bus.dispatchEvent(new CustomEvent<SyncPayload>('sync:state', {
        detail: payload
      }));
    });
  });

  const handleRemote = (event: Event) => {
    const customEvent = event as CustomEvent<SyncPayload>;
    if (customEvent.detail && customEvent.detail.origin !== 'mfe-a') {
      untrack(() => {
        shared.count = customEvent.detail.count;
      });
    }
  };

  bus.addEventListener('sync:state', handleRemote);
  return () => bus.removeEventListener('sync:state', handleRemote);
}
```

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 State Boundary Proxy Isolation Guardrail

Svelte 5 Runes State Boundary Proxy Isolation Guardrail defines an industrial-grade behavioral standard for frontend engineering. Enforces deterministic state boundary serialization when passing Svelte 5 reactive proxies across Web Workers, micro-frontends, or cross-runtime message channels. Deep signal-backed state created via $state() must be explicitly un-proxied using $state.snapshot() before boundary traversal to prevent DataCloneError exceptions, memory retention leaks, and cross-runtime reactive feedback loops. 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: Passing Raw Svelte 5 $state Proxies Across Worker Message Ports or Micro-Frontend Boundaries 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 DriftPassing Raw Svelte 5 $state Proxies Across Worker Message Ports or Micro-Frontend BoundariesCritical
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 invoke $state.snapshot(proxyObject) prior to transmitting reactive rune state through postMessage, Worker ports, or CustomEvent details.

Engineers MUST ALWAYS invoke $state.snapshot(proxyObject) prior to transmitting reactive rune state through postMessage, Worker ports, or CustomEvent details.

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 $state-derived Proxies directly to dynamic Web Workers, BroadcastChannel, or window.dispatchEvent to avoid DOMException DataCloneError and uncollectable cross-context references.

Engineers MUST NOT pass raw $state-derived Proxies directly to dynamic Web Workers, BroadcastChannel, or window.dispatchEvent to avoid DOMException DataCloneError and uncollectable cross-context 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.
3

Engineers MUST wrap bidirectional cross-micro-frontend event subscribers in untrack() if reading local rune state during boundary event synthesis to prevent accidental reactive cascade loops.

Engineers MUST wrap bidirectional cross-micro-frontend event subscribers in untrack() if reading local rune state during boundary event synthesis to prevent accidental reactive cascade loops.

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

Services MUST implement explicit Data Transfer Object (DTO) schema validation (e.g., Zod, Valibot, or ArkType) at the boundary receiver before hydrating foreign payloads back into local $state.

Services MUST implement explicit Data Transfer Object (DTO) schema validation (e.g., Zod, Valibot, or ArkType) at the boundary receiver before hydrating foreign payloads back into local $state.

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 retain references to external micro-frontend mutable models within local $effect scopes without deterministic teardown returning an unregister callback.

Components NEVER retain references to external micro-frontend mutable models within local $effect scopes without deterministic teardown returning an unregister callback.

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 State Boundary Proxy Isolation Guardrail critical for AI coding assistants?

Enforces deterministic state boundary serialization when passing Svelte 5 reactive proxies across Web Workers, micro-frontends, or cross-runtime message channels. Deep signal-backed state created via $state() must be explicitly un-proxied using $state.snapshot() before boundary traversal to prevent DataCloneError exceptions, memory retention leaks, and cross-runtime reactive feedback loops. 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 (Passing Raw Svelte 5 $state Proxies Across Worker Message Ports or Micro-Frontend Boundaries) 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