This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: swift-6-noncopyable-resource-sandbox

Swift 6 Concurrency Non-Copyable Resource Sandbox Standard

Enforces strict single-ownership semantics for low-level system and hardware handles (e.g., POSIX file descriptors, GPU command buffers, Secure Enclave keys) using Swift 6 non-copyable types (~Copyable) coupled with actor isolation. Eliminates data races, reference-counting overhead, and dangling handle leaks by verifying exclusive linear consumption at compile time.

Prohibited Anti-Pattern: Wrapping Raw OS Hardware Handles in Reference-Counted Classes or Unchecked Copyable Structs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Swift 6 Concurrency Non-Copyable Resource Sandbox Standard - Enforces strict single-ownership semantics for low-level system and hardware handles (e.g., POSIX file descriptors, GPU command buffers, Secure Enclave keys) using Swift 6 non-copyable types (~Copyable) coupled with actor isolation. Eliminates data races, reference-counting overhead, and dangling handle leaks by verifying exclusive linear consumption at compile time.
globs: **/*.swift
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/swift-6-noncopyable-resource-sandbox"
---

# Swift 6 Concurrency Non-Copyable Resource Sandbox Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Wrapping Raw OS Hardware Handles in Reference-Counted Classes or Unchecked Copyable Structs

## System Constraints
You are a Principal Mobile Systems Architect enforcing the Swift 6 Concurrency Non-Copyable Resource Sandbox Standard. You mandate that critical hardware resources, secure primitives, and low-level kernel handles be declared as non-copyable structs (`~Copyable`) with strict consumption (`consuming`/`borrowing`) mechanics. You must reject any design that relies on ARC, classes, or unprotected Sendable bypasses to manage unique hardware lifecycles.

## Strict Guidelines
- Engineers MUST ALWAYS declare direct wrappers around hardware/kernel handles (file descriptors, audio buffers, camera IO surfaces) as non-copyable structs using `struct Handle: ~Copyable`.
- Engineers MUST implement a `deinit` block on non-copyable handles to guarantee deterministic, zero-ARC resource release.
- Engineers MUST NOT bridge raw hardware descriptors into standard reference-counted classes (`final class Handle`) to prevent multi-owner race conditions and unbounded release timing.
- Methods that permanently transition, seal, or invalidate a resource MUST mark the parameter as `consuming` and prevent subsequent reuse by the caller.
- Non-copyable resources MUST NOT be marked `@unchecked Sendable`; cross-actor transfers must occur strictly via consuming transfer boundaries across isolated actor domains.

## Bad vs Good Implementations
### Hardware Descriptor Management: ARC Class vs. Non-Copyable Sandbox

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using an @unchecked Sendable reference-type introduces race hazards, non-deterministic deallocation through retained references, and risks silent use-after-free or double-close bugs across actor boundaries.
```swift
import Foundation

// ANTI-PATTERN: Wrapping POSIX descriptor in a class subject to ARC
public final class HardwarePort: @unchecked Sendable {
    private var rawFd: Int32
    
    public init(port: Int32) {
        self.rawFd = port
    }
    
    public func writeBytes(_ buffer: UnsafeRawBufferPointer) {
        // Danger: Concurrent callers can invoke write or close simultaneously
        Darwin.write(rawFd, buffer.baseAddress, buffer.count)
    }
    
    public func closePort() {
        // Race condition: Double close or use-after-close across thread boundaries
        if rawFd != -1 {
            Darwin.close(rawFd)
            rawFd = -1
        }
    }
    
    deinit {
        if rawFd != -1 { Darwin.close(rawFd) }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The non-copyable struct (`~Copyable`) guarantees exactly one owner without ARC overhead. `discard self` alongside `consuming` guarantees compile-time prevention of use-after-free and double-close bugs, while actor confinement orchestrates concurrency.
```swift
import Darwin

// PRODUCTION FIX: Non-copyable resource managed by linear ownership
public struct HardwareHandle: ~Copyable {
    private let fd: Int32
    
    public init(path: String) throws {
        let descriptor = Darwin.open(path, O_RDWR)
        guard descriptor >= 0 else {
            throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
        }
        self.fd = descriptor
    }
    
    public borrowing func write(data: UnsafeRawBufferPointer) throws {
        let written = Darwin.write(fd, data.baseAddress, data.count)
        guard written >= 0 else {
            throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)
        }
    }
    
    // Explicit consumption consumes ownership, ensuring single close
    public consuming func decommission() {
        Darwin.close(fd)
        discard self
    }
    
    deinit {
        Darwin.close(fd)
    }
}

public actor HardwareSandbox {
    private var activeHandle: HardwareHandle?
    
    public func install(handle: consuming HardwareHandle) {
        self.activeHandle = handle
    }
    
    public func transmit(buffer: UnsafeRawBufferPointer) throws {
        guard let activeHandle else { throw POSIXError(.EBADF) }
        try activeHandle.write(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: Swift 6 Concurrency Non-Copyable Resource Sandbox Standard

Swift 6 Concurrency Non-Copyable Resource Sandbox Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces strict single-ownership semantics for low-level system and hardware handles (e.g., POSIX file descriptors, GPU command buffers, Secure Enclave keys) using Swift 6 non-copyable types (~Copyable) coupled with actor isolation. Eliminates data races, reference-counting overhead, and dangling handle leaks by verifying exclusive linear consumption at compile time. 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: Wrapping Raw OS Hardware Handles in Reference-Counted Classes or Unchecked Copyable Structs 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 DriftWrapping Raw OS Hardware Handles in Reference-Counted Classes or Unchecked Copyable StructsCritical
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 declare direct wrappers around hardware/kernel handles (file descriptors, audio buffers, camera IO surfaces) as non-copyable structs using `struct Handle

Engineers MUST ALWAYS declare direct wrappers around hardware/kernel handles (file descriptors, audio buffers, camera IO surfaces) as non-copyable structs using `struct Handle: ~Copyable`.

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 implement a `deinit` block on non-copyable handles to guarantee deterministic, zero-ARC resource release.

Engineers MUST implement a `deinit` block on non-copyable handles to guarantee deterministic, zero-ARC resource release.

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 bridge raw hardware descriptors into standard reference-counted classes (`final class Handle`) to prevent multi-owner race conditions and unbounded release timing.

Engineers MUST NOT bridge raw hardware descriptors into standard reference-counted classes (`final class Handle`) to prevent multi-owner race conditions and unbounded release timing.

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

Methods that permanently transition, seal, or invalidate a resource MUST mark the parameter as `consuming` and prevent subsequent reuse by the caller.

Methods that permanently transition, seal, or invalidate a resource MUST mark the parameter as `consuming` and prevent subsequent reuse by the caller.

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

Non-copyable resources MUST NOT be marked `@unchecked Sendable`

Non-copyable resources MUST NOT be marked `@unchecked Sendable`; cross-actor transfers must occur strictly via consuming transfer boundaries across 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.
Technical Questions & Answers

Frequently Asked Technical Questions

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

Q:Why is Swift 6 Concurrency Non-Copyable Resource Sandbox Standard critical for AI coding assistants?

Enforces strict single-ownership semantics for low-level system and hardware handles (e.g., POSIX file descriptors, GPU command buffers, Secure Enclave keys) using Swift 6 non-copyable types (~Copyable) coupled with actor isolation. Eliminates data races, reference-counting overhead, and dangling handle leaks by verifying exclusive linear consumption at compile time. 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 (Wrapping Raw OS Hardware Handles in Reference-Counted Classes or Unchecked Copyable Structs) 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

Swift