This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-android-15-lifecycle-back-navigation-guardrail

Deterministic Lifecycle State Restoration and Predictive Back Handling in Capacitor 7

Enforces robust process eviction survival and zero-lag Android 15 Predictive Back gesture integration in Capacitor 7 hybrid web runtimes. Mandates asynchronous state preservation during native lifecycle transitions and non-blocking back-action routing to eliminate WebView crashes, unhandled synthetic navigation events, and white-screen regressions on low-memory eviction.

Prohibited Anti-Pattern: Unregistered Predictive Back Handlers with Memory-Synchronous State Eviction

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Lifecycle State Restoration and Predictive Back Handling in Capacitor 7 - Enforces robust process eviction survival and zero-lag Android 15 Predictive Back gesture integration in Capacitor 7 hybrid web runtimes. Mandates asynchronous state preservation during native lifecycle transitions and non-blocking back-action routing to eliminate WebView crashes, unhandled synthetic navigation events, and white-screen regressions on low-memory eviction.
globs: src/**/*.{ts,tsx}, android/app/src/main/AndroidManifest.xml, android/app/src/main/res/values/styles.xml
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-android-15-lifecycle-back-navigation-guardrail"
---

# Deterministic Lifecycle State Restoration and Predictive Back Handling in Capacitor 7

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unregistered Predictive Back Handlers with Memory-Synchronous State Eviction

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 native runtime lifecycle invariants and Android 15 Predictive Back Navigation specifications. Mandate deterministic state snapshotting via native storage adapters during AppState.change, eliminate blocking or unregistered backButton listeners that crash or cause orphaned WebView routing during predictive gesture animations, and ensure proper onBackAnimationCallback lifecycle registration.

## Strict Guidelines
- Engineers MUST ALWAYS register an asynchronous backButton listener via @capacitor/app using registerPlugin or App.addListener('backButton', ...) that checks canGoBack() before delegating to the native finish() or App.exitApp().
- Engineers MUST NOT rely on synchronous window.onbeforeunload or in-memory state stores (Redux, Zustand, Pinia) without backing them up to Capacitor Preferences or SQLite immediately upon App.addListener('appStateChange') transitioning to isActive === false.
- Engineers MUST explicitly verify that android:enableOnBackInvokedCallback='true' is configured in the AndroidManifest.xml application tag to avoid WebView input event freezing on Android 15 (API level 35).
- Components NEVER attach untracked, direct window.history.popstate bindings that clash with Capacitor Native Back Navigation dispatchers, preventing dual-trigger and out-of-order route de-synchronization.
- Services MUST implement idempotent resume handlers listening to App.addListener('appRestoredResult') to consume plugin results returned after OS process termination during background operations.

## Bad vs Good Implementations
### Predictive Back Handling & Background Eviction State Snapshotting

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Does not coordinate with Android 15 predictive back gesture orchestration, lacks listener cleanup leading to memory leaks across re-renders, ignores Capacitor 7 PluginListenerHandle resolution, and fails to snapshot dirty operational state when the OS initiates process death.
```typescript
import { App } from '@capacitor/app';
import { useEffect } from 'react';

export function useNavigationLifecycle() {
  useEffect(() => {
    // ANTI-PATTERN: Synchronous, unmanaged back-button listener.
    // Bypasses Android 15 Predictive Back, does not check WebView history,
    // and relies on ephemeral in-memory state that is lost on OS eviction.
    App.addListener('backButton', () => {
      if (window.location.pathname === '/home') {
        App.exitApp();
      } else {
        window.history.back();
      }
    });
  }, []);
}
```

#### Production Standard (Correct)
> **Standard**: Properly awaits and stores PluginListenerHandle references for zero-leak cleanup, synchronizes runtime back-stack validation with Android 15 Predictive Back requirements, and persists navigation state asynchronously to native disk during background transitions.
```typescript
import { App, PluginListenerHandle } from '@capacitor/app';
import { Preferences } from '@capacitor/preferences';
import { useEffect } from 'react';

interface NavStateSnapshot {
  currentRoute: string;
  scrollPosition: number;
  timestamp: number;
}

export function useNavigationLifecycle(canGoBackInternal: boolean, onNavigateBack: () => void) {
  useEffect(() => {
    let backHandler: PluginListenerHandle | null = null;
    let stateHandler: PluginListenerHandle | null = null;

    const setupLifecycleGuards = async () => {
      // Android 15 & Capacitor 7 deterministic back-stack coordination
      backHandler = await App.addListener('backButton', ({ canGoBack }) => {
        if (canGoBackInternal || canGoBack) {
          onNavigateBack();
        } else {
          App.exitApp();
        }
      });

      // Deterministic process eviction persistence snapshot
      stateHandler = await App.addListener('appStateChange', async (state) => {
        if (!state.isActive) {
          const snapshot: NavStateSnapshot = {
            currentRoute: window.location.pathname,
            scrollPosition: window.scrollY,
            timestamp: Date.now()
          };
          await Preferences.set({
            key: 'APP_PROCESS_EVICTION_SNAPSHOT',
            value: JSON.stringify(snapshot)
          });
        }
      });
    };

    void setupLifecycleGuards();

    return () => {
      void backHandler?.remove();
      void stateHandler?.remove();
    };
  }, [canGoBackInternal, onNavigateBack]);
}
```

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: Deterministic Lifecycle State Restoration and Predictive Back Handling in Capacitor 7

Deterministic Lifecycle State Restoration and Predictive Back Handling in Capacitor 7 defines an industrial-grade behavioral standard for mobile engineering. Enforces robust process eviction survival and zero-lag Android 15 Predictive Back gesture integration in Capacitor 7 hybrid web runtimes. Mandates asynchronous state preservation during native lifecycle transitions and non-blocking back-action routing to eliminate WebView crashes, unhandled synthetic navigation events, and white-screen regressions on low-memory eviction. 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: Unregistered Predictive Back Handlers with Memory-Synchronous State Eviction 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 DriftUnregistered Predictive Back Handlers with Memory-Synchronous State EvictionCritical
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 asynchronous backButton listener via @capacitor/app using registerPlugin or App.addListener('backButton', ...) that checks canGoBack() before delegating to the native finish() or App.exitApp().

Engineers MUST ALWAYS register an asynchronous backButton listener via @capacitor/app using registerPlugin or App.addListener('backButton', ...) that checks canGoBack() before delegating to the native finish() or App.exitApp().

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 synchronous window.onbeforeunload or in-memory state stores (Redux, Zustand, Pinia) without backing them up to Capacitor Preferences or SQLite immediately upon App.addListener('appStateChange') transitioning to isActive === false.

Engineers MUST NOT rely on synchronous window.onbeforeunload or in-memory state stores (Redux, Zustand, Pinia) without backing them up to Capacitor Preferences or SQLite immediately upon App.addListener('appStateChange') transitioning to isActive === false.

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 explicitly verify that android

Engineers MUST explicitly verify that android:enableOnBackInvokedCallback='true' is configured in the AndroidManifest.xml application tag to avoid WebView input event freezing on Android 15 (API level 35).

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 attach untracked, direct window.history.popstate bindings that clash with Capacitor Native Back Navigation dispatchers, preventing dual-trigger and out-of-order route de-synchronization.

Components NEVER attach untracked, direct window.history.popstate bindings that clash with Capacitor Native Back Navigation dispatchers, preventing dual-trigger and out-of-order route de-synchronization.

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

Services MUST implement idempotent resume handlers listening to App.addListener('appRestoredResult') to consume plugin results returned after OS process termination during background operations.

Services MUST implement idempotent resume handlers listening to App.addListener('appRestoredResult') to consume plugin results returned after OS process termination during background operations.

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 Deterministic Lifecycle State Restoration and Predictive Back Handling in Capacitor 7 critical for AI coding assistants?

Enforces robust process eviction survival and zero-lag Android 15 Predictive Back gesture integration in Capacitor 7 hybrid web runtimes. Mandates asynchronous state preservation during native lifecycle transitions and non-blocking back-action routing to eliminate WebView crashes, unhandled synthetic navigation events, and white-screen regressions on low-memory eviction. 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 (Unregistered Predictive Back Handlers with Memory-Synchronous State Eviction) 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

Deterministic