This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-native-memory-pressure-eviction

Capacitor 7 Native-to-WebView Memory Pressure & V8 Heap Eviction Standard

Binds native low-memory signals (Android onTrimMemory / iOS didReceiveMemoryWarning) directly through Capacitor 7 App lifecycle listeners to execute deterministic JavaScript heap scavenging, canvas buffer flushes, and offscreen DOM/cache evictions. Prevents abrupt OS-level process termination by preemptively reducing memory footprint below kernel out-of-memory (OOM) kill thresholds during background and foreground pressure states.

Prohibited Anti-Pattern: Ignoring Native Memory Warnings Leading to Silent WebView OOM Process Termination

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Native-to-WebView Memory Pressure & V8 Heap Eviction Standard - Binds native low-memory signals (Android onTrimMemory / iOS didReceiveMemoryWarning) directly through Capacitor 7 App lifecycle listeners to execute deterministic JavaScript heap scavenging, canvas buffer flushes, and offscreen DOM/cache evictions. Prevents abrupt OS-level process termination by preemptively reducing memory footprint below kernel out-of-memory (OOM) kill thresholds during background and foreground pressure states.
globs: src/**/*.{ts,tsx}, android/app/src/main/java/**/*.java, ios/App/App/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-native-memory-pressure-eviction"
---

# Capacitor 7 Native-to-WebView Memory Pressure & V8 Heap Eviction Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Ignoring Native Memory Warnings Leading to Silent WebView OOM Process Termination

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 memory lifecycle invariants. Native OS low-memory notifications (Android ComponentCallbacks2.TRIM_MEMORY_* and iOS UIApplicationDidReceiveMemoryWarningNotification) must trigger coordinated cleanup across the native-webview boundary. You must enforce immediate offscreen resource release, active image blob revoking, canvas buffer zeroing, and proactive GC pressure hints before the OS watchdog terminates the app.

## Strict Guidelines
- Engineers MUST ALWAYS register an `appStateChange` and native memory pressure listener via `@capacitor/app` or a dedicated low-memory plugin at initialization time.
- Engineers MUST NOT rely on passive browser garbage collection when the application transitions to background or receives OS trim notifications.
- Services MUST clear in-memory LRU caches, revoke unpinned `URL.createObjectURL` references, and purge state management history/snapshots upon receiving memory pressure events.
- Components NEVER hold references to offscreen `<canvas>` elements; offscreen canvases MUST have their `width` and `height` set to `0` and rendering contexts detached during critical memory states.
- Code SHOULD explicitly decouple non-visible Virtual DOM subtrees and detach large detached DOM nodes to allow V8/JavaScriptCore to sweep dead generations efficiently.

## Bad vs Good Implementations
### Naive Resource Management vs. Coordinated Native Memory Eviction Pipeline

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to handle native memory events and app suspension leaves retained blobs and canvas memory intact. On iOS (WebKit WebProcess) and Android (WebView renderer), memory limits are severely constrained in the background, resulting in immediate process death without telemetry.
```typescript
import { App } from '@capacitor/app';

// Anti-pattern: Relying solely on appStateChange without memory-pressure integration,
// retaining large in-memory caches and active blobs across lifecycles.
class MediaCacheManager {
  private cache = new Map<string, Blob>();

  constructor() {
    App.addListener('appStateChange', ({ isActive }) => {
      console.log('App active state changed:', isActive);
      // Flaw: No eviction, no blob revocation, no canvas teardown.
      // App risks SIGKILL / OOM termination when backgrounded under memory pressure.
    });
  }

  public set(key: string, data: Blob) {
    this.cache.set(key, data);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements an eviction registry pattern directly mapped to native lifecycle events. Flushes unpinned assets, releases offscreen canvas framebuffers by resetting dimensions, and facilitates deterministic V8/JSC heap compaction prior to OS kernel eviction.
```typescript
import { App, PluginListenerHandle } from '@capacitor/app';

interface MemoryPressurePayload {
  level: 'moderate' | 'critical';
}

type EvictionHandler = () => void;

export class MemoryPressureCoordinator {
  private static instance: MemoryPressureCoordinator;
  private handlers = new Set<EvictionHandler>();
  private stateListener: PluginListenerHandle | null = null;

  private constructor() {
    this.registerLifecycleHooks();
  }

  public static getInstance(): MemoryPressureCoordinator {
    if (!MemoryPressureCoordinator.instance) {
      MemoryPressureCoordinator.instance = new MemoryPressureCoordinator();
    }
    return MemoryPressureCoordinator.instance;
  }

  public registerEvictor(handler: EvictionHandler): () => void {
    this.handlers.add(handler);
    return () => this.handlers.delete(handler);
  }

  private async registerLifecycleHooks(): Promise<void> {
    // Bind to Capacitor app lifecycle
    this.stateListener = await App.addListener('appStateChange', (state) => {
      if (!state.isActive) {
        this.executeEviction('moderate');
      }
    });

    // Bind custom Capacitor native bridge event for Android onTrimMemory / iOS didReceiveMemoryWarning
    window.addEventListener('nativeMemoryPressure', ((e: CustomEvent<MemoryPressurePayload>) => {
      this.executeEviction(e.detail.level);
    }) as EventListener);
  }

  public executeEviction(level: 'moderate' | 'critical'): void {
    for (const handler of this.handlers) {
      try {
        handler();
      } catch (err) {
        console.error('Eviction handler failure:', err);
      }
    }

    if (level === 'critical') {
      // Release detached elements and trigger GC-friendly de-allocations
      this.zeroOutCanvases();
    }
  }

  private zeroOutCanvases(): void {
    const canvases = document.querySelectorAll('canvas:not([data-persistent])');
    canvases.forEach((canvas) => {
      const c = canvas as HTMLCanvasElement;
      c.width = 0;
      c.height = 0;
    });
  }
}
```

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: Capacitor 7 Native-to-WebView Memory Pressure & V8 Heap Eviction Standard

Capacitor 7 Native-to-WebView Memory Pressure & V8 Heap Eviction Standard defines an industrial-grade behavioral standard for mobile engineering. Binds native low-memory signals (Android onTrimMemory / iOS didReceiveMemoryWarning) directly through Capacitor 7 App lifecycle listeners to execute deterministic JavaScript heap scavenging, canvas buffer flushes, and offscreen DOM/cache evictions. Prevents abrupt OS-level process termination by preemptively reducing memory footprint below kernel out-of-memory (OOM) kill thresholds during background and foreground pressure states. 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: Ignoring Native Memory Warnings Leading to Silent WebView OOM Process Termination 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 DriftIgnoring Native Memory Warnings Leading to Silent WebView OOM Process TerminationCritical
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 register an `appStateChange` and native memory pressure listener via `@capacitor/app` or a dedicated low-memory plugin at initialization time.

Engineers MUST ALWAYS register an `appStateChange` and native memory pressure listener via `@capacitor/app` or a dedicated low-memory plugin at initialization time.

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 rely on passive browser garbage collection when the application transitions to background or receives OS trim notifications.

Engineers MUST NOT rely on passive browser garbage collection when the application transitions to background or receives OS trim notifications.

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

Services MUST clear in-memory LRU caches, revoke unpinned `URL.createObjectURL` references, and purge state management history/snapshots upon receiving memory pressure events.

Services MUST clear in-memory LRU caches, revoke unpinned `URL.createObjectURL` references, and purge state management history/snapshots upon receiving memory pressure events.

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

Components NEVER hold references to offscreen `<canvas>` elements

Components NEVER hold references to offscreen `<canvas>` elements; offscreen canvases MUST have their `width` and `height` set to `0` and rendering contexts detached during critical memory states.

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

Code SHOULD explicitly decouple non-visible Virtual DOM subtrees and detach large detached DOM nodes to allow V8/JavaScriptCore to sweep dead generations efficiently.

Code SHOULD explicitly decouple non-visible Virtual DOM subtrees and detach large detached DOM nodes to allow V8/JavaScriptCore to sweep dead generations efficiently.

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 Capacitor 7 Native-to-WebView Memory Pressure & V8 Heap Eviction Standard critical for AI coding assistants?

Binds native low-memory signals (Android onTrimMemory / iOS didReceiveMemoryWarning) directly through Capacitor 7 App lifecycle listeners to execute deterministic JavaScript heap scavenging, canvas buffer flushes, and offscreen DOM/cache evictions. Prevents abrupt OS-level process termination by preemptively reducing memory footprint below kernel out-of-memory (OOM) kill thresholds during background and foreground pressure states. 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 (Ignoring Native Memory Warnings Leading to Silent WebView OOM Process Termination) 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 MOBILE Rules

View all rules →
1 Rule in Stack

Capacitor