This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: svelte-5-dynamic-context-memory-guardrail

Svelte 5 Runes Dynamic Context Memory Retention Guardrail

Prevents catastrophic detached DOM nodes and cumulative heap memory leaks caused by unbound $state signals, root-less $effect.root closures, and shared module-level context references leaking across deeply nested, dynamically unmounted Svelte 5 component trees. Mandates strict lifecycle scoping, clean teardown of reactive context subscribers, and isolation of module-level reactive stores.

Prohibited Anti-Pattern: Escaping Rune Subscriptions and Leaked Module-Level Context References in Dynamic Component Subtrees

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Dynamic Context Memory Retention Guardrail - Prevents catastrophic detached DOM nodes and cumulative heap memory leaks caused by unbound $state signals, root-less $effect.root closures, and shared module-level context references leaking across deeply nested, dynamically unmounted Svelte 5 component trees. Mandates strict lifecycle scoping, clean teardown of reactive context subscribers, and isolation of module-level reactive stores.
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-dynamic-context-memory-guardrail"
---

# Svelte 5 Runes Dynamic Context Memory Retention Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Escaping Rune Subscriptions and Leaked Module-Level Context References in Dynamic Component Subtrees

## System Constraints
You are a Principal Engineer enforcing Svelte 5 Runes Dynamic Context Memory Retention Guardrails. Svelte 5 changes reactivity from compile-time assignment instrumentation to runtime signal graphs via runes ($state, $derived, $effect). When dynamic components mount and unmount repeatedly (such as tabs, virtualized lists, or modal flows), unbound subscriptions, module-scoped reactive stores, and unmanaged $effect.root instances retain strong references to unmounted component contexts and their detached DOM nodes. You must mandate strict adherence to contextual ownership via setContext/getContext, explicit teardown registrations with $effect cleanups or onDestroy, and prohibit module-level mutable rune singletons that capture component-scoped reactive primitives.

## Strict Guidelines
- Engineers MUST ALWAYS isolate stateful runes inside component or context factories rather than instantiating global mutable $state instances at the module root that retain subscribers across dynamic mount/unmount cycles.
- Engineers MUST NEVER create manual $effect.root instances without capturing their disposal function and calling it within an explicit component teardown lifecycle (e.g., $effect(() => () => cleanup())).
- Engineers MUST ALWAYS return a teardown/cleanup closure from $effect blocks when adding external event listeners, subscribing to custom event buses, or dispatching non-Svelte observable subscriptions.
- Code SHOULD prefer Svelte 5 context API (`setContext`, `getContext`) with dedicated class instances holding runes, ensuring garbage collection sweeps state along with the component instance root.
- Components NEVER store direct references to parent DOM nodes, detached element proxies, or component instances inside long-lived shared service singletons.

## Bad vs Good Implementations
### Module-Level Leaked State vs Context-Scoped Dynamic Rune Service

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-level `activeTabState` holds onto callback closures registered by transient child components. When `DynamicTabChild` is unmounted by an if-block or tab-switch, the closure remains in the module-level Set, preventing `localData` (and the entire component instance) from being garbage collected.
```typescript
// BAD: Module-level mutable state retains references across dynamically mounted subtrees
// file: dynamicTabsStore.svelte.ts
export const activeTabState = $state({
  currentTabId: 'home',
  subscribers: new Set<(tabId: string) => void>()
});

export function registerTabWatcher(callback: (tabId: string) => void) {
  activeTabState.subscribers.add(callback);
  // Memory leak: No unregister, callback closures retain unmounted component scope
}

// DynamicTabChild.svelte
// <script lang="ts">
//   import { registerTabWatcher } from './dynamicTabsStore.svelte';
//   let localData = $state(new Array(1000000).fill('leak'));
//   registerTabWatcher((id) => { console.log(id, localData.length); });
// </script>
```

#### Production Standard (Correct)
> **Standard**: Context is bound to the component hierarchy. When the dynamic subtree is torn down, references are dropped, and all child $effect dependencies are naturally detached from the runtime signal graph.
```typescript
// GOOD: Factory-scoped state managed via Svelte 5 context with explicit cleanup
// file: tabContext.svelte.ts
import { getContext, setContext } from 'svelte';

const TAB_CONTEXT_KEY = Symbol('TAB_CONTEXT_KEY');

export class TabContextManager {
  currentTabId = $state<string>('home');

  setTab(id: string) {
    this.currentTabId = id;
  }
}

export function initTabContext(): TabContextManager {
  const manager = new TabContextManager();
  setContext(TAB_CONTEXT_KEY, manager);
  return manager;
}

export function useTabContext(): TabContextManager {
  const manager = getContext<TabContextManager>(TAB_CONTEXT_KEY);
  if (!manager) {
    throw new Error('useTabContext must be called within an initialized TabContext tree.');
  }
  return manager;
}

// DynamicTabChild.svelte
// <script lang="ts">
//   import { useTabContext } from './tabContext.svelte';
//   const tabs = useTabContext();
//   // Automatic reactive derivation scoped strictly to the lifecycle of this child
//   $effect(() => {
//     console.log('Tab changed:', tabs.currentTabId);
//     return () => {
//       // Guaranteed teardown when DynamicTabChild unmounts
//     };
//   });
// </script>
```

### Manual $effect.root Subscription Leak vs Scoped Reactive Effect

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: $effect.root isolates reactivity from the ambient component context, meaning it will NOT be torn down when the calling component unmounts unless its return callback is explicitly invoked, permanently leaking the DOM element and callback context.
```typescript
// BAD: Uncleaned $effect.root instantiated inside a dynamic helper/utility
export function observeElementIntersection(element: HTMLElement, callback: (visible: boolean) => void) {
  $effect.root(() => {
    const observer = new IntersectionObserver(([entry]) => {
      callback(entry.isIntersecting);
    });
    observer.observe(element);
    // Leak: Observer never disconnects and root is never disposed
  });
}
```

#### Production Standard (Correct)
> **Standard**: The $effect.root disposal function is returned to the caller and registered into the component's own reactive teardown cycle, guaranteeing that the IntersectionObserver is disconnected and the root reactive scope is closed.
```typescript
// GOOD: Scoped lifecycle with returned cleanup or custom action disposal
export function observeElementIntersection(
  element: HTMLElement,
  callback: (visible: boolean) => void
): () => void {
  const cleanup = $effect.root(() => {
    const observer = new IntersectionObserver(([entry]) => {
      callback(entry.isIntersecting);
    });
    observer.observe(element);

    return () => {
      observer.disconnect();
    };
  });

  return cleanup;
}

// Usage inside Svelte component:
// $effect(() => {
//   const dispose = observeElementIntersection(nodeRef, (visible) => { ... });
//   return dispose; // Correctly unmounts and cleans heap when destroyed
// });
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Svelte 5 Runes Dynamic Context Memory Retention Guardrail

Svelte 5 Runes Dynamic Context Memory Retention Guardrail defines an industrial-grade behavioral standard for frontend engineering. Prevents catastrophic detached DOM nodes and cumulative heap memory leaks caused by unbound $state signals, root-less $effect.root closures, and shared module-level context references leaking across deeply nested, dynamically unmounted Svelte 5 component trees. Mandates strict lifecycle scoping, clean teardown of reactive context subscribers, and isolation of module-level reactive 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: Escaping Rune Subscriptions and Leaked Module-Level Context References in Dynamic Component Subtrees 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 DriftEscaping Rune Subscriptions and Leaked Module-Level Context References in Dynamic Component SubtreesCritical
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 stateful runes inside component or context factories rather than instantiating global mutable $state instances at the module root that retain subscribers across dynamic mount/unmount cycles.

Engineers MUST ALWAYS isolate stateful runes inside component or context factories rather than instantiating global mutable $state instances at the module root that retain subscribers across dynamic mount/unmount cycles.

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 create manual $effect.root instances without capturing their disposal function and calling it within an explicit component teardown lifecycle (e.g., $effect(() => () => cleanup())).

Engineers MUST NEVER create manual $effect.root instances without capturing their disposal function and calling it within an explicit component teardown lifecycle (e.g., $effect(() => () => cleanup())).

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 return a teardown/cleanup closure from $effect blocks when adding external event listeners, subscribing to custom event buses, or dispatching non-Svelte observable subscriptions.

Engineers MUST ALWAYS return a teardown/cleanup closure from $effect blocks when adding external event listeners, subscribing to custom event buses, or dispatching non-Svelte observable subscriptions.

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 Svelte 5 context API (`setContext`, `getContext`) with dedicated class instances holding runes, ensuring garbage collection sweeps state along with the component instance root.

Code SHOULD prefer Svelte 5 context API (`setContext`, `getContext`) with dedicated class instances holding runes, ensuring garbage collection sweeps state along with the component instance root.

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 references to parent DOM nodes, detached element proxies, or component instances inside long-lived shared service singletons.

Components NEVER store direct references to parent DOM nodes, detached element proxies, or component instances inside long-lived shared service singletons.

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 Dynamic Context Memory Retention Guardrail critical for AI coding assistants?

Prevents catastrophic detached DOM nodes and cumulative heap memory leaks caused by unbound $state signals, root-less $effect.root closures, and shared module-level context references leaking across deeply nested, dynamically unmounted Svelte 5 component trees. Mandates strict lifecycle scoping, clean teardown of reactive context subscribers, and isolation of module-level reactive 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 (Escaping Rune Subscriptions and Leaked Module-Level Context References in Dynamic Component Subtrees) 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