This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-indexeddb-sqlite-wal-bridge-standard

Capacitor 7 Isolated WebView IndexedDB-to-Native SQLite WAL Bridge

Protects against silent OS-level storage eviction and cross-context race conditions in Capacitor 7 hybrid applications. Mandates that native SQLite in Write-Ahead Logging (WAL) mode acts as the single source of truth, while WebView IndexedDB serves strictly as an ephemeral, rehydratable read cache synchronized via monotonic transaction logs.

Prohibited Anti-Pattern: Direct Authoritative Storage in Isolated WebViews Leading to Silent Eviction and Split-Brain Mutation Races

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Isolated WebView IndexedDB-to-Native SQLite WAL Bridge - Protects against silent OS-level storage eviction and cross-context race conditions in Capacitor 7 hybrid applications. Mandates that native SQLite in Write-Ahead Logging (WAL) mode acts as the single source of truth, while WebView IndexedDB serves strictly as an ephemeral, rehydratable read cache synchronized via monotonic transaction logs.
globs: src/storage/**/*.{ts,tsx}, src/database/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/plugins/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-indexeddb-sqlite-wal-bridge-standard"
---

# Capacitor 7 Isolated WebView IndexedDB-to-Native SQLite WAL Bridge

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Direct Authoritative Storage in Isolated WebViews Leading to Silent Eviction and Split-Brain Mutation Races

## System Constraints
You are a Principal Mobile Architect enforcing strict storage durability and concurrency invariants for Capacitor 7 applications. Mobile operating systems (especially iOS WKWebView and Android WebView) treat web runtime storage (IndexedDB/LocalStorage) as volatile caches subject to silent eviction under disk pressure. You must enforce that native SQLite in WAL mode is the authoritative single source of truth (SSOT). Any web runtime caching must use an atomic Write-Ahead Logging (WAL) queue with monotonic log sequence numbers (LSN), bridge mutual exclusion, and deterministic startup reconciliation.

## Strict Guidelines
- Engineers MUST ALWAYS configure the native SQLite database with `PRAGMA journal_mode=WAL;` and `PRAGMA synchronous=NORMAL;` upon connection initialization.
- Engineers MUST NOT treat WebView IndexedDB, WebSQL, or LocalStorage as authoritative persistent storage.
- Services MUST serialize all bridge mutation commands through an in-memory sequential promise queue to eliminate bridge serialization interleaving and database lock contention.
- Code SHOULD assign a strictly monotonic Log Sequence Number (LSN) and UUIDv4 client transaction ID to every mutation prior to bridging to native storage.
- Engineers MUST ALWAYS implement a two-phase hydration sequence during app bootstrap: verify native SQLite schema version, reconcile any uncommitted offline LSN entries, and blow away/repopulate IndexedDB from native state if corruption or eviction is detected.
- Components NEVER execute raw SQL queries directly from UI presentation layers; all operations must proceed via typed Repository or Unit-of-Work patterns mediating the WAL bridge.

## Bad vs Good Implementations
### Naive Direct IndexedDB / Uncoordinated Native Bridge Write

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This code treats IndexedDB as a reliable store (vulnerable to iOS WKWebView cache eviction under memory pressure) and executes an un-synchronized bridge call to native SQLite without WAL mode or queue locks, causing SQLITE_BUSY concurrency failures and split-brain states.
```typescript
import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';

// ANTI-PATTERN: Direct uncoordinated writes treat IndexedDB as SSOT
// or fire concurrent un-queued native bridge requests prone to 'database locked' errors.
export async function saveUserData(user: { id: string; name: string }): Promise<void> {
  // 1. Storing directly in IndexedDB assumes web storage is permanent (silent eviction hazard)
  const request = window.indexedDB.open('AppCache', 1);
  request.onsuccess = () => {
    const db = request.result;
    const tx = db.transaction('users', 'readwrite');
    tx.objectStore('users').put(user);
  };

  // 2. Uncoordinated direct native call without WAL mode, mutex, or LSN validation
  const sqlite = new SQLiteConnection(CapacitorSQLite);
  const db = await sqlite.createConnection('app_db', false, 'no-encryption', 1, false);
  await db.open();
  // Prone to SQLITE_BUSY or cross-thread race conditions
  await db.execute(`INSERT OR REPLACE INTO users (id, name) VALUES ('${user.id}', '${user.name}');`);
  await db.close();
}
```

#### Production Standard (Correct)
> **Standard**: Native SQLite is established as the single source of truth in WAL mode. Mutations are enqueued atomically using serialized promises, wrapped in transactions, and tracked via an append-only WAL log before committing.
```typescript
import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection } from '@capacitor-community/sqlite';

export interface WALEntry {
  lsn: number;
  txId: string;
  table: string;
  operation: 'INSERT' | 'UPDATE' | 'DELETE';
  payload: Record<string, unknown>;
  timestamp: number;
}

export class DurableStorageBridge {
  private static instance: DurableStorageBridge;
  private db: SQLiteDBConnection | null = null;
  private writeQueue: Promise<unknown> = Promise.resolve();
  private currentLsn = 0;

  private constructor() {}

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

  public async initialize(): Promise<void> {
    const sqlite = new SQLiteConnection(CapacitorSQLite);
    this.db = await sqlite.createConnection('authoritative_store', false, 'no-encryption', 1, false);
    await this.db.open();

    // Mandate WAL mode and foreign key constraints for concurrency and integrity
    await this.db.execute('PRAGMA journal_mode=WAL;');
    await this.db.execute('PRAGMA synchronous=NORMAL;');
    await this.db.execute(`
      CREATE TABLE IF NOT EXISTS sys_wal_log (
        lsn INTEGER PRIMARY KEY AUTOINCREMENT,
        tx_id TEXT UNIQUE NOT NULL,
        table_name TEXT NOT NULL,
        operation TEXT NOT NULL,
        payload TEXT NOT NULL,
        created_at INTEGER NOT NULL
      );
      CREATE TABLE IF NOT EXISTS users (
        id TEXT PRIMARY KEY,
        name TEXT NOT NULL,
        updated_at INTEGER NOT NULL
      );
    `);

    const res = await this.db.query('SELECT COALESCE(MAX(lsn), 0) AS maxLsn FROM sys_wal_log;');
    this.currentLsn = res.values?.[0]?.maxLsn ?? 0;
  }

  public async executeMutation(table: string, operation: 'INSERT' | 'UPDATE' | 'DELETE', payload: Record<string, unknown>): Promise<number> {
    return new Promise((resolve, reject) => {
      // Enforce strict serialized queue to prevent bridge thread race conditions
      this.writeQueue = this.writeQueue.then(async () => {
        if (!this.db) throw new Error('Database not initialized');
        const txId = crypto.randomUUID();
        const now = Date.now();

        try {
          await this.db.execute('BEGIN TRANSACTION;');
          const walSql = `INSERT INTO sys_wal_log (tx_id, table_name, operation, payload, created_at) VALUES (?, ?, ?, ?, ?);`;
          await this.db.run(walSql, [txId, table, operation, JSON.stringify(payload), now]);

          if (table === 'users' && (operation === 'INSERT' || operation === 'UPDATE')) {
            const userSql = `INSERT OR REPLACE INTO users (id, name, updated_at) VALUES (?, ?, ?);`;
            await this.db.run(userSql, [payload.id, payload.name, now]);
          }

          await this.db.execute('COMMIT;');
          this.currentLsn += 1;
          resolve(this.currentLsn);
        } catch (error) {
          await this.db.execute('ROLLBACK;').catch(() => {});
          reject(error);
        }
      });
    });
  }
}
```

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 Isolated WebView IndexedDB-to-Native SQLite WAL Bridge

Capacitor 7 Isolated WebView IndexedDB-to-Native SQLite WAL Bridge defines an industrial-grade behavioral standard for mobile engineering. Protects against silent OS-level storage eviction and cross-context race conditions in Capacitor 7 hybrid applications. Mandates that native SQLite in Write-Ahead Logging (WAL) mode acts as the single source of truth, while WebView IndexedDB serves strictly as an ephemeral, rehydratable read cache synchronized via monotonic transaction logs. 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: Direct Authoritative Storage in Isolated WebViews Leading to Silent Eviction and Split-Brain Mutation Races 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 DriftDirect Authoritative Storage in Isolated WebViews Leading to Silent Eviction and Split-Brain Mutation RacesCritical
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 configure the native SQLite database with `PRAGMA journal_mode=WAL

Engineers MUST ALWAYS configure the native SQLite database with `PRAGMA journal_mode=WAL;` and `PRAGMA synchronous=NORMAL;` upon connection initialization.

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 treat WebView IndexedDB, WebSQL, or LocalStorage as authoritative persistent storage.

Engineers MUST NOT treat WebView IndexedDB, WebSQL, or LocalStorage as authoritative persistent storage.

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 serialize all bridge mutation commands through an in-memory sequential promise queue to eliminate bridge serialization interleaving and database lock contention.

Services MUST serialize all bridge mutation commands through an in-memory sequential promise queue to eliminate bridge serialization interleaving and database lock contention.

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 assign a strictly monotonic Log Sequence Number (LSN) and UUIDv4 client transaction ID to every mutation prior to bridging to native storage.

Code SHOULD assign a strictly monotonic Log Sequence Number (LSN) and UUIDv4 client transaction ID to every mutation prior to bridging to native storage.

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

Engineers MUST ALWAYS implement a two-phase hydration sequence during app bootstrap

Engineers MUST ALWAYS implement a two-phase hydration sequence during app bootstrap: verify native SQLite schema version, reconcile any uncommitted offline LSN entries, and blow away/repopulate IndexedDB from native state if corruption or eviction is detected.

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.
6

Components NEVER execute raw SQL queries directly from UI presentation layers

Components NEVER execute raw SQL queries directly from UI presentation layers; all operations must proceed via typed Repository or Unit-of-Work patterns mediating the WAL bridge.

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 Isolated WebView IndexedDB-to-Native SQLite WAL Bridge critical for AI coding assistants?

Protects against silent OS-level storage eviction and cross-context race conditions in Capacitor 7 hybrid applications. Mandates that native SQLite in Write-Ahead Logging (WAL) mode acts as the single source of truth, while WebView IndexedDB serves strictly as an ephemeral, rehydratable read cache synchronized via monotonic transaction logs. 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 (Direct Authoritative Storage in Isolated WebViews Leading to Silent Eviction and Split-Brain Mutation Races) 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