This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: wasmgc-host-thread-memory-isolation-guardrail

WebAssembly WasmGC Host-Thread Isolation and Cross-Heap Reference Bounds

Enforces strict process and thread boundaries between the browser UI thread and garbage-collected WebAssembly (WasmGC) runtimes. Mandates execution within dedicated Web Workers and forbids retaining strong bidirectional host-guest references that trigger cross-heap cycles, main-thread jank, and uncollectable memory leaks.

Prohibited Anti-Pattern: Executing WasmGC modules synchronously on the UI thread while retaining circular JS-to-Wasm externref references

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: WebAssembly WasmGC Host-Thread Isolation and Cross-Heap Reference Bounds - Enforces strict process and thread boundaries between the browser UI thread and garbage-collected WebAssembly (WasmGC) runtimes. Mandates execution within dedicated Web Workers and forbids retaining strong bidirectional host-guest references that trigger cross-heap cycles, main-thread jank, and uncollectable memory leaks.
globs: src/**/*.{ts,tsx,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/wasmgc-host-thread-memory-isolation-guardrail"
---

# WebAssembly WasmGC Host-Thread Isolation and Cross-Heap Reference Bounds

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Executing WasmGC modules synchronously on the UI thread while retaining circular JS-to-Wasm externref references

## System Constraints
You are a Principal Software Architect enforcing production safety for WebAssembly GC (WasmGC) integrations in client applications. You must ensure that all CPU-intensive WasmGC instantiations run exclusively within dedicated Web Worker threads, never on the main browser thread. You must strictly prevent cross-heap reference leaks by prohibiting long-lived strong JavaScript references to WasmGC `externref`/`anyref` handles without explicit deterministic lifecycle disposal via FinalizationRegistry or Symbol.dispose.

## Strict Guidelines
- Engineers MUST NEVER instantiate or execute compute-intensive WasmGC modules directly on the browser main (UI) thread.
- Engineers MUST offload WasmGC workloads to a `Worker` context, interacting exclusively through asynchronous message passing or transferable buffers.
- Code MUST NOT store raw host JavaScript DOM nodes or persistent host objects into WasmGC tables or `externref` parameters without automatic lifecycle tracking.
- Services MUST manage cross-heap reference lifecycles using `WeakRef` and `FinalizationRegistry` or explicit `Symbol.dispose` cleanup hooks to break host-guest GC cycles.
- Components NEVER import Wasm exports synchronously into UI rendering lifecycles (such as React `useEffect` or animation loops) without bounded task scheduling.

## Bad vs Good Implementations
### UI Thread Pinning and Cross-Heap Retention vs Isolated Worker Client

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Running WasmGC execution on the UI thread risks frame drops during complex GC cycles or computation. Storing raw DOM elements in persistent Maps pinned to Wasm keys produces cross-heap reference cycles that neither the JS GC nor WasmGC can independently collect.
```typescript
import { compileWasmModule } from './wasm-loader';

// ANTI-PATTERN: Executing WasmGC synchronously on UI thread and pinning
// JS references indefinitely inside WasmGC tables via externref.
export class MainThreadWasmManager {
  private wasmInstance: WebAssembly.Instance | null = null;
  private activeNodes = new Map<number, HTMLElement>();
  private nextId = 0;

  async init(wasmBytes: BufferSource): Promise<void> {
    // Synchronous execution on main thread blocks the compositor
    const module = await WebAssembly.compile(wasmBytes);
    this.wasmInstance = await WebAssembly.instantiate(module, {
      env: {
        registerHostCallback: (nodeId: number, el: HTMLElement) => {
          // Strong reference retention causes uncollectable cross-heap GC cycles
          this.activeNodes.set(nodeId, el);
        }
      }
    });
  }

  processBatch(nodes: HTMLElement[]): void {
    if (!this.wasmInstance) throw new Error('Wasm not initialized');
    const runTransform = this.wasmInstance.exports.transformBatch as (id: number) => void;
    
    for (const node of nodes) {
      const id = ++this.nextId;
      this.activeNodes.set(id, node);
      // Blocks the UI frame budget
      runTransform(id);
    }
  }
}
```

#### Production Standard (Correct)
> **Standard**: Production invariant compliant implementation ensuring memory safety, deterministic execution, and zero runtime hallucination.
```typescript
// PRODUCTION INVARIANT: Compute offloaded to Worker; boundary managed via
// structured messaging and WeakRef/FinalizationRegistry lifecycle bounds.

export interface WorkerTask<TInput, TOutput> {
  id: string;
  payload: TInput;
  resolve: (value: TOutput) => void;
  reject: (reason: unknown) => void;
}

export class IsolatedWasmClient {
  private worker: Worker;
  private inflightTasks = new Map<string, (result: unknown) => void>();
  private registry: FinalizationRegistry<string>;

  constructor(workerScriptUrl: URL | string) {
    this.worker = new Worker(workerScriptUrl, { type: 'module' });
    
    this.registry = new FinalizationRegistry((taskId) => {
      this.worker.postMessage({ type: 'RELEASE_HANDLE', taskId });
    });

    this.worker.onmessage = (event: MessageEvent<{ taskId: string; payload: unknown; error?: string }>) => {
      const { taskId, payload, error } = event.data;
      const handler = this.inflightTasks.get(taskId);
      if (!handler) return;
      this.inflightTasks.delete(taskId);
      if (error) {
        throw new Error(`WasmWorker execution failed: ${error}`);
      }
      handler(payload);
    };
  }

  public async executeCompute<TIn, TOut>(data: TIn, transfer: Transferable[] = []): Promise<TOut> {
    const taskId = crypto.randomUUID();
    return new Promise<TOut>((resolve, reject) => {
      this.inflightTasks.set(taskId, resolve as (result: unknown) => void);
      this.worker.postMessage({ type: 'EXECUTE', taskId, data }, transfer);
    });
  }

  public terminate(): void {
    this.worker.terminate();
    this.inflightTasks.clear();
  }
}
```

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: WebAssembly WasmGC Host-Thread Isolation and Cross-Heap Reference Bounds

WebAssembly WasmGC Host-Thread Isolation and Cross-Heap Reference Bounds defines an industrial-grade behavioral standard for frontend engineering. Enforces strict process and thread boundaries between the browser UI thread and garbage-collected WebAssembly (WasmGC) runtimes. Mandates execution within dedicated Web Workers and forbids retaining strong bidirectional host-guest references that trigger cross-heap cycles, main-thread jank, and uncollectable memory leaks. 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: Executing WasmGC modules synchronously on the UI thread while retaining circular JS-to-Wasm externref references 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 DriftExecuting WasmGC modules synchronously on the UI thread while retaining circular JS-to-Wasm externref referencesCritical
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 NEVER instantiate or execute compute-intensive WasmGC modules directly on the browser main (UI) thread.

Engineers MUST NEVER instantiate or execute compute-intensive WasmGC modules directly on the browser main (UI) thread.

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 offload WasmGC workloads to a `Worker` context, interacting exclusively through asynchronous message passing or transferable buffers.

Engineers MUST offload WasmGC workloads to a `Worker` context, interacting exclusively through asynchronous message passing or transferable buffers.

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 NOT store raw host JavaScript DOM nodes or persistent host objects into WasmGC tables or `externref` parameters without automatic lifecycle tracking.

Code MUST NOT store raw host JavaScript DOM nodes or persistent host objects into WasmGC tables or `externref` parameters without automatic lifecycle tracking.

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 manage cross-heap reference lifecycles using `WeakRef` and `FinalizationRegistry` or explicit `Symbol.dispose` cleanup hooks to break host-guest GC cycles.

Services MUST manage cross-heap reference lifecycles using `WeakRef` and `FinalizationRegistry` or explicit `Symbol.dispose` cleanup hooks to break host-guest GC 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.
5

Components NEVER import Wasm exports synchronously into UI rendering lifecycles (such as React `useEffect` or animation loops) without bounded task scheduling.

Components NEVER import Wasm exports synchronously into UI rendering lifecycles (such as React `useEffect` or animation loops) without bounded task scheduling.

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 WebAssembly WasmGC Host-Thread Isolation and Cross-Heap Reference Bounds critical for AI coding assistants?

Enforces strict process and thread boundaries between the browser UI thread and garbage-collected WebAssembly (WasmGC) runtimes. Mandates execution within dedicated Web Workers and forbids retaining strong bidirectional host-guest references that trigger cross-heap cycles, main-thread jank, and uncollectable memory leaks. 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 (Executing WasmGC modules synchronously on the UI thread while retaining circular JS-to-Wasm externref references) 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

WebAssembly