### Swift Protocol Isolation Mismatch Examples Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Demonstrates scenarios where a Swift protocol's isolation requirements do not match its conforming types. Includes examples of under-specified protocols, adding @MainActor isolation to protocols and requirements, handling asynchronous requirements, and suppressing errors with @preconcurrency. ```swift protocol Styler { func applyStyle() } @MainActor class WindowStyler: Styler { func applyStyle() { // access main-actor-isolated state } } ``` ```swift // entire protocol @MainActor protocol Styler { func applyStyle() } // per-requirement protocol Styler { @MainActor func applyStyle() } ``` ```swift protocol Styler { func applyStyle() async } @MainActor class WindowStyler: Styler { // matches, even though it is synchronous and actor-isolated func applyStyle() { } } ``` ```swift @MainActor class WindowStyler: @preconcurrency Styler { func applyStyle() { // implementation body } } ``` ```swift @MainActor class WindowStyler: Styler { nonisolated func applyStyle() { // perhaps this implementation doesn't involve // other MainActor-isolated state } } ``` -------------------------------- ### Install Prerequisites for MCP Servers (Bash) Source: https://github.com/steipete/agent-rules/blob/main/global-rules/steipete-mcps.md This snippet demonstrates how to check for and install essential tools like jq, Node.js, and Ollama using package managers or brew. It also includes a command to verify the presence of required API keys in the user's shell configuration file. ```bash # Check/install required tools command -v jq || brew install jq command -v node || echo "Need Node.js 20+" command -v ollama || brew install ollama # Check API keys in ~/.zshrc grep "OPENAI_API_KEY|GITHUB_PERSONAL_ACCESS_TOKEN|FIRECRAWL_API_KEY" ~/.zshrc ``` -------------------------------- ### Install Project Rules Bash Script Source: https://github.com/steipete/agent-rules/blob/main/global-rules/steipete-mcps.md Clones the agent-rules repository and executes the installation script to set up project-specific slash commands for Claude Code. This involves cloning the repository, navigating into the directory, and running the `install-project-rules.sh` script. ```bash git clone https://github.com/steipete/agent-rules.git cd agent-rules bash install-project-rules.sh ``` -------------------------------- ### Bash Script Usage Instructions Source: https://github.com/steipete/agent-rules/blob/main/global-rules/mcp-sync-rule.md These instructions detail how to save, make executable, and run the provided bash script (`mcp-sync.sh`) for analyzing server configurations. It includes basic usage examples and how to access help. ```bash # Usage Instructions # 1. Save the script: # Save the code above as `mcp-sync.sh` # 2. Make it executable: # chmod +x mcp-sync.sh # 3. Use the script with various options: # Basic Usage: # List all servers and show differences # ./mcp-sync.sh # Show help: # ./mcp-sync.sh --help ``` -------------------------------- ### Create a Concurrent Task in Swift Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Shows how to create a new `Task` to perform work concurrently. The task inherits an isolation domain from its context, which could be an actor, a global actor, or be non-isolated. This example maps a function over a collection within the task. ```swift Task { flock.map(Chicken.produce) } ``` -------------------------------- ### Install Global Claude Code Rules - Bash Source: https://github.com/steipete/agent-rules/blob/main/README.md Shell commands to set up the global Claude Code rules directory and configuration file. This involves creating a directory and optionally adding rule content. ```bash mkdir -p ~/.claude # Create or edit global CLAUDE.md nano ~/.claude/CLAUDE.md # Add desired rules from this repository ``` -------------------------------- ### Swift: Non-Isolated Initializer for Actor-Isolated Type Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Demonstrates initializing an actor-isolated type (`WindowStyler`) with a non-isolated initializer. This allows creating instances of actor-isolated classes from non-isolated contexts. ```swift @MainActor class WindowStyler { nonisolated init(name: String) { self.primaryStyleName = name } } ``` -------------------------------- ### Asynchronous Isolation Boundary Crossing in Swift Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Shows an example of crossing an isolation boundary in Swift using '@MainActor' and 'await'. The 'stockUp' function executes on the MainActor and then calls an asynchronous function 'store' on another actor ('island'), demonstrating suspension points. ```swift @MainActor func stockUp() { // beginning execution on MainActor let food = Pineapple() // switching to the island actor's domain await island.store(food) } ``` -------------------------------- ### Bash Script to Install Project Rules for Claude Code Source: https://context7.com/steipete/agent-rules/llms.txt This bash script automates the installation of project rules into the Claude Code global configuration. It checks for the existence of the 'project-rules' directory and the CLAUDE.md file, adding or updating the import path for project rules. ```bash #!/bin/bash # Install Project Rules for Claude Code echo "🎯 Installing Project Rules for Claude Code" # Check if running from agent-rules directory if [ ! -d "project-rules" ]; then echo "❌ Error: project-rules directory not found" echo " Please run this from the agent-rules repository root" exit 1 fi # Create Claude directory if it doesn't exist mkdir -p ~/.claude # Check if CLAUDE.md exists and add import if [ -f ~/.claude/CLAUDE.md ]; then echo "📝 Found existing ~/.claude/CLAUDE.md" # Check if already imported if grep -q "@.*project-rules" ~/.claude/CLAUDE.md; then echo "✓ Project rules already imported" else echo "" >> ~/.claude/CLAUDE.md echo "# Project Rules" >> ~/.claude/CLAUDE.md echo "@$(pwd)/project-rules" >> ~/.claude/CLAUDE.md echo "✓ Added project rules import" fi else # Create new CLAUDE.md with import cat > ~/.claude/CLAUDE.md << EOF # Claude Code User Memory This file contains personal preferences and custom commands for Claude Code. # Project Rules @$(pwd)/project-rules EOF echo "✓ Created CLAUDE.md with project rules" fi echo "" echo "✅ Installation complete!" ``` -------------------------------- ### JSON MCP Server Configuration Example Source: https://github.com/steipete/agent-rules/blob/main/global-rules/mcp-sync-rule.md This JSON snippet illustrates the structure for defining MCP servers. It includes server names, command execution details (like 'npx'), arguments, and environment variables. This format is used by Claude Desktop and Cursor. ```json { "mcpServers": { "server-name": { "command": "npx", "args": ["-y", "package-name"], "env": { "ENV_VAR": "value" } } } } ``` -------------------------------- ### Create Pull Request with Git and GitHub CLI Source: https://context7.com/steipete/agent-rules/llms.txt This snippet demonstrates how to push a local branch to origin and then create a pull request using the GitHub CLI. It requires Git and the GitHub CLI to be installed and configured. ```bash git push -u origin fix/null-pointer-user-profile gh pr create --title "Fix null pointer in user profile" --body "Fixes #45" ``` -------------------------------- ### VS Code MCP Server Configuration Example Source: https://github.com/steipete/agent-rules/blob/main/global-rules/mcp-sync-rule.md This JSON snippet shows the VS Code specific format for MCP server configurations. It nests server definitions under 'mcp.servers'. Similar to other formats, it specifies command, arguments, and environment variables for each server. ```json { "mcp": { "servers": { "server-name": { "command": "npx", "args": ["-y", "package-name"], "env": { "ENV_VAR": "value" } } } } } ``` -------------------------------- ### SwiftPM Package Manifest: Enable Swift 6 Language Mode Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md A `Package.swift` manifest configured with `swift-tools-version: 6.0` to enable the Swift 6 language mode for all targets within the package. This ensures comprehensive data race safety. ```swift // swift-tools-version: 6.0 let package = Package( name: "MyPackage", targets: [ .target(name: "FullyMigrated"), .target( name: "NotQuiteReadyYet", swiftSettings: [ .swiftLanguageMode(.v5) ] ) ] ) ``` -------------------------------- ### Swift Build: Enable Complete Strict Concurrency Checking Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Command-line invocation for Swift Package Manager (SwiftPM) to enable complete strict concurrency checking during the build process. This helps identify data-race safety issues. ```bash ~ swift build -Xswiftc -strict-concurrency=complete ~ swift test -Xswiftc -strict-concurrency=complete ``` -------------------------------- ### Swift: Wrap Callback-Based Function with Continuation Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md An asynchronous function `updateStyle` that wraps a callback-based version using `withCheckedContinuation`. This allows integrating older APIs that use completion handlers into modern Swift concurrency. ```swift func updateStyle(backgroundColor: ColorComponents) async { await withCheckedContinuation { continuation in updateStyle(backgroundColor: backgroundColor) { continuation.resume() } } } ``` -------------------------------- ### Apply @preconcurrency to Protocols in Swift Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Demonstrates how to use the @preconcurrency directive on a protocol to stage in diagnostics related to global actor isolation. This helps manage actor isolation for protocols that might be adopted by types conforming to different actors. ```swift import Foundation @preconcurrency @MainActor protocol Styler { func applyStyle() } ``` -------------------------------- ### SwiftUI View using SwiftData Query with FetchDescriptor Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Illustrates how to use a SwiftData FetchDescriptor within a SwiftUI view using the @Query property wrapper. This allows for dynamic fetching and display of data that remains synchronized with the data store. The example defines a static fetch descriptor for favorite recipes. ```swift struct FavoriteRecipesList: View { static var fetchDescriptor: FetchDescriptor { FetchDescriptor( predicate: #Predicate { $0.isFavorite == true }, sortBy: [ SortDescriptor(\.createdAt) ] ) } @Query(FavoriteRecipesList.fetchDescriptor) private var favoriteRecipes: [Recipe] var body: some View { List(favoriteRecipes) { RecipeRowView($0) } } } ``` -------------------------------- ### SwiftData Model with Inheritance Example Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Demonstrates a SwiftData @Model class 'Trip' that includes properties like name, destination, dates, relationships, and a boolean to indicate business or personal trips. This serves as a base for potential subclasses, showcasing how inheritance can add flexibility. ```swift @Model class Trip { @Attribute(.preserveValueOnDeletion) var name: String var destination: String @Attribute(.preserveValueOnDeletion) var startDate: Date @Attribute(.preserveValueOnDeletion) var endDate: Date @Relationship(deleteRule: .cascade, inverse: \BucketListItem.trip) var bucketList: [BucketListItem] = BucketListItem @Relationship(deleteRule: .cascade, inverse: \LivingAccommodation.trip) var livingAccommodation: LivingAccommodation? var isBusinessTrip: Boolean = false } ``` -------------------------------- ### Swift Compiler: Enable Swift 6 Language Mode Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Command to compile a Swift file using the Swift 6 language mode. This guarantees the code is free of data races by enabling all Swift 6 concurrency features. ```bash ~ swift -swift-version 6 main.swift ``` -------------------------------- ### Create SwiftData FetchDescriptor with Predicate and Sort Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Demonstrates how to create a SwiftData FetchDescriptor with a predicate to filter models and sort descriptors to order the results. This is useful for selecting specific data subsets based on conditions and a defined sorting logic. The example shows setting a fetch limit. ```swift let descriptor = FetchDescriptor( predicate: #Predicate { $0.isFavorite == true }, sortBy: [ .init(\.createdAt) ] ) descriptor.fetchLimit = 10 let favoriteRecipes = try modelContext.fetch(descriptor) ``` -------------------------------- ### Swift: Handle Cancellation Properly in Async Operations Source: https://github.com/steipete/agent-rules/blob/main/docs/swift-concurrency.md Provides an example of handling task cancellation in Swift using `withTaskCancellationHandler`. It shows how to check for cancellation within a loop and perform cleanup actions when a task is cancelled. ```swift func longRunningOperation() async throws -> Result { try await withTaskCancellationHandler { var progress = 0.0 while progress < 1.0 { try Task.checkCancellation() // Do work... progress += 0.1 try await Task.sleep(for: .seconds(1)) } return result } onCancel: { // Cleanup resources cleanupOperation() } } ``` -------------------------------- ### Limit Concurrency with Task Groups in Swift Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Provides an example of using `withTaskGroup` to limit the number of concurrent tasks created from a large list of work items. This prevents overwhelming the system by creating too many tasks simultaneously and dynamically adds new tasks as others complete. ```swift import Foundation struct Work { func work() async -> Something { return Something() } } struct Something {} func process(_ result: Something) {} let lotsOfWork: [Work] = [] // Assume lotsOfWork is populated let maxConcurrentWorkTasks = min(lotsOfWork.count, 10) await withTaskGroup(of: Something.self) { group in var submittedWork = 0 for _ in 0.. Data? { queue.sync { cache[key] } } func set(_ key: String, value: Data) { queue.async { self.cache[key] = value } } } // Reference types with immutable data final class ImageWrapper: @unchecked Sendable { let cgImage: CGImage init(cgImage: CGImage) { self.cgImage = cgImage } } ``` -------------------------------- ### Swift 6.1: Synchronous Mutual Exclusion Lock (Mutex) Source: https://github.com/steipete/agent-rules/blob/main/docs/swift-concurrency.md Presents SE-0433, the Synchronous Mutual Exclusion Lock (Mutex), for protecting critical sections in non-async code. The example shows a 'Statistics' class using a Mutex to safely update and access shared state. ```swift import Synchronization // For protecting critical sections without async final class Statistics: Sendable { private let mutex = Mutex(.init()) func record(value: Double) { mutex.withLock { stats in stats.count += 1 stats.sum += value } } var average: Double { mutex.withLock { stats in stats.count > 0 ? stats.sum / Double(stats.count) : 0 } } } private struct Stats { var count = 0 var sum = 0.0 } ``` -------------------------------- ### SwiftUI Preview with Mock Data Source: https://context7.com/steipete/agent-rules/llms.txt Shows how to create previews for SwiftUI views using mock data. This is essential for visualizing UI components in isolation and during the development process without needing a full application state. ```swift // 4. Preview with mock data #Preview("User Profile") { let mockModel = UserViewModel() mockModel.username = "John Doe" return UserProfileView(model: mockModel) } ``` -------------------------------- ### ModelContainer Initializer with Schema, MigrationPlan, and Configurations Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Initializes a ModelContainer with a specified schema, migration plan, and configurations. ```APIDOC ## POST /steipete/agent-rules/modelcontainer/init(for:migrationplan:configurations:) ### Description This endpoint initializes a ModelContainer using the specified schema, migration plan, and configurations. ### Method POST ### Endpoint /steipete/agent-rules/modelcontainer/init(for:migrationplan:configurations:) ### Parameters #### Request Body - **schema** (object) - Required - The schema to use for the model container. - **migrationPlan** (object) - Optional - The migration plan to use for schema evolution. - **configurations** (array) - Optional - An array of ModelConfiguration objects. ### Request Example { "schema": { "models": [ "", "" ] }, "migrationPlan": { "stages": [ "" ] }, "configurations": [ { "storage": "" } ] } ### Response #### Success Response (200) - **modelContainer** (object) - The newly created ModelContainer. #### Response Example { "modelContainer": { "schema": { "models": [ "", "" ] }, "migrationPlan": { "stages": [ "" ] }, "configurations": [ { "storage": "" } ] } } ``` -------------------------------- ### Swift 6.1: @isolated(any) Function Types Source: https://github.com/steipete/agent-rules/blob/main/docs/swift-concurrency.md Introduces SE-0431, '@isolated(any) Function Types,' which allows function types to preserve isolation context. This enables functions to be passed around while ensuring they execute within the caller's isolation domain, demonstrated with an actor example. ```swift // Function types that preserve isolation typealias IsolatedHandler = @isolated(any) () async -> Void func withIsolation(_ handler: IsolatedHandler) async { await handler() // Maintains caller's isolation } // Use with actors actor MyActor { func doWork() async { await withIsolation { // Runs on MyActor print("Isolated to: \(self)") } } } ``` -------------------------------- ### ModelContainer Initialization Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Provides details on initializing a SwiftData ModelContainer with various configurations. ```APIDOC ## ModelContainer Initialization ### Description Initializes a `ModelContainer` with the specified schema, migration plan, and configurations. ### Methods * `init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: [ModelConfiguration]) throws` * `convenience init(for: any PersistentModel.Type..., migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) throws` * `convenience init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) throws` ### Types * **`ModelConfiguration`**: Describes the configuration of an app’s schema or specific group of models. * **`Schema`**: Maps model classes to data in the model store and aids in data migration. * **`SchemaMigrationPlan`**: An interface for describing schema evolution and migration between versions. ``` -------------------------------- ### Detecting Priority Inversions in Swift Tasks Source: https://github.com/steipete/agent-rules/blob/main/docs/swift-concurrency.md Provides an example for detecting priority inversions in Swift's `Task` system. A low-priority task is launched, but it might run at a higher priority due to task escalation mechanisms. The `debugPriority` function prints the current task priority, aiding in analysis. ```swift // 3. Detecting priority inversions Task(priority: .low) { await debugPriority() // May run at higher priority due to escalation } func debugPriority() async { print("Current priority: \(Task.currentPriority)") } ``` -------------------------------- ### Using MainActor for UI Code in Swift Source: https://github.com/steipete/agent-rules/blob/main/docs/swift-concurrency.md Illustrates how to apply the @MainActor attribute to ensure UI-related code runs exclusively on the main thread. This example shows a ViewModel that publishes loading and error states, performs background network operations, and automatically returns to the main thread for UI updates. ```swift // Entire class on MainActor @MainActor final class LoginViewModel: ObservableObject { @Published private(set) var isLoading = false @Published private(set) var error: Error? func login(username: String, password: String) async { isLoading = true defer { isLoading = false } do { // This switches to background for network call let user = try await AuthService.shared.login( username: username, password: password ) // Automatically back on MainActor navigateToHome(user: user) } catch { self.error = error } } // Can run on any thread nonisolated func validateEmail(_ email: String) -> Bool { // Email validation logic... } } ``` -------------------------------- ### ModelContainer Initialization Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Initializers for creating a ModelContainer with specified schema, migration plans, and configurations. ```APIDOC ## Creating a Model Container ### Initializer with Schema [`init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: [ModelConfiguration]) throws`](https://developer.apple.com/documentation/swiftdata/modelcontainer/init(for:migrationplan:configurations:)-1czix) Creates a model container using the specified schema, migration plan, and configurations. ### Convenience Initializer with Model Types `convenience init(for: any PersistentModel.Type..., migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) throws` Creates a model container using the specified model types, migration plan, and zero or more configurations. ### Convenience Initializer with Schema `convenience init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) throws` Creates a model container using the specified schema, migration plan, and zero or more configurations. ``` -------------------------------- ### Sync Tool for Configuration Comparison Source: https://github.com/steipete/agent-rules/blob/main/global-rules/steipete-mcps.md Provides a bash script `mcp-sync.sh` for comparing configurations across different applications. This tool is useful for maintaining consistency and identifying discrepancies in settings related to MCP servers and other project configurations. ```bash bash global-rules/mcp-sync.sh ``` -------------------------------- ### Swift Sendable Functions, Closures, and Captures Source: https://github.com/steipete/agent-rules/blob/main/docs/swift-concurrency.md Details how to define and use Sendable function types and closures in Swift. This includes type aliases for asynchronous operations and completion handlers marked as @Sendable, as well as examples of using Sendable closures and managing Sendable captures in contexts like timer callbacks. ```swift // Sendable function types typealias AsyncOperation = @Sendable () async -> Void typealias CompletionHandler = @Sendable (Result) -> Void // Using Sendable closures func performAsync(operation: @Sendable @escaping () async -> Void) { Task { await operation() } } // Sendable captures func createTimer(interval: TimeInterval) -> AsyncStream { AsyncStream { continuation in let timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { _ in continuation.yield(Date()) } continuation.onTermination = { @Sendable _ in timer.invalidate() // Must be Sendable } } } ``` -------------------------------- ### Swift Sendable Protocol and Automatic Conformance Source: https://github.com/steipete/agent-rules/blob/main/docs/swift-concurrency.md Illustrates the Sendable protocol in Swift, which signifies thread-safe types. It shows examples of types that automatically conform to Sendable, including actors, immutable structs and enums, and final classes with immutable storage. It also touches upon @unchecked Sendable for manual safety. ```swift // Sendable indicates thread-safe types public protocol Sendable {} // Automatic conformance for: // 1. Actors (handle synchronization) // 2. Immutable structs/enums // 3. Final classes with immutable storage // 4. @unchecked Sendable for manual safety // Examples of automatic Sendable struct Point: Sendable { // Implicit let x: Double let y: Double } enum Status: Sendable { // Implicit case pending case completed(at: Date) } actor DataManager {} // Implicitly Sendable final class User: Sendable { let id: UUID let name: String // All stored properties are immutable } ``` -------------------------------- ### SwiftData ModelContainer Initialization Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Demonstrates various initializers for creating a ModelContainer in SwiftData. These initializers support different configurations, including specifying the schema, migration plan, and model types. ```swift init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: [ModelConfiguration]) throws convenience init(for: any PersistentModel.Type..., migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) convenience init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) ``` -------------------------------- ### Resolving Actor-Isolated Property Access Errors in Swift Source: https://github.com/steipete/agent-rules/blob/main/docs/swift-concurrency.md Addresses errors where actor-isolated properties are accessed from non-isolated contexts in Swift. The example shows a `DataStore` actor with an `items` property causing an error when accessed via `getItemCount()`. Solutions include making the method `async` (implicitly isolated) or using a computed property. ```swift // ❌ Error: Actor-isolated property accessed without await actor DataStore { var items: [Item] = [] nonisolated func getItemCount() -> Int { items.count // Error: actor-isolated property } } // ✅ Solution 1: Make method async actor DataStore { var items: [Item] = [] func getItemCount() async -> Int { items.count // OK: implicitly isolated to actor } } // ✅ Solution 2: Use computed property actor DataStore { private var items: [Item] = [] var itemCount: Int { items.count // OK: computed property is isolated } } ``` -------------------------------- ### SchemaMigrationPlan Topics Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Provides information about the topics within SchemaMigrationPlan, including managing versioned schemas and migration stages. ```APIDOC ## GET /steipete/agent-rules/schemamigrationplan/topics ### Description This endpoint provides information about the topics available within the SchemaMigrationPlan protocol, focusing on managing versioned schemas and migration stages. ### Method GET ### Endpoint /steipete/agent-rules/schemamigrationplan/topics ### Parameters This endpoint does not have any path, query, or request body parameters. ### Response #### Success Response (200) - **topics** (object) - An object containing details about the SchemaMigrationPlan topics. - **managingVersionedSchemas** (object) - Information about managing versioned schemas. - **schemas** (string) - Description of the 'schemas' static property. - **managingMigrationStages** (object) - Information about managing migration stages. - **stages** (string) - Description of the 'stages' static property. #### Response Example { "topics": { "managingVersionedSchemas": { "schemas": "Required. Describes the 'schemas' static property which returns an array of VersionedSchema types." }, "managingMigrationStages": { "stages": "Describes the 'stages' static property which returns an array of MigrationStage enums." } } } ``` -------------------------------- ### Prime Claude with Project Context (TypeScript/React) Source: https://context7.com/steipete/agent-rules/llms.txt This section describes the '/context-prime' command used to prime an AI assistant (Claude) with project context. It details the steps involved: reading the README, loading AI instructions, listing project structure, reviewing configuration, and identifying test frameworks and CI/CD setup. This process helps the AI understand the project's nature, dependencies, and tooling. ```bash # Usage in Claude Code /context-prime # The assistant will execute: # 1. Read project overview cat README.md # 2. Load AI-specific instructions cat CLAUDE.md # 3. List project structure git ls-files | head -50 # Output: # src/ # components/ # services/ # utils/ # tests/ # package.json # tsconfig.json # 4. Review configuration cat package.json # Output: { # "name": "my-app", # "scripts": { # "build": "tsc", # "test": "vitest", # "lint": "eslint ." # } # } # 5. Identify test framework and CI/CD cat .github/workflows/ci.yml # Result: Assistant understands: # - Project is a TypeScript React application # - Uses Vitest for testing, ESLint for linting # - CI runs on GitHub Actions # - Follows conventional commit format ``` -------------------------------- ### ModelContainer Initialization Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Initializers for creating a ModelContainer with various configurations for schema, migration plans, and model types. ```APIDOC ## ModelContainer Initialization ### Description Provides multiple initializers to create a `ModelContainer` instance, allowing for flexibility in defining the data schema, migration strategies, and model configurations. ### Initializers 1. **`init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: [ModelConfiguration]) throws`** Creates a model container using the specified schema, migration plan, and configurations. 2. **`convenience init(for: any PersistentModel.Type..., migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) throws`** Creates a model container using the specified model types, migration plan, and zero or more configurations. 3. **`convenience init(for: Schema, migrationPlan: (any SchemaMigrationPlan.Type)?, configurations: ModelConfiguration...) throws`** Creates a model container using the specified schema, migration plan, and zero or more configurations. 4. **`convenience init(for: any PersistentModel.Type..., configurations: any DataStoreConfiguration...) throws`** Initializes a ModelContainer with specific persistent model types and data store configurations. 5. **`init(for: Schema, configurations: [any DataStoreConfiguration]) throws`** Initializes a ModelContainer with a specific schema and an array of data store configurations. ``` -------------------------------- ### Swift Migration: Enabling Strict Concurrency Warnings Source: https://github.com/steipete/agent-rules/blob/main/docs/swift-concurrency.md Guides developers on the first step of migrating to strict concurrency in Swift by enabling upcoming features and warnings. This involves configuring the Swift build settings in either the Package.swift file or directly in Xcode Build Settings to 'Strict Concurrency Checking: Complete'. ```swift // In Package.swift .target( name: "MyApp", swiftSettings: [ .enableUpcomingFeature("StrictConcurrency"), .enableUpcomingFeature("ExistentialAny"), .enableUpcomingFeature("ConciseMagicFile") ] ) // Or in Xcode Build Settings // Strict Concurrency Checking: Complete // SWIFT_STRICT_CONCURRENCY = complete ``` -------------------------------- ### ModelContainer Initializer with Schema (Convenience) Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md A convenience initializer for creating a ModelContainer. It takes a schema, an optional migration plan, and a variadic list of model configurations, simplifying the initialization process when you have multiple configurations. ```APIDOC ## POST /modelcontainer/init/convenience ### Description Creates a model container using the specified schema, migration plan, and zero or more configurations. ### Method POST ### Endpoint /modelcontainer/init/convenience ### Parameters #### Request Body - **givenSchema** (object) - Required - A schema that maps your app’s model classes to the associated data in the app’s persistent storage. For more information, see `Schema`. - **migrationPlan** (object) - Optional - A plan that describes the evolution of your app’s schema and how the container migrates between specific versions. For more information, see `SchemaMigrationPlan`. - **configurations** (array of objects) - Required - A list of configurations that describe how the container manages the persisted data for specific groups of models. For more information, see `ModelConfiguration`. ### Request Example ```json { "givenSchema": { "name": "MyAppSchema" }, "migrationPlan": { "type": "MyMigrationPlan" }, "configurations": [ { "forTypes": ["User"], "cloudKitDatabase": "private" }, { "forTypes": ["Settings"], "isStoredInline": true } ] } ``` ### Response #### Success Response (200) - **containerId** (string) - A unique identifier for the created model container. #### Response Example ```json { "containerId": "container-67890" } ``` ``` -------------------------------- ### Handling ModelContext Save Notifications Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Shows how to subscribe to the ModelContext.willSave notification to perform actions before a save operation. This example updates a state variable when the context is about to save changes. ```swift struct LastModifiedView: View { @Environment(\.modelContext) private var context @State private var lastModified = Date.now private var didSavePublisher: NotificationCenter.Publisher { NotificationCenter.default .publisher(for: ModelContext.willSave, object: context) } var body: some View { Text(lastModified.formatted(date: .abbreviated, time: .shortened)) .onReceive(didSavePublisher) { _ in lastModified = Date.now } } } ``` -------------------------------- ### Configure MCP Servers for Cursor (JSON) Source: https://github.com/steipete/agent-rules/blob/main/global-rules/steipete-mcps.md This JSON configuration is for Cursor's `~/.cursor/mcp.json` file. It demonstrates how to add MCP servers like Peekaboo and Context7, including environment variables for API keys. It also shows the specific configuration for GitMCP using SSE transport. ```json { "mcpServers": { "peekaboo": { "command": "npx", "args": ["-y", "@steipete/peekaboo-mcp@beta"], "env": { "PEEKABOO_AI_PROVIDERS": "openai/gpt-4o,ollama/llava:latest", "OPENAI_API_KEY": "sk-..." } }, "context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp@latest"] }, "gitmcp": { "transport": "sse", "url": "https://gitmcp.io/docs" } // Add other servers following the same pattern } } ``` -------------------------------- ### SwiftData: Get Models Marked for Deletion Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Returns an array of models that are marked for removal from persistent storage during the next save operation. This allows for reviewing deletions before they are finalized. ```swift var deletedModelsArray: [any PersistentModel] ``` -------------------------------- ### SwiftData: Get Models with Unsaved Changes Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Retrieves an array of all registered models that currently have unsaved modifications. This property provides access to the specific models needing attention. ```swift var changedModelsArray: [any PersistentModel] ``` -------------------------------- ### ModelContainer Initializers and Properties Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Provides details on initializing a ModelContainer and accessing its configuration properties. ```APIDOC ## init(for:configurations:) Swift 5.9+ convenience init( for forTypes: any PersistentModel.Type..., configurations: any DataStoreConfiguration... ) throws ### Description Initializes a ModelContainer with specified model types and data store configurations. ### Method `init` (Initializer) ### Endpoint N/A (Initializer) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift let container = try ModelContainer(for: MyModel.self, configurations: .default) ``` ### Response #### Success Response (200) N/A (Initializer) #### Response Example N/A (Initializer) --- ## migrationPlan Swift 5.9+ final let migrationPlan: (any SchemaMigrationPlan.Type)? ### Description Provides a reference to the migration plan specified during container initialization. Returns `nil` if no migration plan was specified. ### Method `migrationPlan` (Instance Property) ### Endpoint N/A (Property Access) ### Parameters None ### Request Example ```swift let plan = modelContainer.migrationPlan ``` ### Response #### Success Response (200) - **migrationPlan** (any SchemaMigrationPlan.Type)? - The migration plan or nil. #### Response Example ```json { "migrationPlan": "MyMigrationPlan" } ``` --- ## schema `let schema: Schema` ### Description The schema that maps your app’s model classes to the associated data in the app’s persistent storage. ### Method `schema` (Instance Property) ### Endpoint N/A (Property Access) ### Parameters None ### Request Example ```swift let currentSchema = modelContainer.schema ``` ### Response #### Success Response (200) - **schema** (Schema) - The schema definition. #### Response Example ```json { "schema": { "version": 1, "models": [ { "name": "MyModel", "fields": [ { "name": "id", "type": "UUID" } ] } ] } } ``` ``` -------------------------------- ### Define Non-Isolated Function in Swift Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Demonstrates a top-level function declared without any explicit isolation domain, making it non-isolated by default. This function can be called from any context. ```swift func sailTheSea() { } ``` -------------------------------- ### Define Tool with Comprehensive Descriptions and Schemas Source: https://context7.com/steipete/agent-rules/llms.txt Defines a server tool named 'capture_screenshot' with a detailed description including the application version and an input schema. The schema specifies optional parameters like 'analyze', 'window_index', and 'provider', with descriptions for each. This helps clients understand and utilize the tool effectively. ```typescript // 3. Tool with comprehensive descriptions server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [{ name: 'capture_screenshot', description: `Capture and analyze screenshots (v${VERSION}). ` + 'Captures screen content and optionally processes with AI for analysis.', inputSchema: { type: 'object', properties: { analyze: { type: 'boolean', description: 'Optional: Enable AI analysis of the screenshot. ' + 'Default: false' }, window_index: { type: 'number', description: 'Optional: Specific window to capture (0-based index). ' + 'Default: captures active window' }, provider: { type: 'string', description: 'Optional: AI provider to use (openai/gpt-4o or ' + 'ollama/llava:latest). Default: first configured provider' } }, required: [] // All parameters are optional } }] })); ``` -------------------------------- ### Schema.Relationship.Option API Source: https://github.com/steipete/agent-rules/blob/main/docs/swiftdata.md Documentation for Schema.Relationship.Option, including its equality operator, initializer, and properties. ```APIDOC ## ==(_:_:) Swift 5.9+ func == (lhs: Schema.Relationship.Option, rhs: Schema.Relationship.Option) -> Bool ### Description Returns a Boolean value indicating whether two Schema.Relationship.Option values are equal. ### Method `==` (Operator) ### Endpoint N/A (Operator Overload) ### Parameters - **lhs** (Schema.Relationship.Option) - The left-hand side option to compare. - **rhs** (Schema.Relationship.Option) - The right-hand side option to compare. ### Request Example ```swift let optionsEqual = Schema.Relationship.Option.unique == Schema.Relationship.Option.unique ``` ### Response #### Success Response (200) - **Bool** - `true` if the options are equal, `false` otherwise. #### Response Example ```json { "result": true } ``` --- ## init(from:) Swift 5.9+ init?(from decoder: Decoder) ### Description Initializes a Schema.Relationship.Option from a decoder. ### Method `init(from:)` (Initializer) ### Endpoint N/A (Initializer) ### Parameters - **decoder** (Decoder) - The decoder to read data from. ### Request Example ```swift // Example usage within a decoding context let option = try JSONDecoder().decode(Schema.Relationship.Option.self, from: jsonData) ``` ### Response #### Success Response (200) N/A (Initializer) #### Response Example N/A (Initializer) --- ## debugDescription Swift 5.9+ var debugDescription: String { get } ### Description A textual representation of the Schema.Relationship.Option instance, suitable for debugging. ### Method `debugDescription` (Instance Property) ### Endpoint N/A (Property Access) ### Parameters None ### Request Example ```swift let option = Schema.Relationship.Option.unique let description = String(reflecting: option) print(description) ``` ### Response #### Success Response (200) - **String** - The debug description of the option. #### Response Example ```json { "debugDescription": "unique" } ``` --- ## hashValue Swift 5.9+ var hashValue: Int { get } ### Description The hash value for the Schema.Relationship.Option instance. ### Method `hashValue` (Instance Property) ### Endpoint N/A (Property Access) ### Parameters None ### Request Example ```swift let option = Schema.Relationship.Option.unique let hash = option.hashValue ``` ### Response #### Success Response (200) - **Int** - The hash value of the option. #### Response Example ```json { "hashValue": 123456789 } ``` --- ## encode(to:) Swift 5.9+ func encode(to encoder: Encoder) ### Description Encodes the Schema.Relationship.Option instance to the given encoder. ### Method `encode(to:)` (Instance Method) ### Endpoint N/A (Method Call) ### Parameters - **encoder** (Encoder) - The encoder to write data to. ### Request Example ```swift let option = Schema.Relationship.Option.unique let data = try JSONEncoder().encode(option) ``` ### Response #### Success Response (200) N/A (Method Call) #### Response Example N/A (Method Call) --- ## hash(into:) Swift 5.9+ func hash(into hasher: inout Hasher) ### Description Hashes the essential components of the Schema.Relationship.Option instance. ### Method `hash(into:)` (Instance Method) ### Endpoint N/A (Method Call) ### Parameters - **hasher** (inout Hasher) - The hasher to use for combining the hashable values. ### Request Example ```swift var hasher = Hasher() Schema.Relationship.Option.unique.hash(into: &hasher) let hash = hasher.finalize() ``` ### Response #### Success Response (200) N/A (Method Call) #### Response Example N/A (Method Call) --- ## unique Swift 5.9+ static let unique: Schema.Relationship.Option ### Description Represents a unique relationship option for schema relationships. ### Method `unique` (Static Property) ### Endpoint N/A (Property Access) ### Parameters None ### Request Example ```swift let uniqueOption = Schema.Relationship.Option.unique ``` ### Response #### Success Response (200) - **Schema.Relationship.Option** - The unique option. #### Response Example ```json { "option": "unique" } ``` ``` -------------------------------- ### Swift: Non-Isolated Deinitializer for Actor Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Illustrates a non-isolated deinitializer for an actor (`BackgroundStyler`). Deinitializers are always non-isolated, even for actor types, and can perform asynchronous cleanup operations. ```swift actor BackgroundStyler { private let store = StyleStore() deinit { Task { [store] in await store.stopNotifications() } } } ``` -------------------------------- ### Swift Sendable Type Conformance for Isolation Boundaries Source: https://github.com/steipete/agent-rules/blob/main/swift6-migration-compact.md Illustrates how to handle isolation boundary issues in Swift concurrency, particularly concerning Sendable types. Shows implicit Sendable conformance for non-public value types, explicit Sendable conformance, and the use of @preconcurrency import for unmigrated modules. Also covers latent isolation and strategies for making types Sendable. ```swift public struct ColorComponents { public let red: Float public let green: Float public let blue: Float } @MainActor func applyBackground(_ color: ColorComponents) { } func updateStyle(backgroundColor: ColorComponents) async { await applyBackground(backgroundColor) } ``` ```swift public struct ColorComponents: Sendable { // ... } ``` ```swift // ColorComponents defined here @preconcurrency import UnmigratedModule func updateStyle(backgroundColor: ColorComponents) async { // crossing an isolation domain here await applyBackground(backgroundColor) } ``` ```swift @MainActor func applyBackground(_ color: ColorComponents) { } func updateStyle(backgroundColor: ColorComponents) async { await applyBackground(backgroundColor) } ``` ```swift @MainActor func updateStyle(backgroundColor: ColorComponents) async { applyBackground(backgroundColor) } ``` ```swift func updateStyle(backgroundColor: sending ColorComponents) async { // this boundary crossing can now be proven safe in all cases await applyBackground(backgroundColor) } ``` ```swift @MainActor public struct ColorComponents { // ... } ``` ```swift actor Style { private var background: ColorComponents } ``` ```swift class Style: @unchecked Sendable { private var background: ColorComponents private let queue: DispatchQueue } ``` ```swift final class Style: Sendable { private let background: ColorComponents } ```