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

Capacitor 7 Swift Actor-Isolated Plugin Bridge Guardrail

Enforces strict compile-time Swift actor isolation for Capacitor 7 native iOS plugins to eliminate main-thread UI hitching and cross-runtime data races. Guarantees that all asynchronous I/O, heavy computation, and mutable state mutations reside within isolated Swift actors rather than unisolated CAPPlugin instances or synchronous MainActor blocks.

Prohibited Anti-Pattern: Main-Thread Blocking and Unsynchronized Mutable State in Capacitor iOS Plugins

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Capacitor 7 Swift Actor-Isolated Plugin Bridge Guardrail - Enforces strict compile-time Swift actor isolation for Capacitor 7 native iOS plugins to eliminate main-thread UI hitching and cross-runtime data races. Guarantees that all asynchronous I/O, heavy computation, and mutable state mutations reside within isolated Swift actors rather than unisolated CAPPlugin instances or synchronous MainActor blocks.
globs: ios/App/**/*.swift, ios/Plugin/**/*.swift, ios/**/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/capacitor-7-swift-actor-isolated-plugin-bridge-guardrail"
---

# Capacitor 7 Swift Actor-Isolated Plugin Bridge Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Main-Thread Blocking and Unsynchronized Mutable State in Capacitor iOS Plugins

## System Constraints
You are a Principal Mobile Architect enforcing Capacitor 7 Swift Concurrency and Actor Isolation standards. Capacitor 7 bridges Objective-C runtime invocations to modern Swift. You must mandate that all native plugin state, network I/O, and disk serialization are isolated within dedicated Swift `actor` implementations. Never allow synchronous execution of long-running tasks on the main thread, unshielded mutable state within CAPPlugin subclasses, or legacy GCD synchronization primitives.

## Strict Guidelines
- Engineers MUST ALWAYS isolate plugin business logic and mutable state within a dedicated Swift `actor` separated from the `CAPPlugin` subclass.
- Engineers MUST NOT execute blocking operations, file I/O, or cryptographic transformations synchronously inside `@objc func` plugin handlers.
- Engineers MUST wrap asynchronous bridge calls in structured `Task` blocks and await actor methods before invoking `call.resolve()` or `call.reject()`.
- Components NEVER dispatch synchronous work to `DispatchQueue.main.sync` from plugin calls, which causes deadlocks with the WKWebView rendering loop.
- Services MUST ensure that UI-manipulating native calls (such as presenting view controllers) explicitly transition to `@MainActor` using structured concurrency (`await MainActor.run { ... }`).
- Code SHOULD leverage Capacitor 7 typed error handling and propagate typed Swift errors through plugin call rejections rather than failing silently.

## Bad vs Good Implementations
### Capacitor iOS Plugin Bridge: Actor Isolation vs Main-Thread GCD Mutation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The plugin exposes unprotected mutable state (`cache`) across threads and synchronously blocks `DispatchQueue.main`, inducing frame drops and UI freezes in WKWebView.
```swift
import Foundation
import Capacitor

@objc(SecureStorePlugin)
public class SecureStorePlugin: CAPPlugin {
    // ANTI-PATTERN: Unsynchronized mutable state on unisolated CAPPlugin instance
    private var cache: [String: String] = [:]

    @objc func writeData(_ call: CAPPluginCall) {
        guard let key = call.getString("key"),
              let value = call.getString("value") else {
            call.reject("Invalid parameters")
            return
        }

        // ANTI-PATTERN: Blocking main-thread serialization & GCD lockup
        DispatchQueue.main.sync {
            self.cache[key] = value
            Thread.sleep(forTimeInterval: 0.1) // Simulating synchronous heavy crypto/disk I/O
        }
        call.resolve(["status": "stored"])
    }
}
```

#### Production Standard (Correct)
> **Standard**: State and I/O logic are isolated inside the `SecureStoreEngine` actor. The `@objc` entrypoint initiates an asynchronous `Task` without blocking the main rendering loop or risking cross-thread memory corruption.
```swift
import Foundation
import Capacitor

/// Actor guaranteeing compile-time thread safety for mutable storage and heavy I/O
actor SecureStoreEngine {
    private var cache: [String: String] = [:]

    func write(key: String, value: String) throws {
        // Heavy work runs safely off the main actor without blocking WKWebView rendering
        cache[key] = value
    }

    func read(key: String) -> String? {
        return cache[key]
    }
}

@objc(SecureStorePlugin)
public final class SecureStorePlugin: CAPPlugin, CAPBridgedPlugin {
    public let identifier = "SecureStorePlugin"
    public let jsName = "SecureStore"
    public let pluginMethods: [CAPPluginMethod] = [
        CAPPluginMethod(name: "writeData", returnType: CAPPluginReturnPromise)
    ]

    private let engine = SecureStoreEngine()

    @objc func writeData(_ call: CAPPluginCall) {
        guard let key = call.getString("key"),
              let value = call.getString("value") else {
            call.reject("Missing required string arguments: key and value")
            return
        }

        // Non-blocking Task delegating to isolated actor instance
        Task {
            do {
                try await self.engine.write(key: key, value: value)
                call.resolve(["status": "stored"])
            } catch {
                call.reject("Failed to store value: \(error.localizedDescription)")
            }
        }
    }
}
```

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 Actor-Isolated Plugin Bridge Guardrail

Capacitor 7 Swift Actor-Isolated Plugin Bridge Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict compile-time Swift actor isolation for Capacitor 7 native iOS plugins to eliminate main-thread UI hitching and cross-runtime data races. Guarantees that all asynchronous I/O, heavy computation, and mutable state mutations reside within isolated Swift actors rather than unisolated CAPPlugin instances or synchronous MainActor blocks. 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: Main-Thread Blocking and Unsynchronized Mutable State 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 DriftMain-Thread Blocking and Unsynchronized Mutable State 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 plugin business logic and mutable state within a dedicated Swift `actor` separated from the `CAPPlugin` subclass.

Engineers MUST ALWAYS isolate plugin business logic and mutable state within a dedicated Swift `actor` separated from the `CAPPlugin` subclass.

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 execute blocking operations, file I/O, or cryptographic transformations synchronously inside `@objc func` plugin handlers.

Engineers MUST NOT execute blocking operations, file I/O, or cryptographic transformations synchronously inside `@objc func` plugin handlers.

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 wrap asynchronous bridge calls in structured `Task` blocks and await actor methods before invoking `call.resolve()` or `call.reject()`.

Engineers MUST wrap asynchronous bridge calls in structured `Task` blocks and await actor methods before invoking `call.resolve()` or `call.reject()`.

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

Components NEVER dispatch synchronous work to `DispatchQueue.main.sync` from plugin calls, which causes deadlocks with the WKWebView rendering loop.

Components NEVER dispatch synchronous work to `DispatchQueue.main.sync` from plugin calls, which causes deadlocks with the WKWebView rendering loop.

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

Services MUST ensure that UI-manipulating native calls (such as presenting view controllers) explicitly transition to `@MainActor` using structured concurrency (`await MainActor.run { ... }`).

Services MUST ensure that UI-manipulating native calls (such as presenting view controllers) explicitly transition to `@MainActor` using structured concurrency (`await MainActor.run { ... }`).

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 SHOULD leverage Capacitor 7 typed error handling and propagate typed Swift errors through plugin call rejections rather than failing silently.

Code SHOULD leverage Capacitor 7 typed error handling and propagate typed Swift errors through plugin call rejections rather than failing silently.

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 Actor-Isolated Plugin Bridge Guardrail critical for AI coding assistants?

Enforces strict compile-time Swift actor isolation for Capacitor 7 native iOS plugins to eliminate main-thread UI hitching and cross-runtime data races. Guarantees that all asynchronous I/O, heavy computation, and mutable state mutations reside within isolated Swift actors rather than unisolated CAPPlugin instances or synchronous MainActor blocks. 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 (Main-Thread Blocking and Unsynchronized Mutable State 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