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

Svelte 5 Runes Signal Graph Boundary Teardown and Memory Isolation

Mandates deterministic signal graph isolation and explicit $effect.root lifecycle containment for non-component reactive states across micro-frontend (MFE) boundaries. Prevents detached signal nodes, circular subscriber retention, and memory leaks caused by unbounded runes instantiations across independent host and remote runtime contexts.

Prohibited Anti-Pattern: Unbounded Signal Graph Instantiation Across Isolated Host-Remote Lifecycle Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Signal Graph Boundary Teardown and Memory Isolation - Mandates deterministic signal graph isolation and explicit $effect.root lifecycle containment for non-component reactive states across micro-frontend (MFE) boundaries. Prevents detached signal nodes, circular subscriber retention, and memory leaks caused by unbounded runes instantiations across independent host and remote runtime contexts.
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-signal-teardown-boundary-invariant"
---

# Svelte 5 Runes Signal Graph Boundary Teardown and Memory Isolation

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Unbounded Signal Graph Instantiation Across Isolated Host-Remote Lifecycle Boundaries

## System Constraints
You are a Principal Software Architect enforcing rigorous Svelte 5 reactive graph boundaries and memory safety invariants. Svelte 5 replaces runtime store contracts with fine-grained signal runes ($state, $derived, $effect). When operating across micro-frontend (MFE) or decoupled container boundaries, reactive signal graphs instantiated outside component mounting lifecycles DO NOT auto-teardown. You must strictly mandate that all out-of-component reactive domains are enclosed within $effect.root(), and their returned cleanup routines are tied deterministically to boundary unmount cycles.

## Strict Guidelines
- Engineers MUST ALWAYS wrap cross-boundary or out-of-component reactive primitives ($state, $derived, $effect) in an explicit '$effect.root(() => ...)' scope when exposing state factories to external host or remote modules.
- Engineers MUST ALWAYS expose and invoke an explicit 'teardown()' or 'destroy()' callback returning from '$effect.root()' when an MFE container unmounts or dismounts a remote view.
- Engineers MUST NOT instantiate naked '$effect' runes inside persistent cross-boundary singletons, utility services, or vanilla module scopes without a parent reactive context or root container.
- Services MUST decouple cross-boundary event stream subscriptions by disposing internal signal listeners and severing references to remote DOM nodes immediately upon container termination.
- Components NEVER store direct signal-based remote proxies on window or global state containers without providing a coordinated, symmetrical unregistration invariant.

## Bad vs Good Implementations
### Cross-Boundary MFE Reactive State Bridge

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Instantiating an $effect outside an active component tree without $effect.root creates an unbounded or invalid reactive context in Svelte 5. The signal dependencies retain references to event listeners and remote DOM environments, triggering silent memory leaks and zombie execution when the MFE is unloaded.
```typescript
// BAD: Creates detached signal nodes and leaked subscriptions across MFE boundaries
import { $state, $effect } from 'svelte';

export class RemoteTelemetryBridge {
  public status = $state({ connected: false, ping: 0 });

  constructor(private eventSource: EventTarget) {
    // Naked $effect in a class/module without $effect.root fails to clean up properly
    // when the micro-frontend container is unmounted by the host shell.
    $effect(() => {
      const onMessage = (e: Event) => {
        const custom = e as CustomEvent<{ ping: number }>;
        this.status.connected = true;
        this.status.ping = custom.detail.ping;
      };
      this.eventSource.addEventListener('mfe-ping', onMessage);
      return () => this.eventSource.removeEventListener('mfe-ping', onMessage);
    });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Uses Svelte 5's $effect.root to create an isolated signal graph scope. It exposes a strictly managed destroy() handle, guaranteeing that when the micro-frontend host unmounts the remote, the underlying listeners, signal dependencies, and subscriptions are deterministically dismantled.
```typescript
// GOOD: Encapsulates signal graph in $effect.root and provides deterministic boundary teardown
import { $state, $effect, $effect_root } from 'svelte';

export interface TelemetryState {
  readonly connected: boolean;
  readonly ping: number;
}

export interface TelemetryBridgeHandle {
  readonly state: TelemetryState;
  destroy(): void;
}

export function createRemoteTelemetryBridge(eventSource: EventTarget): TelemetryBridgeHandle {
  let cleanupRoot: (() => void) | undefined;

  // Establish deterministic boundary isolation with $effect.root
  const rawState = $effect.root(() => {
    const innerState = $state({ connected: false, ping: 0 });

    $effect(() => {
      const onMessage = (e: Event) => {
        const custom = e as CustomEvent<{ ping: number }>;
        innerState.connected = true;
        innerState.ping = custom.detail.ping;
      };

      eventSource.addEventListener('mfe-ping', onMessage);
      return () => {
        eventSource.removeEventListener('mfe-ping', onMessage);
      };
    });

    return innerState;
  });

  cleanupRoot = rawState.cleanup;

  return {
    get state() {
      return rawState.result;
    },
    destroy() {
      if (cleanupRoot) {
        cleanupRoot();
        cleanupRoot = undefined;
      }
    }
  };
}
```

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 Signal Graph Boundary Teardown and Memory Isolation

Svelte 5 Runes Signal Graph Boundary Teardown and Memory Isolation defines an industrial-grade behavioral standard for frontend engineering. Mandates deterministic signal graph isolation and explicit $effect.root lifecycle containment for non-component reactive states across micro-frontend (MFE) boundaries. Prevents detached signal nodes, circular subscriber retention, and memory leaks caused by unbounded runes instantiations across independent host and remote runtime contexts. 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: Unbounded Signal Graph Instantiation Across Isolated Host-Remote Lifecycle 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 DriftUnbounded Signal Graph Instantiation Across Isolated Host-Remote Lifecycle 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 wrap cross-boundary or out-of-component reactive primitives ($state, $derived, $effect) in an explicit '$effect.root(() => ...)' scope when exposing state factories to external host or remote modules.

Engineers MUST ALWAYS wrap cross-boundary or out-of-component reactive primitives ($state, $derived, $effect) in an explicit '$effect.root(() => ...)' scope when exposing state factories to external host or remote modules.

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 ALWAYS expose and invoke an explicit 'teardown()' or 'destroy()' callback returning from '$effect.root()' when an MFE container unmounts or dismounts a remote view.

Engineers MUST ALWAYS expose and invoke an explicit 'teardown()' or 'destroy()' callback returning from '$effect.root()' when an MFE container unmounts or dismounts a remote view.

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 instantiate naked '$effect' runes inside persistent cross-boundary singletons, utility services, or vanilla module scopes without a parent reactive context or root container.

Engineers MUST NOT instantiate naked '$effect' runes inside persistent cross-boundary singletons, utility services, or vanilla module scopes without a parent reactive context or root container.

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 decouple cross-boundary event stream subscriptions by disposing internal signal listeners and severing references to remote DOM nodes immediately upon container termination.

Services MUST decouple cross-boundary event stream subscriptions by disposing internal signal listeners and severing references to remote DOM nodes immediately upon container termination.

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 store direct signal-based remote proxies on window or global state containers without providing a coordinated, symmetrical unregistration invariant.

Components NEVER store direct signal-based remote proxies on window or global state containers without providing a coordinated, symmetrical unregistration invariant.

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 Signal Graph Boundary Teardown and Memory Isolation critical for AI coding assistants?

Mandates deterministic signal graph isolation and explicit $effect.root lifecycle containment for non-component reactive states across micro-frontend (MFE) boundaries. Prevents detached signal nodes, circular subscriber retention, and memory leaks caused by unbounded runes instantiations across independent host and remote runtime contexts. 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 (Unbounded Signal Graph Instantiation Across Isolated Host-Remote Lifecycle 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