This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor7-headless-background-sync-thread-safety

Capacitor 7 Headless Native Background Sync Thread-Safety & Storage Invariant

Enforces isolated native synchronization and queue management when background geofencing, push notifications, or periodic workers wake mobile apps in a headless state without an initialized Webview bridge. Prevents silent bridge dispatch failures, bridge memory corruption, and SQLite/Preferences file lock contention across OS native background threads and dormant Webview runtime contexts.

Prohibited Anti-Pattern: Dispatching JS Bridge Calls or Accessing Shared Storage from Headless Native Background Handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Headless Native Background Sync Thread-Safety & Storage Invariant - Enforces isolated native synchronization and queue management when background geofencing, push notifications, or periodic workers wake mobile apps in a headless state without an initialized Webview bridge. Prevents silent bridge dispatch failures, bridge memory corruption, and SQLite/Preferences file lock contention across OS native background threads and dormant Webview runtime contexts.
globs: android/app/src/main/java/**/*.java, android/app/src/main/java/**/*.kt, ios/App/App/**/*.swift, src/plugins/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor7-headless-background-sync-thread-safety"
---

# Capacitor 7 Headless Native Background Sync Thread-Safety & Storage Invariant

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Dispatching JS Bridge Calls or Accessing Shared Storage from Headless Native Background Handlers

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 headless native background processing invariants. Headless background wakeups (e.g., JobScheduler, WorkManager, BGTaskScheduler, Silent APNs) execute without a running WKWebView or Android WebView JavaScript runtime. You must enforce strict isolation: native handlers must verify bridge readiness before emitting plugin events, use WAL-mode atomic persistent native queues for telemetry/sync, and defer UI or Webview sync state reconciliation until the Webview bridge dispatches its initial app-ready lifecycle signal.

## Strict Guidelines
- Native plugins MUST NEVER call 'notifyListeners' or evaluate JavaScript when 'bridge == null', 'bridge.getWebView() == null', or when the web application has not emitted its initial readiness handshake.
- Background tasks MUST store headless sync payloads in an isolated, thread-safe transactional store (Native SQLite in WAL mode or encrypted disk queue) instead of accessing Preferences or Web Storage directly.
- TypeScript services MUST implement an explicit reconciliation handshake on app startup to drain, deduplicate, and process persisted background events stored while the Webview was suspended.
- Native Android services (BroadcastReceiver, WorkManager) MUST avoid instantiating the Capacitor Bridge directly to execute quick background sync tasks.
- Native iOS background tasks (BGAppRefreshTask, BGProcessingTask) MUST NOT access bridge components on non-main threads or assume 'bridge.viewController' is mounted.
- TypeScript code MUST check Capacitor plugin availability and bridge attachment status before assuming continuous listener connectivity across app suspension boundaries.

## Bad vs Good Implementations
### Headless Native Push/Sync Event Handling in Capacitor Plugin (Swift / TypeScript)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When iOS or Android invokes a headless background worker, the WebView JS engine is suspended or non-existent. Calling 'notifyListeners' from native code will fail silently or crash, and 'window.localStorage' is inaccessible or un-synced.
```typescript
import { Plugins } from '@capacitor/core';
const { BackgroundSyncPlugin } = Plugins;

// ANTI-PATTERN: Blindly assuming background events can invoke active JS listeners
// when waking the app headlessly, causing dropped payloads or null pointer bridge crashes
BackgroundSyncPlugin.addListener('onBackgroundSync', async (payload: { id: string; data: unknown }) => {
  const storage = window.localStorage;
  storage.setItem(`sync_${payload.id}`, JSON.stringify(payload.data));
  await fetch('/api/sync', { method: 'POST', body: JSON.stringify(payload.data) });
});
```

#### Production Standard (Correct)
> **Standard**: Separates headless event persistence from Webview consumption. Native workers store payloads in a native WAL-mode store, and the TypeScript layer drains and reconciles the queue once the Webview runtime is fully mounted and network-ready.
```typescript
import { registerPlugin } from '@capacitor/core';

interface SyncQueuePlugin {
  drainPendingBackgroundEvents(): Promise<{ events: Array<{ id: string; payload: unknown; timestamp: number }> }>;
  acknowledgeEvents(options: { ids: string[] }): Promise<void>;
}

const NativeSyncQueue = registerPlugin<SyncQueuePlugin>('NativeSyncQueue');

export class BackgroundSyncCoordinator {
  private isProcessing = false;

  public async reconcilePendingEvents(): Promise<void> {
    if (this.isProcessing) return;
    this.isProcessing = true;

    try {
      // Safe: Drain atomic native queue written by native headless workers
      const { events } = await NativeSyncQueue.drainPendingBackgroundEvents();
      if (!events || events.length === 0) return;

      const acknowledgedIds: string[] = [];
      for (const event of events) {
        await fetch('/api/sync', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(event.payload)
        });
        acknowledgedIds.push(event.id);
      }

      await NativeSyncQueue.acknowledgeEvents({ ids: acknowledgedIds });
    } finally {
      this.isProcessing = false;
    }
  }
}
```

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 Headless Native Background Sync Thread-Safety & Storage Invariant

Capacitor 7 Headless Native Background Sync Thread-Safety & Storage Invariant defines an industrial-grade behavioral standard for mobile engineering. Enforces isolated native synchronization and queue management when background geofencing, push notifications, or periodic workers wake mobile apps in a headless state without an initialized Webview bridge. Prevents silent bridge dispatch failures, bridge memory corruption, and SQLite/Preferences file lock contention across OS native background threads and dormant Webview runtime contexts. 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: Dispatching JS Bridge Calls or Accessing Shared Storage from Headless Native Background Handlers 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 DriftDispatching JS Bridge Calls or Accessing Shared Storage from Headless Native Background HandlersCritical
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

Native plugins MUST NEVER call 'notifyListeners' or evaluate JavaScript when 'bridge == null', 'bridge.getWebView() == null', or when the web application has not emitted its initial readiness handshake.

Native plugins MUST NEVER call 'notifyListeners' or evaluate JavaScript when 'bridge == null', 'bridge.getWebView() == null', or when the web application has not emitted its initial readiness handshake.

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

Background tasks MUST store headless sync payloads in an isolated, thread-safe transactional store (Native SQLite in WAL mode or encrypted disk queue) instead of accessing Preferences or Web Storage directly.

Background tasks MUST store headless sync payloads in an isolated, thread-safe transactional store (Native SQLite in WAL mode or encrypted disk queue) instead of accessing Preferences or Web Storage directly.

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

TypeScript services MUST implement an explicit reconciliation handshake on app startup to drain, deduplicate, and process persisted background events stored while the Webview was suspended.

TypeScript services MUST implement an explicit reconciliation handshake on app startup to drain, deduplicate, and process persisted background events stored while the Webview was suspended.

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

Native Android services (BroadcastReceiver, WorkManager) MUST avoid instantiating the Capacitor Bridge directly to execute quick background sync tasks.

Native Android services (BroadcastReceiver, WorkManager) MUST avoid instantiating the Capacitor Bridge directly to execute quick background sync tasks.

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

Native iOS background tasks (BGAppRefreshTask, BGProcessingTask) MUST NOT access bridge components on non-main threads or assume 'bridge.viewController' is mounted.

Native iOS background tasks (BGAppRefreshTask, BGProcessingTask) MUST NOT access bridge components on non-main threads or assume 'bridge.viewController' is mounted.

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

TypeScript code MUST check Capacitor plugin availability and bridge attachment status before assuming continuous listener connectivity across app suspension boundaries.

TypeScript code MUST check Capacitor plugin availability and bridge attachment status before assuming continuous listener connectivity across app suspension boundaries.

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 Headless Native Background Sync Thread-Safety & Storage Invariant critical for AI coding assistants?

Enforces isolated native synchronization and queue management when background geofencing, push notifications, or periodic workers wake mobile apps in a headless state without an initialized Webview bridge. Prevents silent bridge dispatch failures, bridge memory corruption, and SQLite/Preferences file lock contention across OS native background threads and dormant Webview runtime contexts. 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 (Dispatching JS Bridge Calls or Accessing Shared Storage from Headless Native Background Handlers) 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