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

Capacitor 7 OPFS Worker Direct-to-Disk Sync Standard

Enforces that all Origin Private File System (OPFS) direct-to-disk synchronous access handle operations and embedded SQLite/database I/O are strictly isolated to dedicated Web Workers. Prohibits executing FileSystemSyncAccessHandle operations, IndexedDB synchronous fallbacks, or high-frequency writes on the primary WebView thread to prevent UI micro-stutters and main-thread ANR crashes in Capacitor 7 hybrid applications.

Prohibited Anti-Pattern: Executing Synchronous OPFS Access Handles or Intensive SQLite Disk I/O on the Main WebView Thread

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 OPFS Worker Direct-to-Disk Sync Standard - Enforces that all Origin Private File System (OPFS) direct-to-disk synchronous access handle operations and embedded SQLite/database I/O are strictly isolated to dedicated Web Workers. Prohibits executing FileSystemSyncAccessHandle operations, IndexedDB synchronous fallbacks, or high-frequency writes on the primary WebView thread to prevent UI micro-stutters and main-thread ANR crashes in Capacitor 7 hybrid applications.
globs: src/**/*.{ts,tsx,js,jsx}, src/workers/**/*.{ts,js}, src/services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-opfs-worker-sync-standard"
---

# Capacitor 7 OPFS Worker Direct-to-Disk Sync Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Executing Synchronous OPFS Access Handles or Intensive SQLite Disk I/O on the Main WebView Thread

## System Constraints
You are a Principal Software Architect enforcing the Capacitor 7 OPFS Worker Direct-to-Disk Sync Standard. You must mandate that all synchronous direct-to-disk persistence pipelines utilizing the Origin Private File System (OPFS) and FileSystemSyncAccessHandle operate exclusively within dedicated Web Workers. You must strictly forbid any blocking storage operations, synchronous file mutations, or direct SQLite WASM execution on the Capacitor WebView main thread. All inter-thread communication must rely on structured cloning via standard MessagePort or transferrable ArrayBuffers without leaking synchronous locks.

## Strict Guidelines
- Engineers MUST ALWAYS isolate FileSystemFileHandle.createSyncAccessHandle() invocations exclusively within dedicated Web Workers.
- Engineers MUST NOT invoke createSyncAccessHandle() or execute write/flush sync loops directly in the main DOM/WebView thread context.
- Engineers MUST transfer data payloads across the main thread and worker boundary using transferable objects (e.g., ArrayBuffer) to eliminate serialization overhead.
- Services MUST implement explicit lifecycle management that flushes (accessHandle.flush()) and closes (accessHandle.close()) access handles upon worker termination or idle compaction.
- Components NEVER directly instantiate local-first database engines (e.g., SQLite WASM, wa-sqlite, or PGlite) on the main thread; they must consume an asynchronous RPC client backed by the OPFS worker.
- Code MUST verify Cross-Origin-Opener-Policy (COOP) and Cross-Origin-Embedder-Policy (COEP) headers are configured appropriately for Atomics/SharedArrayBuffer support if shared concurrency is utilized in Capacitor 7.

## Bad vs Good Implementations
### Main-Thread OPFS Access Handle Anti-Pattern vs Dedicated Worker Direct-to-Disk Implementation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Attempting to create and use FileSystemSyncAccessHandle on the main WebView thread is either prohibited by modern web specifications or results in severe UI frame drops and ANR (Application Not Responding) dialogs in native Android/iOS Capacitor wrappers during large database transactions.
```typescript
// Main-thread database client directly invoking OPFS sync handles
export class LocalPersistenceService {
  public async syncRecord(data: Uint8Array): Promise<void> {
    // VIOLATION: Accessing OPFS and attempting synchronous disk operations on the main thread
    const root = await navigator.storage.getDirectory();
    const fileHandle = await root.getFileHandle('app_cache.db', { create: true });
    
    // createSyncAccessHandle throws or blocks the native WebView rendering cycle
    // @ts-expect-error createSyncAccessHandle is not supported in window/main thread
    const syncHandle = await fileHandle.createSyncAccessHandle();
    syncHandle.write(data, { at: 0 });
    syncHandle.flush();
    syncHandle.close();
  }
}
```

#### Production Standard (Correct)
> **Standard**: Isolates synchronous file writes inside a dedicated Web Worker using transferable ArrayBuffers. The main thread delegates write payloads asynchronously, eliminating frame drops, adhering to W3C File System Living Standard OPFS constraints, and maintaining 60/120 FPS native WebView responsiveness in Capacitor 7.
```typescript
// Dedicated Worker: src/workers/opfs-storage.worker.ts
interface SyncMessage {
  type: 'WRITE_RECORD';
  buffer: ArrayBuffer;
  offset: number;
}

self.onmessage = async (event: MessageEvent<SyncMessage>) => {
  const { type, buffer, offset } = event.data;
  if (type === 'WRITE_RECORD') {
    const root = await navigator.storage.getDirectory();
    const fileHandle = await root.getFileHandle('app_cache.db', { create: true });
    const syncHandle = await fileHandle.createSyncAccessHandle();
    
    try {
      const view = new Uint8Array(buffer);
      syncHandle.write(view, { at: offset });
      syncHandle.flush();
      self.postMessage({ status: 'SUCCESS', bytesWritten: view.byteLength });
    } finally {
      syncHandle.close();
    }
  }
};

// Main-thread Service: src/services/StorageClient.ts
export class StorageClient {
  private worker: Worker;

  constructor() {
    this.worker = new Worker(new URL('../workers/opfs-storage.worker.ts', import.meta.url), {
      type: 'module',
    });
  }

  public async syncRecord(data: Uint8Array, offset: number = 0): Promise<void> {
    return new Promise((resolve, reject) => {
      const channel = new MessageChannel();
      channel.port1.onmessage = (event) => {
        if (event.data.status === 'SUCCESS') resolve();
        else reject(new Error('OPFS write failed'));
      };

      // Zero-copy transfer of buffer to worker
      this.worker.postMessage(
        { type: 'WRITE_RECORD', buffer: data.buffer, offset },
        [data.buffer]
      );
    });
  }
}
```

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 OPFS Worker Direct-to-Disk Sync Standard

Capacitor 7 OPFS Worker Direct-to-Disk Sync Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces that all Origin Private File System (OPFS) direct-to-disk synchronous access handle operations and embedded SQLite/database I/O are strictly isolated to dedicated Web Workers. Prohibits executing FileSystemSyncAccessHandle operations, IndexedDB synchronous fallbacks, or high-frequency writes on the primary WebView thread to prevent UI micro-stutters and main-thread ANR crashes in Capacitor 7 hybrid applications. 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 Synchronous OPFS Access Handles or Intensive SQLite Disk I/O on the Main WebView Thread 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 Synchronous OPFS Access Handles or Intensive SQLite Disk I/O on the Main WebView ThreadCritical
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 isolate FileSystemFileHandle.createSyncAccessHandle() invocations exclusively within dedicated Web Workers.

Engineers MUST ALWAYS isolate FileSystemFileHandle.createSyncAccessHandle() invocations exclusively within dedicated Web Workers.

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 invoke createSyncAccessHandle() or execute write/flush sync loops directly in the main DOM/WebView thread context.

Engineers MUST NOT invoke createSyncAccessHandle() or execute write/flush sync loops directly in the main DOM/WebView thread context.

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 transfer data payloads across the main thread and worker boundary using transferable objects (e.g., ArrayBuffer) to eliminate serialization overhead.

Engineers MUST transfer data payloads across the main thread and worker boundary using transferable objects (e.g., ArrayBuffer) to eliminate serialization overhead.

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 implement explicit lifecycle management that flushes (accessHandle.flush()) and closes (accessHandle.close()) access handles upon worker termination or idle compaction.

Services MUST implement explicit lifecycle management that flushes (accessHandle.flush()) and closes (accessHandle.close()) access handles upon worker termination or idle compaction.

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 directly instantiate local-first database engines (e.g., SQLite WASM, wa-sqlite, or PGlite) on the main thread

Components NEVER directly instantiate local-first database engines (e.g., SQLite WASM, wa-sqlite, or PGlite) on the main thread; they must consume an asynchronous RPC client backed by the OPFS worker.

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

Code MUST verify Cross-Origin-Opener-Policy (COOP) and Cross-Origin-Embedder-Policy (COEP) headers are configured appropriately for Atomics/SharedArrayBuffer support if shared concurrency is utilized in Capacitor 7.

Code MUST verify Cross-Origin-Opener-Policy (COOP) and Cross-Origin-Embedder-Policy (COEP) headers are configured appropriately for Atomics/SharedArrayBuffer support if shared concurrency is utilized in Capacitor 7.

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 OPFS Worker Direct-to-Disk Sync Standard critical for AI coding assistants?

Enforces that all Origin Private File System (OPFS) direct-to-disk synchronous access handle operations and embedded SQLite/database I/O are strictly isolated to dedicated Web Workers. Prohibits executing FileSystemSyncAccessHandle operations, IndexedDB synchronous fallbacks, or high-frequency writes on the primary WebView thread to prevent UI micro-stutters and main-thread ANR crashes in Capacitor 7 hybrid applications. 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 Synchronous OPFS Access Handles or Intensive SQLite Disk I/O on the Main WebView Thread) 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