@h1dr0n/skill-pool 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +296 -0
  3. package/bin/cli.js +157 -0
  4. package/package.json +41 -0
  5. package/skills/api/agents/backend-specialist.md +69 -0
  6. package/skills/api/agents/database-optimizer.md +176 -0
  7. package/skills/api/manifest.yaml +20 -0
  8. package/skills/api/rules/auth-security.md +45 -0
  9. package/skills/api/skills/api-patterns/SKILL.md +81 -0
  10. package/skills/api/skills/api-patterns/api-style.md +42 -0
  11. package/skills/api/skills/api-patterns/auth.md +24 -0
  12. package/skills/api/skills/api-patterns/documentation.md +26 -0
  13. package/skills/api/skills/api-patterns/graphql.md +41 -0
  14. package/skills/api/skills/api-patterns/rate-limiting.md +31 -0
  15. package/skills/api/skills/api-patterns/response.md +37 -0
  16. package/skills/api/skills/api-patterns/rest.md +40 -0
  17. package/skills/api/skills/api-patterns/scripts/api_validator.py +211 -0
  18. package/skills/api/skills/api-patterns/security-testing.md +122 -0
  19. package/skills/api/skills/api-patterns/trpc.md +41 -0
  20. package/skills/api/skills/api-patterns/versioning.md +22 -0
  21. package/skills/api/skills/database-patterns.md +126 -0
  22. package/skills/api/skills/deployment-patterns.md +105 -0
  23. package/skills/api/skills/docker-patterns.md +135 -0
  24. package/skills/common/agents/code-reviewer.md +78 -0
  25. package/skills/common/agents/planner.md +80 -0
  26. package/skills/common/agents/security-reviewer.md +82 -0
  27. package/skills/common/agents/software-architect.md +81 -0
  28. package/skills/common/manifest.yaml +25 -0
  29. package/skills/common/rules/coding-style.md +39 -0
  30. package/skills/common/rules/git-workflow.md +33 -0
  31. package/skills/common/rules/security.md +25 -0
  32. package/skills/common/skills/architecture/SKILL.md +55 -0
  33. package/skills/common/skills/architecture/context-discovery.md +43 -0
  34. package/skills/common/skills/architecture/examples.md +94 -0
  35. package/skills/common/skills/architecture/pattern-selection.md +68 -0
  36. package/skills/common/skills/architecture/patterns-reference.md +50 -0
  37. package/skills/common/skills/architecture/trade-off-analysis.md +77 -0
  38. package/skills/common/skills/brainstorming/SKILL.md +163 -0
  39. package/skills/common/skills/brainstorming/dynamic-questioning.md +350 -0
  40. package/skills/common/skills/clean-code.md +99 -0
  41. package/skills/common/skills/code-review-checklist.md +86 -0
  42. package/skills/common/skills/plan-writing/SKILL.md +152 -0
  43. package/skills/common/skills/skill-feedback.md +94 -0
  44. package/skills/common/skills/tdd-workflow.md +130 -0
  45. package/skills/common/skills/verification-loop.md +112 -0
  46. package/skills/cpp/agents/cpp-build-resolver.md +90 -0
  47. package/skills/cpp/agents/cpp-reviewer.md +72 -0
  48. package/skills/cpp/manifest.yaml +15 -0
  49. package/skills/cpp/skills/cpp-coding-standards.md +722 -0
  50. package/skills/cpp/skills/cpp-testing.md +323 -0
  51. package/skills/devops/agents/devops-automator.md +376 -0
  52. package/skills/devops/agents/sre.md +90 -0
  53. package/skills/devops/manifest.yaml +20 -0
  54. package/skills/devops/skills/deployment-patterns.md +427 -0
  55. package/skills/devops/skills/deployment-procedures/SKILL.md +241 -0
  56. package/skills/devops/skills/docker-patterns.md +364 -0
  57. package/skills/devops/skills/e2e-testing.md +326 -0
  58. package/skills/devops/skills/github-ops.md +144 -0
  59. package/skills/django/manifest.yaml +16 -0
  60. package/skills/django/skills/django-patterns.md +734 -0
  61. package/skills/django/skills/django-security.md +593 -0
  62. package/skills/django/skills/django-tdd.md +729 -0
  63. package/skills/django/skills/django-verification.md +469 -0
  64. package/skills/dotnet/agents/csharp-reviewer.md +101 -0
  65. package/skills/dotnet/manifest.yaml +14 -0
  66. package/skills/dotnet/skills/csharp-testing.md +321 -0
  67. package/skills/dotnet/skills/dotnet-patterns.md +321 -0
  68. package/skills/go/agents/code-reviewer.md +76 -0
  69. package/skills/go/agents/go-build-resolver.md +94 -0
  70. package/skills/go/agents/go-reviewer.md +76 -0
  71. package/skills/go/manifest.yaml +17 -0
  72. package/skills/go/rules/go-style.md +55 -0
  73. package/skills/go/skills/golang-patterns.md +674 -0
  74. package/skills/go/skills/golang-testing.md +720 -0
  75. package/skills/java/agents/java-build-resolver.md +153 -0
  76. package/skills/java/agents/java-reviewer.md +92 -0
  77. package/skills/java/manifest.yaml +18 -0
  78. package/skills/java/skills/java-coding-standards.md +147 -0
  79. package/skills/java/skills/jpa-patterns.md +151 -0
  80. package/skills/java/skills/springboot-patterns.md +314 -0
  81. package/skills/java/skills/springboot-security.md +272 -0
  82. package/skills/kotlin/agents/kotlin-build-resolver.md +118 -0
  83. package/skills/kotlin/agents/kotlin-reviewer.md +159 -0
  84. package/skills/kotlin/manifest.yaml +17 -0
  85. package/skills/kotlin/skills/kotlin-coroutines-flows.md +284 -0
  86. package/skills/kotlin/skills/kotlin-patterns.md +711 -0
  87. package/skills/kotlin/skills/kotlin-testing.md +824 -0
  88. package/skills/laravel/manifest.yaml +15 -0
  89. package/skills/laravel/skills/laravel-patterns.md +409 -0
  90. package/skills/laravel/skills/laravel-security.md +279 -0
  91. package/skills/laravel/skills/laravel-tdd.md +277 -0
  92. package/skills/laravel/skills/laravel-verification.md +173 -0
  93. package/skills/mobile/agents/dart-build-resolver.md +201 -0
  94. package/skills/mobile/agents/flutter-reviewer.md +243 -0
  95. package/skills/mobile/manifest.yaml +19 -0
  96. package/skills/mobile/skills/android-clean-architecture.md +339 -0
  97. package/skills/mobile/skills/dart-flutter-patterns.md +563 -0
  98. package/skills/mobile/skills/swiftui-patterns.md +259 -0
  99. package/skills/nestjs/manifest.yaml +13 -0
  100. package/skills/nestjs/skills/nestjs-patterns.md +230 -0
  101. package/skills/perl/manifest.yaml +13 -0
  102. package/skills/perl/skills/perl-patterns.md +504 -0
  103. package/skills/perl/skills/perl-security.md +503 -0
  104. package/skills/perl/skills/perl-testing.md +475 -0
  105. package/skills/python/agents/python-reviewer.md +98 -0
  106. package/skills/python/manifest.yaml +18 -0
  107. package/skills/python/rules/python-style.md +69 -0
  108. package/skills/python/skills/python-patterns/SKILL.md +441 -0
  109. package/skills/python/skills/python-patterns.md +90 -0
  110. package/skills/python/skills/python-testing.md +81 -0
  111. package/skills/rust/agents/rust-build-resolver.md +148 -0
  112. package/skills/rust/agents/rust-reviewer.md +94 -0
  113. package/skills/rust/manifest.yaml +16 -0
  114. package/skills/rust/rules/rust-style.md +107 -0
  115. package/skills/rust/skills/rust-patterns.md +499 -0
  116. package/skills/rust/skills/rust-testing.md +500 -0
  117. package/skills/security/agents/accessibility-auditor.md +316 -0
  118. package/skills/security/agents/security-reviewer.md +108 -0
  119. package/skills/security/manifest.yaml +19 -0
  120. package/skills/security/skills/red-team-tactics/SKILL.md +199 -0
  121. package/skills/security/skills/security-bounty-hunter.md +99 -0
  122. package/skills/security/skills/security-review.md +495 -0
  123. package/skills/security/skills/security-scan.md +165 -0
  124. package/skills/security/skills/vulnerability-scanner/SKILL.md +276 -0
  125. package/skills/security/skills/vulnerability-scanner/checklists.md +121 -0
  126. package/skills/security/skills/vulnerability-scanner/scripts/security_scan.py +458 -0
  127. package/skills/swift/manifest.yaml +16 -0
  128. package/skills/swift/skills/swift-actor-persistence.md +142 -0
  129. package/skills/swift/skills/swift-concurrency.md +216 -0
  130. package/skills/swift/skills/swift-protocol-di-testing.md +190 -0
  131. package/skills/swift/skills/swiftui-patterns.md +259 -0
  132. package/skills/unity/agents/game-designer.md +167 -0
  133. package/skills/unity/agents/unity-architect.md +52 -0
  134. package/skills/unity/agents/unity-editor-tool-developer.md +310 -0
  135. package/skills/unity/agents/unity-multiplayer-engineer.md +321 -0
  136. package/skills/unity/agents/unity-shader-graph-artist.md +269 -0
  137. package/skills/unity/manifest.yaml +21 -0
  138. package/skills/unity/rules/csharp-patterns.md +48 -0
  139. package/skills/unity/rules/unity-specific.md +53 -0
  140. package/skills/unity/skills/systematic-debugging.md +92 -0
  141. package/skills/unity/skills/unity-architecture.md +173 -0
  142. package/skills/unreal/agents/level-designer.md +208 -0
  143. package/skills/unreal/agents/technical-artist.md +229 -0
  144. package/skills/unreal/agents/unreal-multiplayer-architect.md +313 -0
  145. package/skills/unreal/agents/unreal-systems-engineer.md +310 -0
  146. package/skills/unreal/agents/unreal-technical-artist.md +256 -0
  147. package/skills/unreal/agents/unreal-world-builder.md +273 -0
  148. package/skills/unreal/manifest.yaml +21 -0
  149. package/skills/unreal/skills/unreal-patterns.md +183 -0
  150. package/skills/web/agents/frontend-specialist.md +71 -0
  151. package/skills/web/agents/ui-designer.md +383 -0
  152. package/skills/web/agents/ux-architect.md +469 -0
  153. package/skills/web/manifest.yaml +22 -0
  154. package/skills/web/rules/accessibility.md +54 -0
  155. package/skills/web/rules/css-performance.md +52 -0
  156. package/skills/web/skills/e2e-testing.md +132 -0
  157. package/skills/web/skills/frontend-design/SKILL.md +452 -0
  158. package/skills/web/skills/frontend-design/animation-guide.md +331 -0
  159. package/skills/web/skills/frontend-design/color-system.md +311 -0
  160. package/skills/web/skills/frontend-design/decision-trees.md +418 -0
  161. package/skills/web/skills/frontend-design/motion-graphics.md +306 -0
  162. package/skills/web/skills/frontend-design/scripts/accessibility_checker.py +183 -0
  163. package/skills/web/skills/frontend-design/scripts/ux_audit.py +722 -0
  164. package/skills/web/skills/frontend-design/typography-system.md +345 -0
  165. package/skills/web/skills/frontend-design/ux-psychology.md +1116 -0
  166. package/skills/web/skills/frontend-design/visual-effects.md +383 -0
  167. package/skills/web/skills/react-nextjs.md +135 -0
  168. package/skills/web/skills/tailwind-patterns/SKILL.md +269 -0
  169. package/src/adapters/antigravity.js +164 -0
  170. package/src/adapters/claude.js +188 -0
  171. package/src/adapters/cursor.js +161 -0
  172. package/src/adapters/index.js +67 -0
  173. package/src/adapters/windsurf.js +158 -0
  174. package/src/commands/add.js +266 -0
  175. package/src/commands/create.js +127 -0
  176. package/src/commands/diff.js +78 -0
  177. package/src/commands/info.js +88 -0
  178. package/src/commands/init.js +224 -0
  179. package/src/commands/install.js +90 -0
  180. package/src/commands/list.js +54 -0
  181. package/src/commands/remove.js +101 -0
  182. package/src/commands/targets.js +32 -0
  183. package/src/commands/update.js +57 -0
  184. package/src/core/manifest.js +57 -0
  185. package/src/core/plugins.js +86 -0
  186. package/src/core/resolver.js +84 -0
  187. package/src/core/tracker.js +49 -0
  188. package/src/utils/fs.js +80 -0
  189. package/src/utils/git.js +52 -0
@@ -0,0 +1,216 @@
1
+ ---
2
+ name: swift-concurrency-6-2
3
+ description: Swift 6.2 Approachable Concurrency — single-threaded by default, @concurrent for explicit background offloading, isolated conformances for main actor types.
4
+ ---
5
+
6
+ # Swift 6.2 Approachable Concurrency
7
+
8
+ Patterns for adopting Swift 6.2's concurrency model where code runs single-threaded by default and concurrency is introduced explicitly. Eliminates common data-race errors without sacrificing performance.
9
+
10
+ ## When to Activate
11
+
12
+ - Migrating Swift 5.x or 6.0/6.1 projects to Swift 6.2
13
+ - Resolving data-race safety compiler errors
14
+ - Designing MainActor-based app architecture
15
+ - Offloading CPU-intensive work to background threads
16
+ - Implementing protocol conformances on MainActor-isolated types
17
+ - Enabling Approachable Concurrency build settings in Xcode 26
18
+
19
+ ## Core Problem: Implicit Background Offloading
20
+
21
+ In Swift 6.1 and earlier, async functions could be implicitly offloaded to background threads, causing data-race errors even in seemingly safe code:
22
+
23
+ ```swift
24
+ // Swift 6.1: ERROR
25
+ @MainActor
26
+ final class StickerModel {
27
+ let photoProcessor = PhotoProcessor()
28
+
29
+ func extractSticker(_ item: PhotosPickerItem) async throws -> Sticker? {
30
+ guard let data = try await item.loadTransferable(type: Data.self) else { return nil }
31
+
32
+ // Error: Sending 'self.photoProcessor' risks causing data races
33
+ return await photoProcessor.extractSticker(data: data, with: item.itemIdentifier)
34
+ }
35
+ }
36
+ ```
37
+
38
+ Swift 6.2 fixes this: async functions stay on the calling actor by default.
39
+
40
+ ```swift
41
+ // Swift 6.2: OK — async stays on MainActor, no data race
42
+ @MainActor
43
+ final class StickerModel {
44
+ let photoProcessor = PhotoProcessor()
45
+
46
+ func extractSticker(_ item: PhotosPickerItem) async throws -> Sticker? {
47
+ guard let data = try await item.loadTransferable(type: Data.self) else { return nil }
48
+ return await photoProcessor.extractSticker(data: data, with: item.itemIdentifier)
49
+ }
50
+ }
51
+ ```
52
+
53
+ ## Core Pattern — Isolated Conformances
54
+
55
+ MainActor types can now conform to non-isolated protocols safely:
56
+
57
+ ```swift
58
+ protocol Exportable {
59
+ func export()
60
+ }
61
+
62
+ // Swift 6.1: ERROR — crosses into main actor-isolated code
63
+ // Swift 6.2: OK with isolated conformance
64
+ extension StickerModel: @MainActor Exportable {
65
+ func export() {
66
+ photoProcessor.exportAsPNG()
67
+ }
68
+ }
69
+ ```
70
+
71
+ The compiler ensures the conformance is only used on the main actor:
72
+
73
+ ```swift
74
+ // OK — ImageExporter is also @MainActor
75
+ @MainActor
76
+ struct ImageExporter {
77
+ var items: [any Exportable]
78
+
79
+ mutating func add(_ item: StickerModel) {
80
+ items.append(item) // Safe: same actor isolation
81
+ }
82
+ }
83
+
84
+ // ERROR — nonisolated context can't use MainActor conformance
85
+ nonisolated struct ImageExporter {
86
+ var items: [any Exportable]
87
+
88
+ mutating func add(_ item: StickerModel) {
89
+ items.append(item) // Error: Main actor-isolated conformance cannot be used here
90
+ }
91
+ }
92
+ ```
93
+
94
+ ## Core Pattern — Global and Static Variables
95
+
96
+ Protect global/static state with MainActor:
97
+
98
+ ```swift
99
+ // Swift 6.1: ERROR — non-Sendable type may have shared mutable state
100
+ final class StickerLibrary {
101
+ static let shared: StickerLibrary = .init() // Error
102
+ }
103
+
104
+ // Fix: Annotate with @MainActor
105
+ @MainActor
106
+ final class StickerLibrary {
107
+ static let shared: StickerLibrary = .init() // OK
108
+ }
109
+ ```
110
+
111
+ ### MainActor Default Inference Mode
112
+
113
+ Swift 6.2 introduces a mode where MainActor is inferred by default — no manual annotations needed:
114
+
115
+ ```swift
116
+ // With MainActor default inference enabled:
117
+ final class StickerLibrary {
118
+ static let shared: StickerLibrary = .init() // Implicitly @MainActor
119
+ }
120
+
121
+ final class StickerModel {
122
+ let photoProcessor: PhotoProcessor
123
+ var selection: [PhotosPickerItem] // Implicitly @MainActor
124
+ }
125
+
126
+ extension StickerModel: Exportable { // Implicitly @MainActor conformance
127
+ func export() {
128
+ photoProcessor.exportAsPNG()
129
+ }
130
+ }
131
+ ```
132
+
133
+ This mode is opt-in and recommended for apps, scripts, and other executable targets.
134
+
135
+ ## Core Pattern — @concurrent for Background Work
136
+
137
+ When you need actual parallelism, explicitly offload with `@concurrent`:
138
+
139
+ > **Important:** This example requires Approachable Concurrency build settings — SE-0466 (MainActor default isolation) and SE-0461 (NonisolatedNonsendingByDefault). With these enabled, `extractSticker` stays on the caller's actor, making mutable state access safe. **Without these settings, this code has a data race** — the compiler will flag it.
140
+
141
+ ```swift
142
+ nonisolated final class PhotoProcessor {
143
+ private var cachedStickers: [String: Sticker] = [:]
144
+
145
+ func extractSticker(data: Data, with id: String) async -> Sticker {
146
+ if let sticker = cachedStickers[id] {
147
+ return sticker
148
+ }
149
+
150
+ let sticker = await Self.extractSubject(from: data)
151
+ cachedStickers[id] = sticker
152
+ return sticker
153
+ }
154
+
155
+ // Offload expensive work to concurrent thread pool
156
+ @concurrent
157
+ static func extractSubject(from data: Data) async -> Sticker { /* ... */ }
158
+ }
159
+
160
+ // Callers must await
161
+ let processor = PhotoProcessor()
162
+ processedPhotos[item.id] = await processor.extractSticker(data: data, with: item.id)
163
+ ```
164
+
165
+ To use `@concurrent`:
166
+ 1. Mark the containing type as `nonisolated`
167
+ 2. Add `@concurrent` to the function
168
+ 3. Add `async` if not already asynchronous
169
+ 4. Add `await` at call sites
170
+
171
+ ## Key Design Decisions
172
+
173
+ | Decision | Rationale |
174
+ |----------|-----------|
175
+ | Single-threaded by default | Most natural code is data-race free; concurrency is opt-in |
176
+ | Async stays on calling actor | Eliminates implicit offloading that caused data-race errors |
177
+ | Isolated conformances | MainActor types can conform to protocols without unsafe workarounds |
178
+ | `@concurrent` explicit opt-in | Background execution is a deliberate performance choice, not accidental |
179
+ | MainActor default inference | Reduces boilerplate `@MainActor` annotations for app targets |
180
+ | Opt-in adoption | Non-breaking migration path — enable features incrementally |
181
+
182
+ ## Migration Steps
183
+
184
+ 1. **Enable in Xcode**: Swift Compiler > Concurrency section in Build Settings
185
+ 2. **Enable in SPM**: Use `SwiftSettings` API in package manifest
186
+ 3. **Use migration tooling**: Automatic code changes via swift.org/migration
187
+ 4. **Start with MainActor defaults**: Enable inference mode for app targets
188
+ 5. **Add `@concurrent` where needed**: Profile first, then offload hot paths
189
+ 6. **Test thoroughly**: Data-race issues become compile-time errors
190
+
191
+ ## Best Practices
192
+
193
+ - **Start on MainActor** — write single-threaded code first, optimize later
194
+ - **Use `@concurrent` only for CPU-intensive work** — image processing, compression, complex computation
195
+ - **Enable MainActor inference mode** for app targets that are mostly single-threaded
196
+ - **Profile before offloading** — use Instruments to find actual bottlenecks
197
+ - **Protect globals with MainActor** — global/static mutable state needs actor isolation
198
+ - **Use isolated conformances** instead of `nonisolated` workarounds or `@Sendable` wrappers
199
+ - **Migrate incrementally** — enable features one at a time in build settings
200
+
201
+ ## Anti-Patterns to Avoid
202
+
203
+ - Applying `@concurrent` to every async function (most don't need background execution)
204
+ - Using `nonisolated` to suppress compiler errors without understanding isolation
205
+ - Keeping legacy `DispatchQueue` patterns when actors provide the same safety
206
+ - Skipping `model.availability` checks in concurrency-related Foundation Models code
207
+ - Fighting the compiler — if it reports a data race, the code has a real concurrency issue
208
+ - Assuming all async code runs in the background (Swift 6.2 default: stays on calling actor)
209
+
210
+ ## When to Use
211
+
212
+ - All new Swift 6.2+ projects (Approachable Concurrency is the recommended default)
213
+ - Migrating existing apps from Swift 5.x or 6.0/6.1 concurrency
214
+ - Resolving data-race safety compiler errors during Xcode 26 adoption
215
+ - Building MainActor-centric app architectures (most UI apps)
216
+ - Performance optimization — offloading specific heavy computations to background
@@ -0,0 +1,190 @@
1
+ ---
2
+ name: swift-protocol-di-testing
3
+ description: Protocol-based dependency injection for testable Swift code — mock file system, network, and external APIs using focused protocols and Swift Testing.
4
+ origin: ECC
5
+ ---
6
+
7
+ # Swift Protocol-Based Dependency Injection for Testing
8
+
9
+ Patterns for making Swift code testable by abstracting external dependencies (file system, network, iCloud) behind small, focused protocols. Enables deterministic tests without I/O.
10
+
11
+ ## When to Activate
12
+
13
+ - Writing Swift code that accesses file system, network, or external APIs
14
+ - Need to test error handling paths without triggering real failures
15
+ - Building modules that work across environments (app, test, SwiftUI preview)
16
+ - Designing testable architecture with Swift concurrency (actors, Sendable)
17
+
18
+ ## Core Pattern
19
+
20
+ ### 1. Define Small, Focused Protocols
21
+
22
+ Each protocol handles exactly one external concern.
23
+
24
+ ```swift
25
+ // File system access
26
+ public protocol FileSystemProviding: Sendable {
27
+ func containerURL(for purpose: Purpose) -> URL?
28
+ }
29
+
30
+ // File read/write operations
31
+ public protocol FileAccessorProviding: Sendable {
32
+ func read(from url: URL) throws -> Data
33
+ func write(_ data: Data, to url: URL) throws
34
+ func fileExists(at url: URL) -> Bool
35
+ }
36
+
37
+ // Bookmark storage (e.g., for sandboxed apps)
38
+ public protocol BookmarkStorageProviding: Sendable {
39
+ func saveBookmark(_ data: Data, for key: String) throws
40
+ func loadBookmark(for key: String) throws -> Data?
41
+ }
42
+ ```
43
+
44
+ ### 2. Create Default (Production) Implementations
45
+
46
+ ```swift
47
+ public struct DefaultFileSystemProvider: FileSystemProviding {
48
+ public init() {}
49
+
50
+ public func containerURL(for purpose: Purpose) -> URL? {
51
+ FileManager.default.url(forUbiquityContainerIdentifier: nil)
52
+ }
53
+ }
54
+
55
+ public struct DefaultFileAccessor: FileAccessorProviding {
56
+ public init() {}
57
+
58
+ public func read(from url: URL) throws -> Data {
59
+ try Data(contentsOf: url)
60
+ }
61
+
62
+ public func write(_ data: Data, to url: URL) throws {
63
+ try data.write(to: url, options: .atomic)
64
+ }
65
+
66
+ public func fileExists(at url: URL) -> Bool {
67
+ FileManager.default.fileExists(atPath: url.path)
68
+ }
69
+ }
70
+ ```
71
+
72
+ ### 3. Create Mock Implementations for Testing
73
+
74
+ ```swift
75
+ public final class MockFileAccessor: FileAccessorProviding, @unchecked Sendable {
76
+ public var files: [URL: Data] = [:]
77
+ public var readError: Error?
78
+ public var writeError: Error?
79
+
80
+ public init() {}
81
+
82
+ public func read(from url: URL) throws -> Data {
83
+ if let error = readError { throw error }
84
+ guard let data = files[url] else {
85
+ throw CocoaError(.fileReadNoSuchFile)
86
+ }
87
+ return data
88
+ }
89
+
90
+ public func write(_ data: Data, to url: URL) throws {
91
+ if let error = writeError { throw error }
92
+ files[url] = data
93
+ }
94
+
95
+ public func fileExists(at url: URL) -> Bool {
96
+ files[url] != nil
97
+ }
98
+ }
99
+ ```
100
+
101
+ ### 4. Inject Dependencies with Default Parameters
102
+
103
+ Production code uses defaults; tests inject mocks.
104
+
105
+ ```swift
106
+ public actor SyncManager {
107
+ private let fileSystem: FileSystemProviding
108
+ private let fileAccessor: FileAccessorProviding
109
+
110
+ public init(
111
+ fileSystem: FileSystemProviding = DefaultFileSystemProvider(),
112
+ fileAccessor: FileAccessorProviding = DefaultFileAccessor()
113
+ ) {
114
+ self.fileSystem = fileSystem
115
+ self.fileAccessor = fileAccessor
116
+ }
117
+
118
+ public func sync() async throws {
119
+ guard let containerURL = fileSystem.containerURL(for: .sync) else {
120
+ throw SyncError.containerNotAvailable
121
+ }
122
+ let data = try fileAccessor.read(
123
+ from: containerURL.appendingPathComponent("data.json")
124
+ )
125
+ // Process data...
126
+ }
127
+ }
128
+ ```
129
+
130
+ ### 5. Write Tests with Swift Testing
131
+
132
+ ```swift
133
+ import Testing
134
+
135
+ @Test("Sync manager handles missing container")
136
+ func testMissingContainer() async {
137
+ let mockFileSystem = MockFileSystemProvider(containerURL: nil)
138
+ let manager = SyncManager(fileSystem: mockFileSystem)
139
+
140
+ await #expect(throws: SyncError.containerNotAvailable) {
141
+ try await manager.sync()
142
+ }
143
+ }
144
+
145
+ @Test("Sync manager reads data correctly")
146
+ func testReadData() async throws {
147
+ let mockFileAccessor = MockFileAccessor()
148
+ mockFileAccessor.files[testURL] = testData
149
+
150
+ let manager = SyncManager(fileAccessor: mockFileAccessor)
151
+ let result = try await manager.loadData()
152
+
153
+ #expect(result == expectedData)
154
+ }
155
+
156
+ @Test("Sync manager handles read errors gracefully")
157
+ func testReadError() async {
158
+ let mockFileAccessor = MockFileAccessor()
159
+ mockFileAccessor.readError = CocoaError(.fileReadCorruptFile)
160
+
161
+ let manager = SyncManager(fileAccessor: mockFileAccessor)
162
+
163
+ await #expect(throws: SyncError.self) {
164
+ try await manager.sync()
165
+ }
166
+ }
167
+ ```
168
+
169
+ ## Best Practices
170
+
171
+ - **Single Responsibility**: Each protocol should handle one concern — don't create "god protocols" with many methods
172
+ - **Sendable conformance**: Required when protocols are used across actor boundaries
173
+ - **Default parameters**: Let production code use real implementations by default; only tests need to specify mocks
174
+ - **Error simulation**: Design mocks with configurable error properties for testing failure paths
175
+ - **Only mock boundaries**: Mock external dependencies (file system, network, APIs), not internal types
176
+
177
+ ## Anti-Patterns to Avoid
178
+
179
+ - Creating a single large protocol that covers all external access
180
+ - Mocking internal types that have no external dependencies
181
+ - Using `#if DEBUG` conditionals instead of proper dependency injection
182
+ - Forgetting `Sendable` conformance when used with actors
183
+ - Over-engineering: if a type has no external dependencies, it doesn't need a protocol
184
+
185
+ ## When to Use
186
+
187
+ - Any Swift code that touches file system, network, or external APIs
188
+ - Testing error handling paths that are hard to trigger in real environments
189
+ - Building modules that need to work in app, test, and SwiftUI preview contexts
190
+ - Apps using Swift concurrency (actors, structured concurrency) that need testable architecture
@@ -0,0 +1,259 @@
1
+ ---
2
+ name: swiftui-patterns
3
+ description: SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.
4
+ ---
5
+
6
+ # SwiftUI Patterns
7
+
8
+ Modern SwiftUI patterns for building declarative, performant user interfaces on Apple platforms. Covers the Observation framework, view composition, type-safe navigation, and performance optimization.
9
+
10
+ ## When to Activate
11
+
12
+ - Building SwiftUI views and managing state (`@State`, `@Observable`, `@Binding`)
13
+ - Designing navigation flows with `NavigationStack`
14
+ - Structuring view models and data flow
15
+ - Optimizing rendering performance for lists and complex layouts
16
+ - Working with environment values and dependency injection in SwiftUI
17
+
18
+ ## State Management
19
+
20
+ ### Property Wrapper Selection
21
+
22
+ Choose the simplest wrapper that fits:
23
+
24
+ | Wrapper | Use Case |
25
+ |---------|----------|
26
+ | `@State` | View-local value types (toggles, form fields, sheet presentation) |
27
+ | `@Binding` | Two-way reference to parent's `@State` |
28
+ | `@Observable` class + `@State` | Owned model with multiple properties |
29
+ | `@Observable` class (no wrapper) | Read-only reference passed from parent |
30
+ | `@Bindable` | Two-way binding to an `@Observable` property |
31
+ | `@Environment` | Shared dependencies injected via `.environment()` |
32
+
33
+ ### @Observable ViewModel
34
+
35
+ Use `@Observable` (not `ObservableObject`) — it tracks property-level changes so SwiftUI only re-renders views that read the changed property:
36
+
37
+ ```swift
38
+ @Observable
39
+ final class ItemListViewModel {
40
+ private(set) var items: [Item] = []
41
+ private(set) var isLoading = false
42
+ var searchText = ""
43
+
44
+ private let repository: any ItemRepository
45
+
46
+ init(repository: any ItemRepository = DefaultItemRepository()) {
47
+ self.repository = repository
48
+ }
49
+
50
+ func load() async {
51
+ isLoading = true
52
+ defer { isLoading = false }
53
+ items = (try? await repository.fetchAll()) ?? []
54
+ }
55
+ }
56
+ ```
57
+
58
+ ### View Consuming the ViewModel
59
+
60
+ ```swift
61
+ struct ItemListView: View {
62
+ @State private var viewModel: ItemListViewModel
63
+
64
+ init(viewModel: ItemListViewModel = ItemListViewModel()) {
65
+ _viewModel = State(initialValue: viewModel)
66
+ }
67
+
68
+ var body: some View {
69
+ List(viewModel.items) { item in
70
+ ItemRow(item: item)
71
+ }
72
+ .searchable(text: $viewModel.searchText)
73
+ .overlay { if viewModel.isLoading { ProgressView() } }
74
+ .task { await viewModel.load() }
75
+ }
76
+ }
77
+ ```
78
+
79
+ ### Environment Injection
80
+
81
+ Replace `@EnvironmentObject` with `@Environment`:
82
+
83
+ ```swift
84
+ // Inject
85
+ ContentView()
86
+ .environment(authManager)
87
+
88
+ // Consume
89
+ struct ProfileView: View {
90
+ @Environment(AuthManager.self) private var auth
91
+
92
+ var body: some View {
93
+ Text(auth.currentUser?.name ?? "Guest")
94
+ }
95
+ }
96
+ ```
97
+
98
+ ## View Composition
99
+
100
+ ### Extract Subviews to Limit Invalidation
101
+
102
+ Break views into small, focused structs. When state changes, only the subview reading that state re-renders:
103
+
104
+ ```swift
105
+ struct OrderView: View {
106
+ @State private var viewModel = OrderViewModel()
107
+
108
+ var body: some View {
109
+ VStack {
110
+ OrderHeader(title: viewModel.title)
111
+ OrderItemList(items: viewModel.items)
112
+ OrderTotal(total: viewModel.total)
113
+ }
114
+ }
115
+ }
116
+ ```
117
+
118
+ ### ViewModifier for Reusable Styling
119
+
120
+ ```swift
121
+ struct CardModifier: ViewModifier {
122
+ func body(content: Content) -> some View {
123
+ content
124
+ .padding()
125
+ .background(.regularMaterial)
126
+ .clipShape(RoundedRectangle(cornerRadius: 12))
127
+ }
128
+ }
129
+
130
+ extension View {
131
+ func cardStyle() -> some View {
132
+ modifier(CardModifier())
133
+ }
134
+ }
135
+ ```
136
+
137
+ ## Navigation
138
+
139
+ ### Type-Safe NavigationStack
140
+
141
+ Use `NavigationStack` with `NavigationPath` for programmatic, type-safe routing:
142
+
143
+ ```swift
144
+ @Observable
145
+ final class Router {
146
+ var path = NavigationPath()
147
+
148
+ func navigate(to destination: Destination) {
149
+ path.append(destination)
150
+ }
151
+
152
+ func popToRoot() {
153
+ path = NavigationPath()
154
+ }
155
+ }
156
+
157
+ enum Destination: Hashable {
158
+ case detail(Item.ID)
159
+ case settings
160
+ case profile(User.ID)
161
+ }
162
+
163
+ struct RootView: View {
164
+ @State private var router = Router()
165
+
166
+ var body: some View {
167
+ NavigationStack(path: $router.path) {
168
+ HomeView()
169
+ .navigationDestination(for: Destination.self) { dest in
170
+ switch dest {
171
+ case .detail(let id): ItemDetailView(itemID: id)
172
+ case .settings: SettingsView()
173
+ case .profile(let id): ProfileView(userID: id)
174
+ }
175
+ }
176
+ }
177
+ .environment(router)
178
+ }
179
+ }
180
+ ```
181
+
182
+ ## Performance
183
+
184
+ ### Use Lazy Containers for Large Collections
185
+
186
+ `LazyVStack` and `LazyHStack` create views only when visible:
187
+
188
+ ```swift
189
+ ScrollView {
190
+ LazyVStack(spacing: 8) {
191
+ ForEach(items) { item in
192
+ ItemRow(item: item)
193
+ }
194
+ }
195
+ }
196
+ ```
197
+
198
+ ### Stable Identifiers
199
+
200
+ Always use stable, unique IDs in `ForEach` — avoid using array indices:
201
+
202
+ ```swift
203
+ // Use Identifiable conformance or explicit id
204
+ ForEach(items, id: \.stableID) { item in
205
+ ItemRow(item: item)
206
+ }
207
+ ```
208
+
209
+ ### Avoid Expensive Work in body
210
+
211
+ - Never perform I/O, network calls, or heavy computation inside `body`
212
+ - Use `.task {}` for async work — it cancels automatically when the view disappears
213
+ - Use `.sensoryFeedback()` and `.geometryGroup()` sparingly in scroll views
214
+ - Minimize `.shadow()`, `.blur()`, and `.mask()` in lists — they trigger offscreen rendering
215
+
216
+ ### Equatable Conformance
217
+
218
+ For views with expensive bodies, conform to `Equatable` to skip unnecessary re-renders:
219
+
220
+ ```swift
221
+ struct ExpensiveChartView: View, Equatable {
222
+ let dataPoints: [DataPoint] // DataPoint must conform to Equatable
223
+
224
+ static func == (lhs: Self, rhs: Self) -> Bool {
225
+ lhs.dataPoints == rhs.dataPoints
226
+ }
227
+
228
+ var body: some View {
229
+ // Complex chart rendering
230
+ }
231
+ }
232
+ ```
233
+
234
+ ## Previews
235
+
236
+ Use `#Preview` macro with inline mock data for fast iteration:
237
+
238
+ ```swift
239
+ #Preview("Empty state") {
240
+ ItemListView(viewModel: ItemListViewModel(repository: EmptyMockRepository()))
241
+ }
242
+
243
+ #Preview("Loaded") {
244
+ ItemListView(viewModel: ItemListViewModel(repository: PopulatedMockRepository()))
245
+ }
246
+ ```
247
+
248
+ ## Anti-Patterns to Avoid
249
+
250
+ - Using `ObservableObject` / `@Published` / `@StateObject` / `@EnvironmentObject` in new code — migrate to `@Observable`
251
+ - Putting async work directly in `body` or `init` — use `.task {}` or explicit load methods
252
+ - Creating view models as `@State` inside child views that don't own the data — pass from parent instead
253
+ - Using `AnyView` type erasure — prefer `@ViewBuilder` or `Group` for conditional views
254
+ - Ignoring `Sendable` requirements when passing data to/from actors
255
+
256
+ ## References
257
+
258
+ See skill: `swift-actor-persistence` for actor-based persistence patterns.
259
+ See skill: `swift-protocol-di-testing` for protocol-based DI and testing with Swift Testing.