This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: capacitor-7-swift-6-concurrency-bridge-contract

Capacitor 7 Swift 6 Complete Concurrency & Sendable Boundary Contract

Enforces strict Swift 6 actor isolation and Sendable boundary guarantees across Capacitor 7 native iOS bridges. Prevents low-level data races and memory corruption caused by cross-isolation mutations between WebKit message handlers, background worker tasks, and the main UI runloop.

Prohibited Anti-Pattern: Unchecked Cross-Actor Mutability and Non-Sendable CAPPluginCall Passing in Capacitor iOS Plugins

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Swift 6 Complete Concurrency & Sendable Boundary Contract - Enforces strict Swift 6 actor isolation and Sendable boundary guarantees across Capacitor 7 native iOS bridges. Prevents low-level data races and memory corruption caused by cross-isolation mutations between WebKit message handlers, background worker tasks, and the main UI runloop.
globs: ios/Plugin/**/*.swift, ios/App/**/*.swift, src/definitions.ts, src/index.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-swift-6-concurrency-bridge-contract"
---

# Capacitor 7 Swift 6 Complete Concurrency & Sendable Boundary Contract

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Unchecked Cross-Actor Mutability and Non-Sendable CAPPluginCall Passing in Capacitor iOS Plugins

## System Constraints
You are a Principal Mobile Architect specializing in Capacitor 7 and Swift 6 Complete Concurrency architecture. Enforce strict isolation boundaries across Web-to-Native calls. Ensure every native bridge method isolates execution through dedicated global actors, custom actors, or explicit Sendable parameter extraction, eliminating data races at compile time without relying on '@unchecked Sendable' escapes.

## Strict Guidelines
- Engineers MUST ALWAYS isolate Capacitor native plugin classes (`CAPPlugin`) with explicit concurrency boundaries, decorating UI-touching bridges with `@MainActor` or assigning background operations to isolated actor domains.
- Engineers MUST NOT extract mutable non-Sendable state from `CAPPluginCall` across unstructured `Task { }` boundaries without copying or transforming into immutable `Sendable` types.
- Engineers MUST ALWAYS resolve or reject `CAPPluginCall` instances within the actor domain that created them or wrap callback handling within `@Sendable` closure boundaries.
- Engineers MUST NOT use `@unchecked Sendable` on plugin data payloads or state holder classes to bypass Swift 6 compiler concurrency errors.
- Code SHOULD enforce strict type-safe TypeScript bridge definitions mirroring native immutable Swift structures to avoid untyped payload mismatch across the serialization boundary.

## Bad vs Good Implementations
### Swift 6 Concurrency Migration for Capacitor 7 Bridge Methods

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Capturing `CAPPluginCall` inside an unstructured `Task` without strict actor isolation induces data races on `cache` under Swift 6 mode. `CAPPluginCall` is not inherently `Sendable`, leading to concurrent memory mutations across threads.
```swift
import Foundation
import Capacitor

@objc(SecureStoragePlugin)
public class SecureStoragePlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "SecureStoragePlugin"
    public let jsName = "SecureStorage"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "setCredentials", returnType: CAPPluginReturnPromise)
    ]

    // ANTI-PATTERN: Mutable shared state outside actor isolation
    private var cache: [String: String] = [:]

    @objc func setCredentials(_ call: CAPPluginCall) {
        // ANTI-PATTERN: Capturing non-Sendable CAPPluginCall across unstructured Task
        Task {
            guard let key = call.getString("key"),
                  let value = call.getString("value") else {
                call.reject("Missing parameters")
                return
            }
            // Data race: mutating shared state from non-isolated background context
            self.cache[key] = value
            call.resolve(["status": "stored"])
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Plugin class is pinned to `@MainActor`, mutable state is encapsulated inside an isolated `actor StorageVault`, and values passed across boundaries are immutable `Sendable` types (`String`). Callback resolution explicitly adheres to actor boundaries.
```swift
import Foundation
import Capacitor

// Actor guarding mutable storage state
actor StorageVault {
    private var cache: [String: String] = [:]

    func write(key: String, value: String) {
        cache[key] = value
    }
}

@objc(SecureStoragePlugin)
@MainActor
public final class SecureStoragePlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "SecureStoragePlugin"
    public let jsName = "SecureStorage"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "setCredentials", returnType: CAPPluginReturnPromise)
    ]

    private let vault = StorageVault()

    @objc public func setCredentials(_ call: CAPPluginCall) {
        // Extract immutable Sendable types before dispatching across actor boundaries
        guard let key = call.getString("key"),
              let value = call.getString("value") else {
            call.reject("Missing parameters")
            return
        }

        Task { [vault] in
            await vault.write(key: key, value: value)
            // Resolve on main actor to maintain bridge thread safety
            await MainActor.run {
                call.resolve(["status": "stored"])
            }
        }
    }
}
```

### TypeScript Bridge Contract Invariance

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Untyped parameters ('any') bypass compile-time guarantees, permitting complex non-serializable objects to cross the bridge, leading to runtime serialization failures and native unmarshalling race conditions.
```typescript
// ANTI-PATTERN: Loosely-typed bridge payload allowing arbitrary mutating structures
import { registerPlugin } from '@capacitor/core';

export interface SecureStoragePlugin {
  setCredentials(options: any): Promise<any>;
}

export const SecureStorage = registerPlugin<SecureStoragePlugin>('SecureStorage');
```

#### Production Standard (Correct)
> **Standard**: Readonly, immutable interfaces guarantee that the web payload maps deterministically to Swift primitives, eliminating structural mismatch and mutation across serialization layers.
```typescript
// Strict Sendable-compliant TypeScript schema
import { registerPlugin } from '@capacitor/core';

export interface SetCredentialsOptions {
  readonly key: string;
  readonly value: string;
}

export interface SetCredentialsResult {
  readonly status: 'stored';
}

export interface SecureStoragePlugin {
  setCredentials(options: SetCredentialsOptions): Promise<SetCredentialsResult>;
}

export const SecureStorage = registerPlugin<SecureStoragePlugin>('SecureStorage');
```

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 Swift 6 Complete Concurrency & Sendable Boundary Contract

Capacitor 7 Swift 6 Complete Concurrency & Sendable Boundary Contract defines an industrial-grade behavioral standard for mobile engineering. Enforces strict Swift 6 actor isolation and Sendable boundary guarantees across Capacitor 7 native iOS bridges. Prevents low-level data races and memory corruption caused by cross-isolation mutations between WebKit message handlers, background worker tasks, and the main UI runloop. 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: Unchecked Cross-Actor Mutability and Non-Sendable CAPPluginCall Passing in Capacitor iOS Plugins 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 DriftUnchecked Cross-Actor Mutability and Non-Sendable CAPPluginCall Passing in Capacitor iOS PluginsCritical
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 Capacitor native plugin classes (`CAPPlugin`) with explicit concurrency boundaries, decorating UI-touching bridges with `@MainActor` or assigning background operations to isolated actor domains.

Engineers MUST ALWAYS isolate Capacitor native plugin classes (`CAPPlugin`) with explicit concurrency boundaries, decorating UI-touching bridges with `@MainActor` or assigning background operations to isolated actor domains.

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 extract mutable non-Sendable state from `CAPPluginCall` across unstructured `Task { }` boundaries without copying or transforming into immutable `Sendable` types.

Engineers MUST NOT extract mutable non-Sendable state from `CAPPluginCall` across unstructured `Task { }` boundaries without copying or transforming into immutable `Sendable` types.

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 ALWAYS resolve or reject `CAPPluginCall` instances within the actor domain that created them or wrap callback handling within `@Sendable` closure boundaries.

Engineers MUST ALWAYS resolve or reject `CAPPluginCall` instances within the actor domain that created them or wrap callback handling within `@Sendable` closure 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.
4

Engineers MUST NOT use `@unchecked Sendable` on plugin data payloads or state holder classes to bypass Swift 6 compiler concurrency errors.

Engineers MUST NOT use `@unchecked Sendable` on plugin data payloads or state holder classes to bypass Swift 6 compiler concurrency errors.

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

Code SHOULD enforce strict type-safe TypeScript bridge definitions mirroring native immutable Swift structures to avoid untyped payload mismatch across the serialization boundary.

Code SHOULD enforce strict type-safe TypeScript bridge definitions mirroring native immutable Swift structures to avoid untyped payload mismatch across the serialization boundary.

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 Swift 6 Complete Concurrency & Sendable Boundary Contract critical for AI coding assistants?

Enforces strict Swift 6 actor isolation and Sendable boundary guarantees across Capacitor 7 native iOS bridges. Prevents low-level data races and memory corruption caused by cross-isolation mutations between WebKit message handlers, background worker tasks, and the main UI runloop. 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 (Unchecked Cross-Actor Mutability and Non-Sendable CAPPluginCall Passing in Capacitor iOS Plugins) 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