engsys 1.0.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 (173) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +202 -0
  3. package/core/agents/aaron.md +152 -0
  4. package/core/agents/bert.md +115 -0
  5. package/core/agents/isabelle.md +136 -0
  6. package/core/agents/jody.md +150 -0
  7. package/core/agents/leith.md +111 -0
  8. package/core/agents/marcelo.md +282 -0
  9. package/core/agents/melvin.md +101 -0
  10. package/core/agents/nyx.md +152 -0
  11. package/core/agents/otto.md +168 -0
  12. package/core/agents/patricia.md +283 -0
  13. package/core/commands/design-audit-local.md +155 -0
  14. package/core/commands/design-audit.md +235 -0
  15. package/core/commands/design-critique.md +96 -0
  16. package/core/commands/file-issue.md +22 -0
  17. package/core/commands/generate-project.md +45 -0
  18. package/core/commands/implement-issue.md +37 -0
  19. package/core/commands/implement-project.md +40 -0
  20. package/core/commands/naturalize.md +61 -0
  21. package/core/commands/pre-push.md +29 -0
  22. package/core/commands/prep-review-collect.md +130 -0
  23. package/core/commands/prep-review-finalize.md +121 -0
  24. package/core/commands/prep-review-publish.md +113 -0
  25. package/core/commands/prep-review.md +65 -0
  26. package/core/commands/project-closeout.md +25 -0
  27. package/core/skills/agentic-eval/SKILL.md +195 -0
  28. package/core/skills/chrome-devtools/SKILL.md +97 -0
  29. package/core/skills/code-review/SKILL.md +26 -0
  30. package/core/skills/gh-cli/SKILL.md +2202 -0
  31. package/core/skills/git-commit/SKILL.md +124 -0
  32. package/core/skills/git-workflow-agents/SKILL.md +462 -0
  33. package/core/skills/git-workflow-agents/reference.md +220 -0
  34. package/core/skills/github-actions/SKILL.md +190 -0
  35. package/core/skills/github-issues/SKILL.md +154 -0
  36. package/core/skills/llm-structured-outputs/SKILL.md +323 -0
  37. package/core/skills/llm-structured-outputs/references/provider-details.md +392 -0
  38. package/core/skills/pre-push/SKILL.md +115 -0
  39. package/core/skills/refactor/SKILL.md +645 -0
  40. package/core/skills/web-design-reviewer/SKILL.md +371 -0
  41. package/core/skills/webapp-testing/SKILL.md +127 -0
  42. package/core/skills/webapp-testing/test-helper.js +56 -0
  43. package/core/templates/CLAUDE.md.tmpl +98 -0
  44. package/core/templates/adr-template.md +67 -0
  45. package/core/templates/gh-issue-templates/bug.md +39 -0
  46. package/core/templates/gh-issue-templates/content.md +42 -0
  47. package/core/templates/gh-issue-templates/enhancement.md +36 -0
  48. package/core/templates/gh-issue-templates/feature.md +39 -0
  49. package/core/templates/gh-issue-templates/infrastructure.md +41 -0
  50. package/core/templates/post-edit-reminders.sh.tmpl +19 -0
  51. package/core/templates/settings.json.tmpl +90 -0
  52. package/core/templates/settings.local.json.tmpl +3 -0
  53. package/core/workflows/agent-implementation-workflow.md +346 -0
  54. package/core/workflows/generate-project.md +258 -0
  55. package/core/workflows/implement-project-workflow.md +190 -0
  56. package/core/workflows/issue-tracking.md +89 -0
  57. package/core/workflows/project-closeout-ceremony.md +77 -0
  58. package/core/workflows/review-workflow.md +266 -0
  59. package/engsys.config.example.yaml +46 -0
  60. package/install +202 -0
  61. package/lessons-library/README.md +80 -0
  62. package/lessons-library/async-callbacks-verify-liveness.md +15 -0
  63. package/lessons-library/change-isnt-done-until-every-surface-updated.md +15 -0
  64. package/lessons-library/claim-then-act-for-irreversible-ops.md +16 -0
  65. package/lessons-library/co-commit-entangled-work.md +15 -0
  66. package/lessons-library/dependabot-triage-playbook.md +17 -0
  67. package/lessons-library/deploy-by-digest-and-verify-the-running-revision.md +15 -0
  68. package/lessons-library/enforce-your-guarantee-at-your-boundary.md +16 -0
  69. package/lessons-library/gate-changes-on-measurement-not-vibes.md +15 -0
  70. package/lessons-library/iac-first-no-console-changes.md +15 -0
  71. package/lessons-library/independent-objective-review-gate.md +15 -0
  72. package/lessons-library/keep-an-immutable-source-of-truth.md +15 -0
  73. package/lessons-library/long-agent-runs-checkpoint-not-poll.md +15 -0
  74. package/lessons-library/model-identity-with-stable-ids-and-provenance.md +15 -0
  75. package/lessons-library/operator-choices-are-first-class.md +15 -0
  76. package/lessons-library/prefer-tool-enforced-structured-output.md +15 -0
  77. package/lessons-library/prove-causation-before-acting.md +15 -0
  78. package/lessons-library/re-read-state-before-acting.md +14 -0
  79. package/lessons-library/read-layer-tolerates-unbackfilled-rows.md +15 -0
  80. package/lessons-library/shell-safety-pipefail-and-validate-before-teardown.md +14 -0
  81. package/lessons-library/shift-correctness-left-and-distrust-false-greens.md +15 -0
  82. package/lessons-library/stray-control-bytes-hide-changes.md +14 -0
  83. package/lessons-library/tests-can-assert-the-bug.md +15 -0
  84. package/lessons-library/verify-ground-truth-not-reports.md +15 -0
  85. package/lessons-library/worktrees-need-bootstrap-from-origin-main.md +15 -0
  86. package/lib/commands.js +356 -0
  87. package/lib/generate-team-avatars.mjs +251 -0
  88. package/lib/manifest.js +155 -0
  89. package/lib/render.js +135 -0
  90. package/lib/selftest.js +90 -0
  91. package/lib/util.js +89 -0
  92. package/lib/yaml.js +156 -0
  93. package/optional-agents/gary.md +86 -0
  94. package/optional-agents/jos.md +136 -0
  95. package/optional-agents/sandy.md +101 -0
  96. package/optional-agents/steve.md +161 -0
  97. package/package.json +43 -0
  98. package/stacks/cloud/aws/claude.fragment.md +17 -0
  99. package/stacks/cloud/aws/settings.fragment.json +39 -0
  100. package/stacks/cloud/aws/skills/aws-deployment-preflight/SKILL.md +165 -0
  101. package/stacks/cloud/aws/skills/cloud-architecture-aws/SKILL.md +265 -0
  102. package/stacks/cloud/azure/claude.fragment.md +17 -0
  103. package/stacks/cloud/azure/settings.fragment.json +45 -0
  104. package/stacks/cloud/azure/skills/azure-deployment-preflight/SKILL.md +175 -0
  105. package/stacks/cloud/azure/skills/cloud-architecture-azure/SKILL.md +211 -0
  106. package/stacks/cloud/cloudflare/claude.fragment.md +21 -0
  107. package/stacks/cloud/cloudflare/settings.fragment.json +31 -0
  108. package/stacks/cloud/cloudflare/skills/cloud-architecture-cloudflare/SKILL.md +294 -0
  109. package/stacks/cloud/cloudflare/skills/cloudflare-deployment-preflight/SKILL.md +175 -0
  110. package/stacks/cloud/gcp/claude.fragment.md +17 -0
  111. package/stacks/cloud/gcp/settings.fragment.json +40 -0
  112. package/stacks/cloud/gcp/skills/cloud-architecture-gcp/SKILL.md +208 -0
  113. package/stacks/cloud/gcp/skills/gcp-deployment-preflight/SKILL.md +137 -0
  114. package/stacks/db/mongo/skills/mongo-conventions/SKILL.md +96 -0
  115. package/stacks/db/prisma/claude.fragment.md +49 -0
  116. package/stacks/db/prisma/skills/docker-database-package-copy/SKILL.md +44 -0
  117. package/stacks/db/prisma/skills/prisma-conventions/SKILL.md +37 -0
  118. package/stacks/domain/mobile-growth/skills/apple-ads/SKILL.md +184 -0
  119. package/stacks/domain/mobile-growth/skills/apple-ads/references/benchmark-notes.md +47 -0
  120. package/stacks/domain/mobile-growth/skills/apple-ads/references/official-links.md +53 -0
  121. package/stacks/domain/mobile-growth/skills/google-play-growth/SKILL.md +197 -0
  122. package/stacks/domain/mobile-growth/skills/google-play-growth/references/benchmark-notes.md +47 -0
  123. package/stacks/domain/mobile-growth/skills/google-play-growth/references/official-links.md +45 -0
  124. package/stacks/iac/bicep/claude.fragment.md +14 -0
  125. package/stacks/iac/bicep/settings.fragment.json +20 -0
  126. package/stacks/iac/bicep/skills/iac-bicep/SKILL.md +113 -0
  127. package/stacks/iac/cdk/claude.fragment.md +14 -0
  128. package/stacks/iac/cdk/settings.fragment.json +23 -0
  129. package/stacks/iac/cdk/skills/iac-cdk/SKILL.md +104 -0
  130. package/stacks/iac/terraform/claude.fragment.md +13 -0
  131. package/stacks/iac/terraform/settings.fragment.json +25 -0
  132. package/stacks/iac/terraform/skills/iac-terraform/SKILL.md +93 -0
  133. package/stacks/iac/terraform/skills/terraform-conventions/SKILL.md +87 -0
  134. package/stacks/lang/kotlin/skills/android-testing/SKILL.md +263 -0
  135. package/stacks/lang/kotlin/skills/jetpack-compose/SKILL.md +264 -0
  136. package/stacks/lang/kotlin/skills/kotlin-coroutines/SKILL.md +329 -0
  137. package/stacks/lang/python/skills/python-conventions/SKILL.md +61 -0
  138. package/stacks/lang/shell/skills/shell-scripting/SKILL.md +110 -0
  139. package/stacks/lang/swift/skills/swift-concurrency/SKILL.md +423 -0
  140. package/stacks/lang/swift/skills/swift-concurrency/references/approachable-concurrency.md +80 -0
  141. package/stacks/lang/swift/skills/swift-concurrency/references/concurrency-patterns.md +233 -0
  142. package/stacks/lang/swift/skills/swift-concurrency/references/swiftui-concurrency.md +187 -0
  143. package/stacks/lang/swift/skills/swift-concurrency/references/synchronization-primitives.md +341 -0
  144. package/stacks/lang/swift/skills/swift-testing/SKILL.md +497 -0
  145. package/stacks/lang/swift/skills/swift-testing/references/testing-advanced.md +106 -0
  146. package/stacks/lang/swift/skills/swift-testing/references/testing-patterns.md +504 -0
  147. package/stacks/lang/swift/skills/swiftdata/SKILL.md +334 -0
  148. package/stacks/lang/swift/skills/swiftdata/references/core-data-coexistence.md +504 -0
  149. package/stacks/lang/swift/skills/swiftdata/references/swiftdata-advanced.md +975 -0
  150. package/stacks/lang/swift/skills/swiftdata/references/swiftdata-queries.md +675 -0
  151. package/stacks/lang/swift/skills/swiftui-patterns/SKILL.md +371 -0
  152. package/stacks/lang/swift/skills/swiftui-patterns/references/architecture-patterns.md +486 -0
  153. package/stacks/lang/swift/skills/swiftui-patterns/references/deprecated-migration.md +1097 -0
  154. package/stacks/lang/swift/skills/swiftui-patterns/references/design-polish.md +780 -0
  155. package/stacks/lang/swift/skills/swiftui-patterns/references/platform-and-sharing.md +696 -0
  156. package/stacks/lang/typescript/skills/typescript-conventions/SKILL.md +91 -0
  157. package/stacks/platform/android/claude.fragment.md +40 -0
  158. package/stacks/platform/android/hooks/pre-push-gradle.sh +70 -0
  159. package/stacks/platform/android/settings.fragment.json +13 -0
  160. package/stacks/platform/android/skills/android-build-conventions/SKILL.md +247 -0
  161. package/stacks/platform/ios/claude.fragment.md +24 -0
  162. package/stacks/platform/ios/hooks/pre-push-xcodebuild.sh +82 -0
  163. package/stacks/platform/ios/settings.fragment.json +21 -0
  164. package/stacks/platform/ios/skills/xcodebuildmcp-simulator-logs/SKILL.md +76 -0
  165. package/stacks/platform/web/skills/frontend-testing/SKILL.md +246 -0
  166. package/stacks/platform/web/skills/react-conventions/SKILL.md +261 -0
  167. package/stacks/platform/web/skills/web-platform-conventions/SKILL.md +55 -0
  168. package/stacks/tooling/issue-tracker-github/claude.fragment.md +10 -0
  169. package/stacks/tooling/issue-tracker-github/settings.fragment.json +24 -0
  170. package/stacks/tooling/issue-tracker-github/skills/issue-tracker-github/SKILL.md +278 -0
  171. package/stacks/tooling/issue-tracker-linear/claude.fragment.md +17 -0
  172. package/stacks/tooling/issue-tracker-linear/settings.fragment.json +9 -0
  173. package/stacks/tooling/issue-tracker-linear/skills/issue-tracker-linear/SKILL.md +183 -0
@@ -0,0 +1,675 @@
1
+ # SwiftData Queries Reference
2
+
3
+ Deep reference for all @Query initializer variants, FetchDescriptor options,
4
+ sort descriptors, sectioned queries, dynamic query switching, background fetch
5
+ patterns, and aggregate queries.
6
+
7
+ ---
8
+
9
+ ## Contents
10
+
11
+ - [@Query Initializer Variants](#query-initializer-variants)
12
+ - [FetchDescriptor Deep Dive](#fetchdescriptor-deep-dive)
13
+ - [Complex Sort Descriptors](#complex-sort-descriptors)
14
+ - [Sectioned Queries Pattern](#sectioned-queries-pattern)
15
+ - [Dynamic Query Switching](#dynamic-query-switching)
16
+ - [Background Fetch Patterns with @ModelActor](#background-fetch-patterns-with-modelactor)
17
+ - [Aggregate Queries](#aggregate-queries)
18
+ - [Enumerate for Large Datasets](#enumerate-for-large-datasets)
19
+
20
+ ## @Query Initializer Variants
21
+
22
+ `@Query` is a SwiftUI property wrapper (`DynamicProperty`) that automatically
23
+ fetches and observes persistent model data. All variants are `@MainActor`.
24
+
25
+ ### Basic (No Filter, No Sort)
26
+
27
+ ```swift
28
+ // Fetch all, default order
29
+ @Query private var trips: [Trip]
30
+
31
+ // With animation
32
+ @Query(animation: .default) private var trips: [Trip]
33
+
34
+ // With transaction
35
+ @Query(transaction: Transaction(animation: .spring)) private var trips: [Trip]
36
+ ```
37
+
38
+ ### Filter + SortDescriptor Array
39
+
40
+ ```swift
41
+ @Query(
42
+ filter: #Predicate<Trip> { $0.isFavorite == true },
43
+ sort: [SortDescriptor(\.startDate, order: .reverse)]
44
+ )
45
+ private var favoriteTrips: [Trip]
46
+
47
+ // With animation
48
+ @Query(
49
+ filter: #Predicate<Trip> { $0.isFavorite == true },
50
+ sort: [SortDescriptor(\.startDate, order: .reverse)],
51
+ animation: .default
52
+ )
53
+ private var favoriteTrips: [Trip]
54
+ ```
55
+
56
+ ### Filter + KeyPath Sort
57
+
58
+ ```swift
59
+ @Query(
60
+ filter: #Predicate<Trip> { $0.destination != "" },
61
+ sort: \.startDate,
62
+ order: .forward
63
+ )
64
+ private var upcomingTrips: [Trip]
65
+
66
+ // With optional key path sort
67
+ @Query(
68
+ sort: \.endDate, // KeyPath<Trip, Date?> -- optional sort key
69
+ order: .reverse
70
+ )
71
+ private var tripsByEndDate: [Trip]
72
+ ```
73
+
74
+ ### FetchDescriptor
75
+
76
+ ```swift
77
+ static var recentDescriptor: FetchDescriptor<Trip> {
78
+ var d = FetchDescriptor<Trip>(
79
+ predicate: #Predicate { $0.startDate > Date.now },
80
+ sortBy: [SortDescriptor(\.startDate)]
81
+ )
82
+ d.fetchLimit = 10
83
+ return d
84
+ }
85
+
86
+ @Query(RecentTripsView.recentDescriptor) private var recentTrips: [Trip]
87
+
88
+ // With animation
89
+ @Query(RecentTripsView.recentDescriptor, animation: .default)
90
+ private var recentTrips: [Trip]
91
+ ```
92
+
93
+ ### Query Properties
94
+
95
+ | Property | Type | Description |
96
+ |----------|------|-------------|
97
+ | `wrappedValue` | `Result` (typically `[Element]`) | Most recent fetched results |
98
+ | `modelContext` | `ModelContext` | The context used for fetching |
99
+ | `fetchError` | `(any Error)?` | Error from most recent fetch, if any |
100
+
101
+ Access `fetchError` to detect query failures:
102
+
103
+ ```swift
104
+ struct TripListView: View {
105
+ @Query private var trips: [Trip]
106
+
107
+ var body: some View {
108
+ Group {
109
+ if let error = $trips.fetchError {
110
+ ContentUnavailableView("Fetch Error",
111
+ systemImage: "exclamationmark.triangle",
112
+ description: Text(error.localizedDescription))
113
+ } else {
114
+ List(trips) { trip in
115
+ Text(trip.name)
116
+ }
117
+ }
118
+ }
119
+ }
120
+ }
121
+ ```
122
+
123
+ ---
124
+
125
+ ## FetchDescriptor Deep Dive
126
+
127
+ ### Full Property Reference
128
+
129
+ ```swift
130
+ var descriptor = FetchDescriptor<Trip>()
131
+ ```
132
+
133
+ | Property | Type | Default | Description |
134
+ |----------|------|---------|-------------|
135
+ | `predicate` | `Predicate<T>?` | `nil` | Filter condition |
136
+ | `sortBy` | `[SortDescriptor<T>]` | `[]` | Sort order |
137
+ | `fetchLimit` | `Int?` | `nil` | Maximum results |
138
+ | `fetchOffset` | `Int?` | `nil` | Skip first N results |
139
+ | `includePendingChanges` | `Bool` | `true` | Include unsaved in-memory changes |
140
+ | `propertiesToFetch` | `[PartialKeyPath<T>]` | all | Specific properties to load |
141
+ | `relationshipKeyPathsForPrefetching` | `[PartialKeyPath<T>]` | `[]` | Related models to eagerly load |
142
+
143
+ ### fetchLimit and fetchOffset (Pagination)
144
+
145
+ ```swift
146
+ func fetchPage(page: Int, pageSize: Int) throws -> [Trip] {
147
+ var descriptor = FetchDescriptor<Trip>(
148
+ sortBy: [SortDescriptor(\.startDate)]
149
+ )
150
+ descriptor.fetchLimit = pageSize
151
+ descriptor.fetchOffset = page * pageSize
152
+ return try modelContext.fetch(descriptor)
153
+ }
154
+ ```
155
+
156
+ ### includePendingChanges
157
+
158
+ When `true` (default), the fetch includes objects inserted or modified in the
159
+ current context but not yet saved. Set to `false` for read-only queries against
160
+ the persisted store only.
161
+
162
+ ```swift
163
+ var descriptor = FetchDescriptor<Trip>()
164
+ descriptor.includePendingChanges = false // Only persisted data
165
+ ```
166
+
167
+ Note: `includePendingChanges: true` cannot be used with batched fetches
168
+ (`fetch(_:batchSize:)`). This will throw
169
+ `SwiftDataError.includePendingChangesWithBatchSize`.
170
+
171
+ ### propertiesToFetch (Partial Loading)
172
+
173
+ Load only specific attributes to reduce memory footprint:
174
+
175
+ ```swift
176
+ var descriptor = FetchDescriptor<Trip>()
177
+ descriptor.propertiesToFetch = [\.name, \.destination, \.startDate]
178
+ let trips = try modelContext.fetch(descriptor)
179
+ // Only name, destination, startDate are loaded; other properties fault on access
180
+ ```
181
+
182
+ ### relationshipKeyPathsForPrefetching
183
+
184
+ Eagerly load related objects to avoid N+1 query patterns:
185
+
186
+ ```swift
187
+ var descriptor = FetchDescriptor<Trip>()
188
+ descriptor.relationshipKeyPathsForPrefetching = [
189
+ \.accommodation,
190
+ \.tags
191
+ ]
192
+ let trips = try modelContext.fetch(descriptor)
193
+ // Accessing trip.accommodation does not trigger a separate fetch
194
+ ```
195
+
196
+ ### Fetch Variants on ModelContext
197
+
198
+ | Method | Returns | Use Case |
199
+ |--------|---------|----------|
200
+ | `fetch(_:)` | `[T]` | Standard fetch, all results in memory |
201
+ | `fetch(_:batchSize:)` | `FetchResultsCollection<T>` | Lazy batched loading |
202
+ | `fetchCount(_:)` | `Int` | Count only, no objects loaded |
203
+ | `fetchIdentifiers(_:)` | `[PersistentIdentifier]` | IDs only, lightweight |
204
+ | `fetchIdentifiers(_:batchSize:)` | `FetchResultsCollection<PersistentIdentifier>` | Batched ID loading |
205
+ | `enumerate(_:batchSize:...)` | `Void` | Process large sets in batches |
206
+
207
+ ### FetchResultsCollection (Batched Fetch)
208
+
209
+ ```swift
210
+ let results: FetchResultsCollection<Trip> = try modelContext.fetch(
211
+ FetchDescriptor<Trip>(sortBy: [SortDescriptor(\.name)]),
212
+ batchSize: 100
213
+ )
214
+
215
+ // Iterate lazily -- only 100 objects in memory at a time
216
+ for trip in results {
217
+ print(trip.name)
218
+ }
219
+ ```
220
+
221
+ Requirements for batched fetch:
222
+ - `includePendingChanges` must be `false` (or will throw).
223
+ - Results are read-only snapshots.
224
+
225
+ ---
226
+
227
+ ## Complex Sort Descriptors
228
+
229
+ ### Single Sort
230
+
231
+ ```swift
232
+ SortDescriptor(\.name, order: .forward) // A-Z
233
+ SortDescriptor(\.name, order: .reverse) // Z-A
234
+ SortDescriptor(\.startDate) // Ascending (default)
235
+ ```
236
+
237
+ ### Multi-Level Sort
238
+
239
+ ```swift
240
+ let descriptor = FetchDescriptor<Trip>(
241
+ sortBy: [
242
+ SortDescriptor(\.isFavorite, order: .reverse), // Favorites first
243
+ SortDescriptor(\.startDate, order: .forward), // Then by date
244
+ SortDescriptor(\.name, order: .forward) // Then alphabetical
245
+ ]
246
+ )
247
+ ```
248
+
249
+ ### Optional Key Path Sort
250
+
251
+ Sort on optional properties -- nil values sort to the end:
252
+
253
+ ```swift
254
+ @Query(sort: \.endDate, order: .reverse) private var trips: [Trip]
255
+ // endDate is Date? -- trips without endDate appear last
256
+ ```
257
+
258
+ ### Dynamic Sort Switching
259
+
260
+ ```swift
261
+ struct TripListView: View {
262
+ @State private var sortOrder: SortOrder = .forward
263
+ @State private var sortKey: TripSortKey = .name
264
+
265
+ var body: some View {
266
+ SortedTripList(sortKey: sortKey, sortOrder: sortOrder)
267
+ .toolbar {
268
+ Picker("Sort", selection: $sortKey) {
269
+ Text("Name").tag(TripSortKey.name)
270
+ Text("Date").tag(TripSortKey.date)
271
+ Text("Destination").tag(TripSortKey.destination)
272
+ }
273
+ }
274
+ }
275
+ }
276
+
277
+ enum TripSortKey: String, CaseIterable {
278
+ case name, date, destination
279
+ }
280
+
281
+ struct SortedTripList: View {
282
+ @Query private var trips: [Trip]
283
+
284
+ init(sortKey: TripSortKey, sortOrder: SortOrder) {
285
+ let sortDescriptor: SortDescriptor<Trip> = switch sortKey {
286
+ case .name: SortDescriptor(\.name, order: sortOrder)
287
+ case .date: SortDescriptor(\.startDate, order: sortOrder)
288
+ case .destination: SortDescriptor(\.destination, order: sortOrder)
289
+ }
290
+ _trips = Query(sort: [sortDescriptor])
291
+ }
292
+
293
+ var body: some View {
294
+ List(trips) { trip in
295
+ TripRow(trip: trip)
296
+ }
297
+ }
298
+ }
299
+ ```
300
+
301
+ ---
302
+
303
+ ## Sectioned Queries Pattern
304
+
305
+ SwiftData does not provide a built-in sectioned query like Core Data's
306
+ `NSFetchedResultsController`. Build sectioned views manually:
307
+
308
+ ### Using Dictionary Grouping
309
+
310
+ ```swift
311
+ struct SectionedTripListView: View {
312
+ @Query(sort: \.startDate) private var trips: [Trip]
313
+
314
+ private var sections: [(String, [Trip])] {
315
+ let formatter = DateFormatter()
316
+ formatter.dateFormat = "MMMM yyyy"
317
+ let grouped = Dictionary(grouping: trips) { trip in
318
+ formatter.string(from: trip.startDate)
319
+ }
320
+ return grouped.sorted { $0.key < $1.key }
321
+ }
322
+
323
+ var body: some View {
324
+ List {
325
+ ForEach(sections, id: \.0) { section, trips in
326
+ Section(section) {
327
+ ForEach(trips) { trip in
328
+ TripRow(trip: trip)
329
+ }
330
+ }
331
+ }
332
+ }
333
+ }
334
+ }
335
+ ```
336
+
337
+ ### Using Enum-Based Sections
338
+
339
+ ```swift
340
+ enum TripStatus: String, CaseIterable {
341
+ case upcoming = "Upcoming"
342
+ case current = "Current"
343
+ case past = "Past"
344
+ }
345
+
346
+ struct StatusSectionedView: View {
347
+ @Query(sort: \.startDate) private var trips: [Trip]
348
+
349
+ private func trips(for status: TripStatus) -> [Trip] {
350
+ let now = Date.now
351
+ return trips.filter { trip in
352
+ switch status {
353
+ case .upcoming: trip.startDate > now
354
+ case .current: trip.startDate <= now && trip.endDate >= now
355
+ case .past: trip.endDate < now
356
+ }
357
+ }
358
+ }
359
+
360
+ var body: some View {
361
+ List {
362
+ ForEach(TripStatus.allCases, id: \.self) { status in
363
+ let sectionTrips = trips(for: status)
364
+ if !sectionTrips.isEmpty {
365
+ Section(status.rawValue) {
366
+ ForEach(sectionTrips) { trip in
367
+ TripRow(trip: trip)
368
+ }
369
+ }
370
+ }
371
+ }
372
+ }
373
+ }
374
+ }
375
+ ```
376
+
377
+ ---
378
+
379
+ ## Dynamic Query Switching
380
+
381
+ ### Filter + Sort Controlled by Parent
382
+
383
+ ```swift
384
+ struct TripBrowserView: View {
385
+ @State private var searchText = ""
386
+ @State private var showFavoritesOnly = false
387
+
388
+ var body: some View {
389
+ NavigationStack {
390
+ FilteredTripList(
391
+ searchText: searchText,
392
+ favoritesOnly: showFavoritesOnly
393
+ )
394
+ .searchable(text: $searchText)
395
+ .toolbar {
396
+ Toggle("Favorites", isOn: $showFavoritesOnly)
397
+ }
398
+ }
399
+ }
400
+ }
401
+
402
+ struct FilteredTripList: View {
403
+ @Query private var trips: [Trip]
404
+
405
+ init(searchText: String, favoritesOnly: Bool) {
406
+ let predicate = #Predicate<Trip> { trip in
407
+ (searchText.isEmpty || trip.name.localizedStandardContains(searchText))
408
+ && (!favoritesOnly || trip.isFavorite == true)
409
+ }
410
+ _trips = Query(
411
+ filter: predicate,
412
+ sort: [SortDescriptor(\.startDate, order: .reverse)]
413
+ )
414
+ }
415
+
416
+ var body: some View {
417
+ List(trips) { trip in
418
+ NavigationLink(trip.name) {
419
+ TripDetailView(trip: trip)
420
+ }
421
+ }
422
+ }
423
+ }
424
+ ```
425
+
426
+ ### Full Dynamic Descriptor
427
+
428
+ ```swift
429
+ struct AdvancedTripList: View {
430
+ @Query private var trips: [Trip]
431
+
432
+ init(
433
+ destination: String?,
434
+ minDate: Date?,
435
+ sortKey: KeyPath<Trip, some Comparable>,
436
+ ascending: Bool,
437
+ limit: Int?
438
+ ) {
439
+ var descriptor = FetchDescriptor<Trip>(
440
+ sortBy: [SortDescriptor(\.startDate, order: ascending ? .forward : .reverse)]
441
+ )
442
+
443
+ if let destination {
444
+ descriptor.predicate = #Predicate<Trip> { trip in
445
+ trip.destination == destination
446
+ }
447
+ }
448
+
449
+ if let limit {
450
+ descriptor.fetchLimit = limit
451
+ }
452
+
453
+ _trips = Query(descriptor)
454
+ }
455
+
456
+ var body: some View {
457
+ List(trips) { trip in
458
+ TripRow(trip: trip)
459
+ }
460
+ }
461
+ }
462
+ ```
463
+
464
+ ---
465
+
466
+ ## Background Fetch Patterns with @ModelActor
467
+
468
+ ### Basic Background Fetch
469
+
470
+ ```swift
471
+ @ModelActor
472
+ actor TripDataHandler {
473
+ func fetchUpcomingTrips() throws -> [PersistentIdentifier] {
474
+ let descriptor = FetchDescriptor<Trip>(
475
+ predicate: #Predicate { $0.startDate > Date.now },
476
+ sortBy: [SortDescriptor(\.startDate)]
477
+ )
478
+ return try modelContext.fetchIdentifiers(descriptor)
479
+ }
480
+
481
+ func fetchTripCount(destination: String) throws -> Int {
482
+ let descriptor = FetchDescriptor<Trip>(
483
+ predicate: #Predicate<Trip> { trip in
484
+ trip.destination == destination
485
+ }
486
+ )
487
+ return try modelContext.fetchCount(descriptor)
488
+ }
489
+ }
490
+
491
+ // Usage from SwiftUI view
492
+ struct TripDashboardView: View {
493
+ @Environment(\.modelContext) private var modelContext
494
+ @State private var upcomingCount = 0
495
+
496
+ var body: some View {
497
+ Text("Upcoming: \(upcomingCount)")
498
+ .task {
499
+ let handler = TripDataHandler(
500
+ modelContainer: modelContext.container
501
+ )
502
+ upcomingCount = (try? await handler.fetchTripCount(
503
+ destination: "Paris"
504
+ )) ?? 0
505
+ }
506
+ }
507
+ }
508
+ ```
509
+
510
+ ### Background Import with Progress
511
+
512
+ ```swift
513
+ @ModelActor
514
+ actor ImportHandler {
515
+ func importTrips(
516
+ _ records: [TripRecord],
517
+ progress: @Sendable (Int) -> Void
518
+ ) throws -> Int {
519
+ var imported = 0
520
+ for (index, record) in records.enumerated() {
521
+ let trip = Trip(
522
+ name: record.name,
523
+ destination: record.destination,
524
+ startDate: record.startDate,
525
+ endDate: record.endDate
526
+ )
527
+ modelContext.insert(trip)
528
+ imported += 1
529
+
530
+ // Save periodically to flush memory
531
+ if index % 500 == 0 {
532
+ try modelContext.save()
533
+ progress(imported)
534
+ }
535
+ }
536
+ try modelContext.save()
537
+ return imported
538
+ }
539
+ }
540
+ ```
541
+
542
+ ### Resolving Identifiers on MainActor
543
+
544
+ ```swift
545
+ @ModelActor
546
+ actor DataHandler {
547
+ func findDuplicateIDs() throws -> [PersistentIdentifier] {
548
+ // Complex logic to find duplicates
549
+ let all = try modelContext.fetch(FetchDescriptor<Trip>())
550
+ var seen = Set<String>()
551
+ var duplicateIDs: [PersistentIdentifier] = []
552
+ for trip in all {
553
+ if seen.contains(trip.name) {
554
+ duplicateIDs.append(trip.persistentModelID)
555
+ }
556
+ seen.insert(trip.name)
557
+ }
558
+ return duplicateIDs
559
+ }
560
+ }
561
+
562
+ // On MainActor, resolve IDs to objects
563
+ struct DuplicateReviewView: View {
564
+ @Environment(\.modelContext) private var modelContext
565
+ @State private var duplicates: [Trip] = []
566
+
567
+ var body: some View {
568
+ List(duplicates) { trip in
569
+ Text(trip.name)
570
+ }
571
+ .task {
572
+ let handler = DataHandler(modelContainer: modelContext.container)
573
+ let ids = (try? await handler.findDuplicateIDs()) ?? []
574
+ duplicates = ids.compactMap { id in
575
+ modelContext.registeredModel(for: id) as Trip?
576
+ ?? (try? modelContext.model(for: id) as? Trip)
577
+ }
578
+ }
579
+ }
580
+ }
581
+ ```
582
+
583
+ ---
584
+
585
+ ## Aggregate Queries
586
+
587
+ SwiftData does not provide built-in aggregate functions (SUM, AVG, etc.).
588
+ Compute aggregates using fetch + Swift computation.
589
+
590
+ ### Count
591
+
592
+ ```swift
593
+ let count = try modelContext.fetchCount(
594
+ FetchDescriptor<Trip>(predicate: #Predicate { $0.isFavorite == true })
595
+ )
596
+ ```
597
+
598
+ ### Sum, Average, Min, Max
599
+
600
+ ```swift
601
+ let trips = try modelContext.fetch(FetchDescriptor<Trip>())
602
+
603
+ let totalBudget = trips.reduce(0.0) { $0 + $1.budget }
604
+ let averageBudget = trips.isEmpty ? 0 : totalBudget / Double(trips.count)
605
+ let maxBudget = trips.map(\.budget).max() ?? 0
606
+ let minBudget = trips.map(\.budget).min() ?? 0
607
+ ```
608
+
609
+ ### Efficient Aggregates with Partial Fetch
610
+
611
+ Fetch only the property needed for aggregation:
612
+
613
+ ```swift
614
+ var descriptor = FetchDescriptor<Trip>()
615
+ descriptor.propertiesToFetch = [\.budget]
616
+ let trips = try modelContext.fetch(descriptor)
617
+ let total = trips.reduce(0.0) { $0 + $1.budget }
618
+ ```
619
+
620
+ ### Background Aggregate Computation
621
+
622
+ ```swift
623
+ @ModelActor
624
+ actor StatsHandler {
625
+ struct TripStats: Sendable {
626
+ let totalCount: Int
627
+ let favoriteCount: Int
628
+ let averageDuration: TimeInterval
629
+ }
630
+
631
+ func computeStats() throws -> TripStats {
632
+ let allTrips = try modelContext.fetch(FetchDescriptor<Trip>())
633
+ let favoriteCount = try modelContext.fetchCount(
634
+ FetchDescriptor<Trip>(predicate: #Predicate { $0.isFavorite == true })
635
+ )
636
+
637
+ let totalDuration = allTrips.reduce(0.0) { sum, trip in
638
+ sum + trip.endDate.timeIntervalSince(trip.startDate)
639
+ }
640
+ let avgDuration = allTrips.isEmpty ? 0 : totalDuration / Double(allTrips.count)
641
+
642
+ return TripStats(
643
+ totalCount: allTrips.count,
644
+ favoriteCount: favoriteCount,
645
+ averageDuration: avgDuration
646
+ )
647
+ }
648
+ }
649
+ ```
650
+
651
+ ---
652
+
653
+ ## Enumerate for Large Datasets
654
+
655
+ Use `enumerate` instead of `fetch` when processing many records to keep memory
656
+ usage constant:
657
+
658
+ ```swift
659
+ // Process all trips without loading all into memory
660
+ try modelContext.enumerate(
661
+ FetchDescriptor<Trip>(sortBy: [SortDescriptor(\.startDate)]),
662
+ batchSize: 1000,
663
+ allowEscapingMutations: false
664
+ ) { trip in
665
+ // Process each trip
666
+ trip.isProcessed = true
667
+ }
668
+ try modelContext.save()
669
+ ```
670
+
671
+ Parameters:
672
+ - `batchSize`: Objects per batch (default 5000). Lower values use less memory.
673
+ - `allowEscapingMutations`: When `false`, objects are autoreleased after the
674
+ block. Set to `true` only if mutations must persist beyond the block.
675
+