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

Capacitor 7 Encrypted SQLite Cryptographic Migration Rollback Standard

Enforces fail-safe atomic migrations and deterministic cryptographic rollbacks for @capacitor-community/sqlite on hardware-encrypted mobile storage. Guarantees zero database corruption when background app lifecycles, operating system watchdog timers, or biometric key revocations abort schema updates mid-execution.

Prohibited Anti-Pattern: In-Place Non-Atomic DDL Execution on Encrypted SQLite Without Verified Cryptographic Snapshots

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Encrypted SQLite Cryptographic Migration Rollback Standard - Enforces fail-safe atomic migrations and deterministic cryptographic rollbacks for @capacitor-community/sqlite on hardware-encrypted mobile storage. Guarantees zero database corruption when background app lifecycles, operating system watchdog timers, or biometric key revocations abort schema updates mid-execution.
globs: src/database/**/*.ts, src/services/storage/**/*.ts, src/migrations/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-encrypted-sqlite-migration-rollback-standard"
---

# Capacitor 7 Encrypted SQLite Cryptographic Migration Rollback Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: In-Place Non-Atomic DDL Execution on Encrypted SQLite Without Verified Cryptographic Snapshots

## System Constraints
You are a Principal Mobile Architect specializing in Capacitor 7, SQLite/SQLCipher internals, and mobile OS lifecycle constraints. You mandate zero data-loss, zero corruption, and atomic rollback guarantees during hardware-encrypted database migrations across iOS Keychain and Android Keystore backed storage.

## Strict Guidelines
- Engineers MUST ALWAYS create a validated, encrypted pre-migration shadow backup using copyFile or native backup APIs before initiating any DDL or migration sequence.
- Engineers MUST ALWAYS wrap migration steps within an explicit BEGIN EXCLUSIVE TRANSACTION block, validating PRAGMA foreign_keys = ON and PRAGMA integrity_check before commit.
- Engineers MUST NOT execute schema migrations directly against the live database without verifying persistent hardware-keystore unlock status and registering a background task token (Capacitor App/BackgroundRunner).
- Services MUST execute a cryptographic and structural validation check (PRAGMA cipher_integrity_check and PRAGMA quick_check) immediately prior to committing and immediately post-rollback.
- Components NEVER execute raw DDL scripts asynchronously without handling SIGKILL/SIGTERM recovery by asserting a database 'migration_lock' sentinel table on connection initialization.

## Bad vs Good Implementations
### Unsafe in-place migration vs. Atomic snapshot-backed cryptographic migration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executes sequential DDL queries without an EXCLUSIVE transaction, background lifecycle assertion, or snapshot restoration strategy. If iOS/Android kills the background process midway, the database is left in a dirty, partially migrated schema state with no path to restore.
```typescript
import { SQLiteDBConnection } from '@capacitor-community/sqlite';

export async function runUnsafeMigration(db: SQLiteDBConnection, targetVersion: number): Promise<void> {
  // Anti-Pattern: Executing DDL in-place without exclusive locking or rollback snapshots.
  // If the OS terminates the app in the background, the DB becomes irreversibly corrupted.
  await db.open();
  await db.execute('ALTER TABLE users ADD COLUMN biometric_hash TEXT;');
  await db.execute('CREATE TABLE audit_logs (id TEXT PRIMARY KEY, action TEXT);');
  await db.setVersion(targetVersion);
  // If app is killed here, state is inconsistent, no backup exists, and cipher salt may desync.
}
```

#### Production Standard (Correct)
> **Standard**: Implements pre-flight integrity verification, allocates a background runtime execution lease, captures a full hardware-encrypted shadow database snapshot, enforces atomic execution under an EXCLUSIVE lock, and performs an automatic binary rollback if any DDL statement or integrity assertion fails.
```typescript
import { CapacitorSQLite, SQLiteConnection, SQLiteDBConnection } from '@capacitor-community/sqlite';
import { App } from '@capacitor/app';

interface MigrationStep {
  version: number;
  up: string[];
}

export async function runSafeMigration(
  sqlite: SQLiteConnection,
  db: SQLiteDBConnection,
  dbName: string,
  steps: MigrationStep[]
): Promise<void> {
  const snapshotName = `${dbName}_pre_migration_backup`;
  let backgroundTaskId: string | null = null;

  try {
    // 1. Acquire background task lease to avoid OS termination mid-DDL
    backgroundTaskId = (await App.requestBackgroundYield?.()) ?? null;

    // 2. Cryptographic and integrity pre-flight check
    const integrity = await db.query('PRAGMA integrity_check;');
    if (integrity.values?.[0]?.integrity_check !== 'ok') {
      throw new Error('Database failed pre-flight integrity check.');
    }

    // 3. Create pre-migration physical encrypted snapshot
    await sqlite.copyFromLocalDatabase(dbName, snapshotName);

    // 4. Begin explicit exclusive lock
    await db.execute('BEGIN EXCLUSIVE TRANSACTION;');
    await db.execute('PRAGMA foreign_keys = OFF;');

    for (const step of steps) {
      for (const ddl of step.up) {
        await db.execute(ddl);
      }
      await db.execute(`INSERT INTO _schema_versions (version, applied_at) VALUES (${step.version}, ${Date.now()});`);
    }

    await db.execute('PRAGMA foreign_keys = ON;');
    const postCheck = await db.query('PRAGMA integrity_check;');
    if (postCheck.values?.[0]?.integrity_check !== 'ok') {
      throw new Error('Post-migration integrity verification failed.');
    }

    await db.execute('COMMIT;');
    // Remove shadow snapshot only after successful commit
    await sqlite.deleteDatabase(snapshotName);
  } catch (error) {
    try {
      await db.execute('ROLLBACK;').catch(() => {});
      await db.close();
      // Restore verified shadow backup
      await sqlite.copyFromLocalDatabase(snapshotName, dbName);
      await sqlite.deleteDatabase(snapshotName);
    } catch (restoreError) {
      console.error('FATAL: Cryptographic rollback failed:', restoreError);
    }
    throw new Error(`Migration aborted and rolled back: ${(error as Error).message}`);
  } finally {
    if (backgroundTaskId) {
      await App.finishBackgroundYield?.();
    }
  }
}
```

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 Encrypted SQLite Cryptographic Migration Rollback Standard

Capacitor 7 Encrypted SQLite Cryptographic Migration Rollback Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces fail-safe atomic migrations and deterministic cryptographic rollbacks for @capacitor-community/sqlite on hardware-encrypted mobile storage. Guarantees zero database corruption when background app lifecycles, operating system watchdog timers, or biometric key revocations abort schema updates mid-execution. 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: In-Place Non-Atomic DDL Execution on Encrypted SQLite Without Verified Cryptographic Snapshots 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 DriftIn-Place Non-Atomic DDL Execution on Encrypted SQLite Without Verified Cryptographic SnapshotsCritical
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 create a validated, encrypted pre-migration shadow backup using copyFile or native backup APIs before initiating any DDL or migration sequence.

Engineers MUST ALWAYS create a validated, encrypted pre-migration shadow backup using copyFile or native backup APIs before initiating any DDL or migration sequence.

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 ALWAYS wrap migration steps within an explicit BEGIN EXCLUSIVE TRANSACTION block, validating PRAGMA foreign_keys = ON and PRAGMA integrity_check before commit.

Engineers MUST ALWAYS wrap migration steps within an explicit BEGIN EXCLUSIVE TRANSACTION block, validating PRAGMA foreign_keys = ON and PRAGMA integrity_check before commit.

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 NOT execute schema migrations directly against the live database without verifying persistent hardware-keystore unlock status and registering a background task token (Capacitor App/BackgroundRunner).

Engineers MUST NOT execute schema migrations directly against the live database without verifying persistent hardware-keystore unlock status and registering a background task token (Capacitor App/BackgroundRunner).

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 execute a cryptographic and structural validation check (PRAGMA cipher_integrity_check and PRAGMA quick_check) immediately prior to committing and immediately post-rollback.

Services MUST execute a cryptographic and structural validation check (PRAGMA cipher_integrity_check and PRAGMA quick_check) immediately prior to committing and immediately post-rollback.

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 execute raw DDL scripts asynchronously without handling SIGKILL/SIGTERM recovery by asserting a database 'migration_lock' sentinel table on connection initialization.

Components NEVER execute raw DDL scripts asynchronously without handling SIGKILL/SIGTERM recovery by asserting a database 'migration_lock' sentinel table on 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Capacitor 7 Encrypted SQLite Cryptographic Migration Rollback Standard critical for AI coding assistants?

Enforces fail-safe atomic migrations and deterministic cryptographic rollbacks for @capacitor-community/sqlite on hardware-encrypted mobile storage. Guarantees zero database corruption when background app lifecycles, operating system watchdog timers, or biometric key revocations abort schema updates mid-execution. 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 (In-Place Non-Atomic DDL Execution on Encrypted SQLite Without Verified Cryptographic Snapshots) 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