Halo Family Test declarations 106 / 14 suites Lint 0 / 74 files Source reviews 4 clear Batch runtime Not run

Pre-push source review: Halo Family backup, categories and search

Reviewed source checkpoint on verified V6. Runtime gates remain pending the shared Mac build/test slot.

At a glance

  • A selected family exports JSON, payloads and an optional readable summary in a bounded stored ZIP.
  • Preview precedes one atomic local import. Existing identities reject original-identity restore; fresh copies remap live and historical UUIDs.
  • Categories preserve referenced archived links; literal titles, nested Contexts and dated Person roles are visible and searchable.
  • Completeness: backup/category/search source is implemented; extensions, account/share lifecycle and runtime/release gates remain.

Verdict

Source reviewed; verification pending

All four incremental source reviews are clear and strict lint passes. No compilation, tests, native UI or CloudKit ran for this batch. The last verified V6 checkpoint is 3286293: 79 passing cases and both Debug builds. Publication remains pending the full scheduled gate.

Review findings

8 raised · 8 fixed · 0 skipped

Jump to findings →

Tests

Pass rate: n/a

New tests: 21

Diff coverage: n/a

Jump to tests →

Three-level explanation

What changed

A family can be saved as a ZIP and previewed before bringing it back. Import can create a separate family copy or restore identities that are absent locally.

Why it matters

Existing records are preserved. Categories can be renamed or archived, and People can be found by entered titles, roles and Contexts.

Key concepts

Each record has a stable identity. A new copy uses new identities, including references kept in merge history.

Approach

Portable typed attributes and UUID references describe the Core Data graph. Binary payloads are ZIP members. Export pins a background read generation; restore validates before a single Private-store save.

Patterns

Per-stack import serialization, file fingerprints, indexed inverses and explicit cancellation protect the import boundary. Forms reuse existing repository guards and role editors.

Trade-offs

The codec accepts Halo stored ZIP32 only. Aggregate limits bound import memory. Copied historical merges retain their accounts but old undo is disabled.

Deep dive

Historical snapshots can retain UUIDs for rows since removed by guarded undo. Namespace remapping covers these identities, metadata UUIDs, links and recovery arrays; new UUID order is canonicalized to prevent phantom late-account changes.

Architecture

Imports write into one local Private store. Absence checks cover both attached stores and do not establish whole-account CloudKit uniqueness. Device-local Contacts mappings stay outside the portable graph.

Completeness and limits

Current source and four reviews cover backup/import, categories and expanded search. The 106 declared cases, both platform compilers and native UI remain unrun. Account change, no-account launch, removed shares, extensions, schema deployment and real transport still require their own evidence.

Important changes — detailed

Export and restore a portable family graph

Halo Family/Halo Family/Persistence/BackupRepository.swift

Why it matters. Preserve family-scoped data and reject overwrite.

What to look at. export, preview, restore

Takeaway. Pin reads, preview first, save imported references once.
Rationale. Decision 2 approves ZIP backups, preview and explicit fresh copies.

Remap retained historical identities

Halo Family/Halo Family/Persistence/BackupHistory.swift

Why it matters. Copied merge history must refer to the copied family and retain causal accounts.

What to look at. copied and validate

Takeaway. Recanonicalize ordering after changing stable identifiers.
Rationale. Fresh copies create a separate identity namespace; old undo is disabled conservatively.

Bound and validate stored ZIP members

Halo Family/Halo Family/Persistence/BackupArchive.swift

Why it matters. Validate framing, paths, offsets and payload integrity without extracting paths or subprocesses.

What to look at. write, members, validateRanges, read

Retain editable category links

Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift

Why it matters. User-defined labels remain ordinary categories when renamed or archived.

What to look at. seedCategories, updateCategory, setContextCategory

Find entered titles and show dated roles

Halo Family/Halo Family/Persistence/PeopleSearch.swift

Why it matters. Search and Person details expose existing contextual and family knowledge.

What to look at. peopleSearch, personContextRoles

Key decisions

Bounded stored ZIP32

1 GB archive, 10,000 members, 32 MB manifest, 100,000 records, 16 MB per historical snapshot and aggregate preview/restore payloads of 128 MB on iOS / 512 MB on macOS.

Fresh copies retain history with unavailable old undo

Live and historical UUIDs are remapped; original identities are preserved only for an absent local-family restore. The copied audit remains visible without replaying an original guard into a new identity namespace.

Review findings

SeverityAreaFindingResolution
majorAsset payload limitsKind metadata alone could bypass photo limits or omit referenced data.Use shared image limits from actual ownership; reject missing referenced payloads.
majorHistory preview memoryPreview retained every decoded history snapshot.Reject aggregate payload budgets before decoding and process one snapshot at a time.
majorInverse validationReciprocal links performed quadratic scans.Index relationship target sets once.
majorCopied historical orderingNew UUIDs changed canonical snapshot ordering and could invent late accounts.Sort remapped links and rows by their new UUIDs; add archived-account copy regression.
majorOwned staging cleanupCancelled failed restore could orphan the whole-family staged ZIP.Drain owned staging after canceled or disappeared work.
majorDetached cancellationStaging and preview did not observe view-task cancellation.Forward cancellation to owned detached workers.
majorCore Data cancellationCaller cancellation was absent from history and identity-query phases.Carry a locked cancellation signal through validation, remapping, SQL batches and the save boundary.
majorDisplayed structural labelsSearch matched raw stored kinds rather than displayed labels with spaces.Match StructuralKind.label and symmetric reverse facts; assert neutral-name Parent of search.

Tests

Source: local run at 2026-10-07T03:24:05.084756+00:00 · snapshot 866fd7a1b70d8c628c04f155a3397b21558ac845 (dirty working tree)

Baseline: none

Execution: not run · JUnit: none · Coverage: none · Baseline: absent

Coverage scope: every test in the repository

No test results

scheduled build/test slot pending

New and removed tests

Derived by declaration name, from the diff (no baseline run).

Blast radius

Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base 866fd7a.

Dependents none found Changed Dependencies none found Halo Family/Halo Family … Family/Halo Family.xcodeproj …amily/Halo Family/Persistence Tests/HaloPersistenceTests Halo Family/Halo Family/ContextCategoryViews.swift…ly/ContextCategoryViews.swift Halo Family/Halo Family/ContextsView.swift…alo Family/ContextsView.swift Halo Family/Halo Family/FamilyBackupView.swift…Family/FamilyBackupView.swift Halo Family/Halo Family/FamilyManagerView.swift…amily/FamilyManagerView.swift Halo Family/Halo Family/PeopleView.swift…/Halo Family/PeopleView.swift Halo Family/Halo Family.xcodeproj/project.pbxproj…ily.xcodeproj/project.pbxproj Halo Family/Halo Family/Persistence/BackupArchive.swift…rsistence/BackupArchive.swift Halo Family/Halo Family/Persistence/BackupCancellation.swift…ence/BackupCancellation.swift Halo Family/Halo Family/Persistence/BackupHistory.swift…rsistence/BackupHistory.swift Halo Family/Halo Family/Persistence/BackupRepository.swift…stence/BackupRepository.swift Halo Family/Halo Family/Persistence/BackupStaging.swift…rsistence/BackupStaging.swift Halo Family/Halo Family/Persistence/BackupValidation.swift…stence/BackupValidation.swift Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift…ntextCategoryRepository.swift Halo Family/Halo Family/Persistence/FamilyRepository.swift…stence/FamilyRepository.swift Halo Family/Halo Family/Persistence/PeopleSearch.swift…ersistence/PeopleSearch.swift Halo Family/Halo Family/Persistence/PersistenceStack.swift…stence/PersistenceStack.swift Halo Family/Halo Family/Persistence/PortableGraph.swift…rsistence/PortableGraph.swift Halo Family/Halo Family/Persistence/RelationshipQueries.swift…nce/RelationshipQueries.swift Tests/HaloPersistenceTests/ContextCategoryTests.swift…ts/ContextCategoryTests.swift Tests/HaloPersistenceTests/FamilyBackupTests.swift…Tests/FamilyBackupTests.swift Tests/HaloPersistenceTests/LocalContactLinksTests.swift…/LocalContactLinksTests.swift Tests/HaloPersistenceTests/PeopleSearchTests.swift…Tests/PeopleSearchTests.swift
addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

27 files: 22 code · 5 docs. Click to expand.

Code (22)

Halo Family/Halo Family.xcodeproj/project.pbxproj Modified
diff --git a/Halo Family/Halo Family.xcodeproj/project.pbxproj b/Halo Family/Halo Family.xcodeproj/project.pbxprojindex 69bdb28..c2a59f8 100644--- a/Halo Family/Halo Family.xcodeproj/project.pbxproj	+++ b/Halo Family/Halo Family.xcodeproj/project.pbxproj	@@ -260,7 +260,7 @@ 				DEVELOPMENT_TEAM = V24684SCZN; 				ENABLE_APP_SANDBOX = YES; 				ENABLE_PREVIEWS = YES;-				ENABLE_USER_SELECTED_FILES = readonly;+				ENABLE_USER_SELECTED_FILES = readwrite; 				GENERATE_INFOPLIST_FILE = YES; 				INFOPLIST_FILE = "Halo-Family-Info.plist"; 				"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;@@ -301,7 +301,7 @@ 				DEVELOPMENT_TEAM = V24684SCZN; 				ENABLE_APP_SANDBOX = YES; 				ENABLE_PREVIEWS = YES;-				ENABLE_USER_SELECTED_FILES = readonly;+				ENABLE_USER_SELECTED_FILES = readwrite; 				GENERATE_INFOPLIST_FILE = YES; 				INFOPLIST_FILE = "Halo-Family-Info.plist"; 				"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;
Halo Family/Halo Family/ContextsView.swift Modified
diff --git a/Halo Family/Halo Family/ContextsView.swift b/Halo Family/Halo Family/ContextsView.swiftindex 92ea3a7..92c6a13 100644--- a/Halo Family/Halo Family/ContextsView.swift	+++ b/Halo Family/Halo Family/ContextsView.swift	@@ -14,6 +14,7 @@ struct ContextsView: View {     var body: some View {         Form {             Section("Contexts") {+                NavigationLink("Manage categories") { ContextCategoriesView(repository: repository, familyID: familyID) }                 Toggle("Include archived", isOn: $showArchived)                 ForEach(contexts.filter { showArchived || !$0.isArchived }) { context in                     NavigationLink {@@ -71,11 +72,15 @@ private struct ContextDetailView: View {     @State private var startedAt = Date()     @State private var endedAt = Date()     @State private var editingAssociation: ContextPersonRow?+    @State private var choosingCategory = false+    @State private var categoryName = "No category"      var body: some View {         Form {             Section {                 Text(context.path)+                Text(categoryName).foregroundStyle(.secondary)+                Button("Choose category") { choosingCategory = true }                 Button(archived ? "Restore context" : "Archive context") {                     perform { try repository.archiveContext(context.id, archived: !archived) }                 }@@ -137,6 +142,9 @@ private struct ContextDetailView: View {             }         }         .navigationTitle(context.name)+        .sheet(isPresented: $choosingCategory, onDismiss: { perform {} }, content: {+            ContextCategorySelection(repository: repository, familyID: familyID, contextID: context.id)+        })         .sheet(item: $editingAssociation, onDismiss: { perform {} }, content: { association in             ContextRoleEditor(repository: repository, original: association)         })@@ -152,6 +160,8 @@ private struct ContextDetailView: View {         do {             try action()             archived = try repository.contextIsArchived(context.id)+            let selected = try repository.contextCategory(context.id)+            categoryName = try repository.contextCategories(in: familyID).first { $0.id == selected }?.name ?? "No category"             connections = try repository.contextConnections(context.id)             associations = try repository.contextPeople(context.id)             people = try repository.people(in: familyID)
Halo Family/Halo Family/FamilyManagerView.swift Modified
diff --git a/Halo Family/Halo Family/FamilyManagerView.swift b/Halo Family/Halo Family/FamilyManagerView.swiftindex d8442c7..5af25f6 100644--- a/Halo Family/Halo Family/FamilyManagerView.swift	+++ b/Halo Family/Halo Family/FamilyManagerView.swift	@@ -43,6 +43,15 @@ struct FamilyManagerView: View {                     .disabled(preparingShare || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)                     .accessibilityIdentifier("family.create")                 }+                Section("Keep a backup") {+                    NavigationLink("Backup and import") {+                        FamilyBackupView(repository: BackupRepository(stack: repository.stack), familyID: selectedFamilyID) {+                            selectedFamilyID = $0+                            reload()+                        }+                    }+                    .disabled(preparingShare)+                }                 if let selectedFamilyID, selectedFamilyID.persistentStore == repository.stack.privateStore {                     Section("Share with a co-parent") {                         Text("Everyone you invite can see and edit the whole family space, " +
Halo Family/Halo Family/PeopleView.swift Modified
diff --git a/Halo Family/Halo Family/PeopleView.swift b/Halo Family/Halo Family/PeopleView.swiftindex f4a111a..66c4927 100644--- a/Halo Family/Halo Family/PeopleView.swift	+++ b/Halo Family/Halo Family/PeopleView.swift	@@ -37,7 +37,7 @@ struct PeopleView: View {             }         }         .navigationTitle("People")-        .searchable(text: $search, prompt: "Search names")+        .searchable(text: $search, prompt: "Names, titles, roles or Contexts")         .task { perform {} }         .onChange(of: search) { perform {} }         .onChange(of: reviewOnly) { perform {} }@@ -76,6 +76,8 @@ struct PersonDetailView: View {     @State private var merging = false     @State private var mergedIntoID: NSManagedObjectID?     @State private var mergeConflict = false+    @State private var contextRoles: [PersonContextRoleRow] = []+    @State private var editingRole: ContextPersonRow?      var body: some View {         MemoryForm {@@ -140,6 +142,21 @@ struct PersonDetailView: View {                 .disabled(childID == nil)             }             .disabled(mergedIntoID != nil || mergeConflict)+            if !contextRoles.isEmpty {+                MemorySection("Context roles") {+                    ForEach(contextRoles) { role in+                        VStack(alignment: .leading) {+                            Text(role.contextPath)+                            Text(role.association.role.isEmpty ? "Role not recorded" : role.association.role)+                            if role.isArchived { Text("Archived Context").foregroundStyle(.secondary) }+                            if let start = role.association.startedAt { Text("From \(start.formatted(date: .abbreviated, time: .omitted))") }+                            if let end = role.association.endedAt { Text("Until \(end.formatted(date: .abbreviated, time: .omitted))") }+                            Button("Edit role or dates") { editingRole = role.association }+                                .disabled(mergedIntoID != nil || mergeConflict)+                        }+                    }+                }+            }             if !events.isEmpty {                 MemorySection("Social event history") {                     ForEach(events) { event in@@ -165,6 +182,9 @@ struct PersonDetailView: View {         .sheet(isPresented: $merging, onDismiss: { perform {} }, content: {             PersonMergeView(repository: repository, familyID: familyID, sourceID: personID)         })+        .sheet(item: $editingRole, onDismiss: { perform {} }, content: {+            ContextRoleEditor(repository: repository, original: $0)+        })         .task {             perform {}         }@@ -187,6 +207,7 @@ struct PersonDetailView: View {             connections = try repository.connections(to: personID)             photoID = try repository.primaryPhoto(personID)             events = try repository.socialEvents(for: personID)+            contextRoles = try repository.personContextRoles(personID)             mergeConflict = try repository.mergeConflicts(in: familyID).contains { $0.people.contains { $0.id == personID } }             mergedIntoID = mergeConflict ? nil : try repository.mergedPersonTarget(personID)             loaded = true
Halo Family/Halo Family/Persistence/FamilyRepository.swift Modified
diff --git a/Halo Family/Halo Family/Persistence/FamilyRepository.swift b/Halo Family/Halo Family/Persistence/FamilyRepository.swiftindex 4df9e05..92d75b1 100644--- a/Halo Family/Halo Family/Persistence/FamilyRepository.swift	+++ b/Halo Family/Halo Family/Persistence/FamilyRepository.swift	@@ -91,6 +91,8 @@ final class FamilyRepository {             family.setValue(name, forKey: "name")             family.setValue(Date(), forKey: "createdAt")             family.setValue(Date(), forKey: "modifiedAt")+            try context.obtainPermanentIDs(for: [family])+            try seedCategories(family: family, in: context)             return family         }     }
Halo Family/Halo Family/Persistence/PersistenceStack.swift Modified
diff --git a/Halo Family/Halo Family/Persistence/PersistenceStack.swift b/Halo Family/Halo Family/Persistence/PersistenceStack.swiftindex f0c5dfb..f96d5fa 100644--- a/Halo Family/Halo Family/Persistence/PersistenceStack.swift	+++ b/Halo Family/Halo Family/Persistence/PersistenceStack.swift	@@ -12,6 +12,7 @@ final class PersistenceStack {     let sharedStore: NSPersistentStore     let role: PersistenceRole     let nativeContactsEnabled: Bool+    @ObservationIgnored var importingBackup = false     private(set) var issue: String?     private(set) var syncIssue: String?     @ObservationIgnored private var history: HistoryProcessor?
Halo Family/Halo Family/Persistence/RelationshipQueries.swift Modified
diff --git a/Halo Family/Halo Family/Persistence/RelationshipQueries.swift b/Halo Family/Halo Family/Persistence/RelationshipQueries.swiftindex 83c047e..9daff96 100644--- a/Halo Family/Halo Family/Persistence/RelationshipQueries.swift	+++ b/Halo Family/Halo Family/Persistence/RelationshipQueries.swift	@@ -78,7 +78,7 @@ extension FamilyRepository {             if needsReview || !includeDeceased { predicates.append(NSPredicate(format: "isDeceased == NO OR isDeceased == nil")) }         }         let search = search.trimmingCharacters(in: .whitespacesAndNewlines)-        if !search.isEmpty { predicates.append(NSPredicate(format: "displayName CONTAINS[cd] %@", search)) }+        if !search.isEmpty { predicates.append(try peopleSearch(search, familyID: familyID)) }         if needsReview { predicates.append(NSPredicate(format: "needsReview == YES")) }         return try rows(entity: "Person", nameKey: "displayName", predicate: NSCompoundPredicate(andPredicateWithSubpredicates: predicates))     }
Tests/HaloPersistenceTests/LocalContactLinksTests.swift Modified
diff --git a/Tests/HaloPersistenceTests/LocalContactLinksTests.swift b/Tests/HaloPersistenceTests/LocalContactLinksTests.swiftindex dd4879d..3a417d5 100644--- a/Tests/HaloPersistenceTests/LocalContactLinksTests.swift+++ b/Tests/HaloPersistenceTests/LocalContactLinksTests.swift@@ -105,7 +105,7 @@ struct LocalContactLinksTests {         let graph = FamilyRepository(stack: host)         let family = try graph.createFamily(name: "Synthetic family")         let person = try graph.addPerson(name: "Synthetic person", familyID: family)-        for role in [PersistenceRole.widget, .intent] {+        for role in [PersistenceRole.widget, .appIntent] {             let extensionStack = try PersistenceStack(directory: directory, role: role)             #expect(throws: GraphError.self) { try extensionStack.localContactLinks() }             #expect(throws: GraphError.self) { try FamilyRepository(stack: extensionStack).contactIdentity(person) }
Halo Family/Halo Family/ContextCategoryViews.swift Added
diff --git a/Halo Family/Halo Family/ContextCategoryViews.swift b/Halo Family/Halo Family/ContextCategoryViews.swiftnew file mode 100644index 0000000..2c44a1a--- /dev/null+++ b/Halo Family/Halo Family/ContextCategoryViews.swift	@@ -0,0 +1,132 @@+import Combine+import CoreData+import SwiftUI++struct ContextCategoriesView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    @State private var categories: [ContextCategoryRow] = []+    @State private var name = ""+    @State private var edited: ContextCategoryRow?+    @State private var failure: String?++    var body: some View {+        MemoryForm {+            MemorySection("Categories") {+                Text("Categories are your own labels. Renaming or archiving a category preserves every linked Context.")+                    .foregroundStyle(.secondary)+                ForEach(categories) { category in+                    Button { edited = category } label: {+                        HStack {+                            Text(category.name)+                            if category.isArchived { Text("Archived").foregroundStyle(.secondary) }+                        }+                    }+                }+            }+            MemorySection("Add category") {+                MemoryField("Name") { TextField("Category name", text: $name) }+                Button("Add category") {+                    perform { _ = try repository.createCategory(name: name, familyID: familyID); name = "" }+                }+                .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+                Button("Add missing starter categories") { perform { try repository.addStarterCategories(familyID: familyID) } }+            }+        }+        .navigationTitle("Context categories")+        .task { perform {} }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in perform {} }+        .sheet(item: $edited) { ContextCategoryEditView(repository: repository, original: $0) }+        .graphFailure($failure)+    }++    private func perform(_ operation: () throws -> Void) {+        do { try operation(); categories = try repository.contextCategories(in: familyID) } catch { failure = error.localizedDescription }+    }+}++private struct ContextCategoryEditView: View {+    let repository: FamilyRepository+    let original: ContextCategoryRow+    @State private var name: String+    @State private var archived: Bool+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    init(repository: FamilyRepository, original: ContextCategoryRow) {+        self.repository = repository; self.original = original+        _name = State(initialValue: original.name); _archived = State(initialValue: original.isArchived)+    }++    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("Category") {+                    MemoryField("Name") { TextField("Category name", text: $name) }+                    Toggle("Archived", isOn: $archived)+                    Text("Archived categories stay attached to existing Contexts and are hidden from new choices.")+                        .foregroundStyle(.secondary)+                }+            }+            .navigationTitle("Edit category")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save") {+                        do { try repository.updateCategory(original, name: name, archived: archived); dismiss() } catch {+                            failure = error.localizedDescription+                        }+                    }+                }+            }+        }+        .frame(minWidth: 320, minHeight: 260)+        .graphFailure($failure)+    }+}++struct ContextCategorySelection: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    let contextID: NSManagedObjectID+    @State private var categories: [ContextCategoryRow] = []+    @State private var initial: NSManagedObjectID?+    @State private var selected: NSManagedObjectID?+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("Category") {+                    Picker("Category", selection: $selected) {+                        Text("No category").tag(nil as NSManagedObjectID?)+                        ForEach(categories.filter { !$0.isArchived || $0.id == initial }) { category in+                            Text(category.name + (category.isArchived ? " (archived)" : "")).tag(Optional(category.id))+                        }+                    }+                }+            }+            .navigationTitle("Context category")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save") {+                        do { try repository.setContextCategory(contextID, categoryID: selected, expectedID: initial); dismiss() } catch {+                            failure = error.localizedDescription+                        }+                    }+                }+            }+        }+        .frame(minWidth: 320, minHeight: 260)+        .task {+            do {+                categories = try repository.contextCategories(in: familyID)+                initial = try repository.contextCategory(contextID); selected = initial+            } catch { failure = error.localizedDescription }+        }+        .graphFailure($failure)+    }+}
Halo Family/Halo Family/FamilyBackupView.swift Added
diff --git a/Halo Family/Halo Family/FamilyBackupView.swift b/Halo Family/Halo Family/FamilyBackupView.swiftnew file mode 100644index 0000000..f9bf130--- /dev/null+++ b/Halo Family/Halo Family/FamilyBackupView.swift	@@ -0,0 +1,138 @@+import CoreData+import SwiftUI+import UniformTypeIdentifiers++struct FamilyBackupView: View {+    let repository: BackupRepository+    let familyID: NSManagedObjectID?+    var imported: (NSManagedObjectID) -> Void+    @State private var readable = true+    @State private var working = false+    @State private var picking = false+    @State private var moving = false+    @State private var exportURL: URL?+    @State private var selectedURL: URL?+    @State private var preview: BackupPreview?+    @State private var asNewCopy = true+    @State private var failure: String?+    @State private var outcome: String?+    @State private var operation: Task<Void, Never>?+    @State private var visible = false++    var body: some View {+        MemoryForm {+            MemorySection("Export family") {+                Text("The ZIP contains the whole selected family, including shared notes, Sensitive Details, photos and attachments. " ++                     "Anyone with the file can read them. Apple Contacts links stay on this device.")+                    .font(.callout).foregroundStyle(.secondary)+                Toggle("Include a readable Markdown summary", isOn: $readable)+                Button("Create ZIP backup") { export() }.disabled(familyID == nil || working || moving || picking)+            }+            MemorySection("Import backup") {+                Text("Select a Halo Family ZIP to preview it before importing. Existing records are never overwritten.")+                    .foregroundStyle(.secondary)+                Button("Choose backup…") { clearPreview(); picking = true }.disabled(working || moving || picking)+                if let preview {+                    Text(preview.familyName).font(.headline)+                    Text("\(preview.peopleCount) people · \(preview.eventCount) events · " ++                         ByteCountFormatter.string(fromByteCount: Int64(preview.payloadBytes), countStyle: .file) ++                         " in attachments/history")+                    Text("Created \(preview.backup.createdAt.formatted(date: .abbreviated, time: .shortened))")+                        .font(.caption).foregroundStyle(.secondary)+                    Picker("Import as", selection: $asNewCopy) {+                        Text("A new family copy").tag(true)+                        Text("Restore original identities if absent").tag(false)+                    }+                    Text(asNewCopy ? "Creates a separate family with new identities. Merge history is retained; " ++                         "old merges cannot be undone in the copy." :+                         "Preserves original identities. The import stops if any identity already exists on this device.")+                        .font(.caption).foregroundStyle(.secondary)+                    Text("The imported family is saved in your own space and may sync to your iCloud account. " ++                         "It is not shared automatically.")+                        .font(.caption).foregroundStyle(.secondary)+                    Button(asNewCopy ? "Import new copy" : "Restore absent family") { restore(preview) }.disabled(working)+                    Button("Cancel preview", role: .cancel) { clearPreview() }.disabled(working)+                }+            }+            if working { ProgressView("Working…") }+            if let outcome { Text(outcome).foregroundStyle(.secondary) }+        }+        .disabled(working)+        .navigationTitle("Backup and import")+        .fileImporter(isPresented: $picking, allowedContentTypes: [.zip]) { result in select(result) }+        .fileMover(isPresented: $moving, file: exportURL) { result in+            switch result {+            case .success: outcome = "Backup saved."+            case .failure(let error): failure = error.localizedDescription+            }+            clearExport()+        } onCancellation: { clearExport() }+        .graphFailure($failure)+        .onAppear { visible = true }+        .onDisappear { visible = false; operation?.cancel(); if !working { clearExport(); clearPreview() } }+    }++    private func export() {+        guard let familyID, !working else { return }+        working = true; outcome = nil+        operation = Task {+            defer { drained() }+            do {+                let url = try await repository.export(familyID: familyID, readable: readable)+                if Task.isCancelled { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()); return }+                exportURL = url; moving = true+            } catch { if !Task.isCancelled { failure = error.localizedDescription } }+        }+    }++    private func select(_ result: Result<URL, Error>) {+        guard !working else { return }+        working = true; outcome = nil+        operation = Task {+            defer { drained() }+            do {+                let selected = try result.get()+                let staging = Task.detached { try BackupStaging.copy(selected) }+                let archive = try await withTaskCancellationHandler { try await staging.value } onCancel: { staging.cancel() }+                selectedURL = archive+                try Task.checkCancellation()+                preview = try await repository.preview(archive)+                try Task.checkCancellation()+                asNewCopy = true+            } catch {+                clearPreview()+                if !Task.isCancelled { failure = error.localizedDescription }+            }+        }+    }++    private func restore(_ preview: BackupPreview) {+        guard !working else { return }+        working = true; outcome = nil+        operation = Task {+            defer { drained() }+            do {+                let family = try await repository.restore(preview, asNewCopy: asNewCopy)+                imported(family)+                outcome = "Family imported."+                clearPreview()+            } catch { if !Task.isCancelled { failure = error.localizedDescription } }+        }+    }++    private func clearPreview() {+        preview = nil+        if let selectedURL { try? FileManager.default.removeItem(at: selectedURL.deletingLastPathComponent()) }+        selectedURL = nil+    }++    private func drained() {+        if Task.isCancelled || !visible { clearExport(); clearPreview() }+        working = false; operation = nil+    }++    private func clearExport() {+        if let exportURL { try? FileManager.default.removeItem(at: exportURL.deletingLastPathComponent()) }+        exportURL = nil+    }+}
Halo Family/Halo Family/Persistence/BackupArchive.swift Added
diff --git a/Halo Family/Halo Family/Persistence/BackupArchive.swift b/Halo Family/Halo Family/Persistence/BackupArchive.swiftnew file mode 100644index 0000000..8dc7650--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupArchive.swift	@@ -0,0 +1,224 @@+import Foundation++nonisolated enum BackupError: LocalizedError {+    case invalidArchive+    case unsupportedVersion+    case missingIdentity+    case familyExists+    case changed+    case tooLarge+    case importing++    var errorDescription: String? {+        switch self {+        case .invalidArchive: "This is not a valid Halo Family backup. No family data was changed."+        case .unsupportedVersion: "This backup uses an unsupported format or model version."+        case .missingIdentity: "A saved record has no stable identity. The backup was not created."+        case .familyExists: "This family already exists. Restore into an absent family or explicitly import a new copy."+        case .changed: "The backup or family changed. Preview it again before importing."+        case .tooLarge: "This backup exceeds the supported archive limits."+        case .importing: "Another family import is in progress. Wait for it to finish."+        }+    }+}++nonisolated struct BackupFile: Sendable {+    let name: String+    let url: URL+}++nonisolated struct ArchiveMember: Sendable {+    let name: String+    let size: UInt32+    let checksum: UInt32+    let offset: UInt32+}++/// A streaming, uncompressed ZIP32 codec for Halo's own versioned backup files.+/// No subprocess, external service, path extraction, encryption or executable content.+nonisolated enum BackupArchive {+    static let maximumBytes: UInt64 = 1_000_000_000+    private static let chunkSize = 65_536++    static func write(_ files: [BackupFile], to destination: URL,+                      check: () throws -> Void = { try Task.checkCancellation() }) throws {+        guard files.count <= 10_000, Set(files.map(\.name)).count == files.count else { throw BackupError.tooLarge }+        let partial = destination.deletingLastPathComponent().appendingPathComponent(UUID().uuidString + ".partial")+        guard FileManager.default.createFile(atPath: partial.path, contents: nil) else { throw BackupError.invalidArchive }+        defer { try? FileManager.default.removeItem(at: partial) }+        let handle = try FileHandle(forWritingTo: partial)+        defer { try? handle.close() }+        var directory: [ArchiveMember] = []+        for file in files {+            try check()+            try validName(file.name)+            let (size, checksum) = try measured(file.url, check: check)+            let position = try handle.offset()+            guard position + UInt64(size) < maximumBytes else { throw BackupError.tooLarge }+            let member = ArchiveMember(name: file.name, size: size, checksum: checksum, offset: UInt32(position))+            try handle.write(contentsOf: localHeader(member))+            let input = try FileHandle(forReadingFrom: file.url)+            defer { try? input.close() }+            var actual: UInt64 = 0+            var crc: UInt32 = .max+            while let bytes = try input.read(upToCount: chunkSize), !bytes.isEmpty {+                try check()+                actual += UInt64(bytes.count)+                guard actual <= UInt64(size) else { throw BackupError.changed }+                crc = CRC32.update(crc, bytes)+                try handle.write(contentsOf: bytes)+            }+            guard actual == UInt64(size), ~crc == checksum else { throw BackupError.changed }+            directory.append(member)+        }+        let start = try handle.offset()+        for member in directory { try handle.write(contentsOf: centralHeader(member)) }+        let end = try handle.offset()+        guard end + 22 <= maximumBytes else { throw BackupError.tooLarge }+        var footer = Data()+        footer.le32(0x06054b50); footer.le16(0); footer.le16(0)+        footer.le16(UInt16(directory.count)); footer.le16(UInt16(directory.count))+        footer.le32(UInt32(end - start)); footer.le32(UInt32(start)); footer.le16(0)+        try handle.write(contentsOf: footer)+        try handle.synchronize()+        try FileManager.default.moveItem(at: partial, to: destination)+    }++    static func members(in archive: URL) throws -> [ArchiveMember] {+        let handle = try FileHandle(forReadingFrom: archive)+        defer { try? handle.close() }+        let size = try handle.seekToEnd()+        guard size >= 22, size <= maximumBytes else { throw BackupError.tooLarge }+        try handle.seek(toOffset: size - 22)+        let footer = try exact(handle, count: 22)+        guard footer.u32(0) == 0x06054b50, footer.u16(4) == 0, footer.u16(6) == 0,+              footer.u16(8) == footer.u16(10), footer.u16(20) == 0 else { throw BackupError.invalidArchive }+        let count = Int(footer.u16(10))+        let length = UInt64(footer.u32(12)), offset = UInt64(footer.u32(16))+        guard offset + length == size - 22, count <= 10_000 else { throw BackupError.invalidArchive }+        try handle.seek(toOffset: offset)+        var members: [ArchiveMember] = []+        for _ in 0..<count {+            let header = try exact(handle, count: 46)+            guard header.u32(0) == 0x02014b50, header.u16(8) == 0x0800, header.u16(10) == 0,+                  header.u32(20) == header.u32(24), header.u16(34) == 0,+                  header.u16(30) == 0, header.u16(32) == 0 else { throw BackupError.unsupportedVersion }+            let nameBytes = try exact(handle, count: Int(header.u16(28)))+            guard let name = String(data: nameBytes, encoding: .utf8) else { throw BackupError.invalidArchive }+            try validName(name)+            _ = try exact(handle, count: Int(header.u16(30)) + Int(header.u16(32)))+            let member = ArchiveMember(name: name, size: header.u32(24), checksum: header.u32(16), offset: header.u32(42))+            guard UInt64(member.offset) < offset else { throw BackupError.invalidArchive }+            members.append(member)+        }+        guard try handle.offset() == offset + length, Set(members.map(\.name)).count == members.count else {+            throw BackupError.invalidArchive+        }+        try validateRanges(members, handle: handle, directoryOffset: offset)+        return members+    }++    private static func validateRanges(_ members: [ArchiveMember], handle: FileHandle, directoryOffset: UInt64) throws {+        var previousEnd: UInt64 = 0+        for member in members.sorted(by: { $0.offset < $1.offset }) {+            guard UInt64(member.offset) == previousEnd else { throw BackupError.invalidArchive }+            try handle.seek(toOffset: UInt64(member.offset))+            let local = try exact(handle, count: 30)+            guard local.u32(0) == 0x04034b50, local.u16(6) == 0x0800, local.u16(8) == 0,+                  local.u32(14) == member.checksum, local.u32(18) == member.size, local.u32(22) == member.size,+                  local.u16(28) == 0,+                  String(data: try exact(handle, count: Int(local.u16(26))), encoding: .utf8) == member.name else {+                throw BackupError.invalidArchive+            }+            previousEnd = try handle.offset() + UInt64(member.size)+            guard previousEnd <= directoryOffset else { throw BackupError.invalidArchive }+        }+        guard previousEnd == directoryOffset else { throw BackupError.invalidArchive }+    }++    static func read(_ member: ArchiveMember, from archive: URL, limit: Int) throws -> Data {+        guard UInt64(member.size) <= UInt64(limit) else { throw BackupError.tooLarge }+        let handle = try FileHandle(forReadingFrom: archive)+        defer { try? handle.close() }+        try handle.seek(toOffset: UInt64(member.offset))+        let header = try exact(handle, count: 30)+        guard header.u32(0) == 0x04034b50, header.u16(6) == 0x0800, header.u16(8) == 0,+              header.u32(14) == member.checksum, header.u32(18) == member.size, header.u32(22) == member.size else {+            throw BackupError.invalidArchive+        }+        let name = try exact(handle, count: Int(header.u16(26)))+        guard String(data: name, encoding: .utf8) == member.name else { throw BackupError.invalidArchive }+        _ = try exact(handle, count: Int(header.u16(28)))+        let data = try exact(handle, count: Int(member.size))+        guard ~CRC32.update(.max, data) == member.checksum else { throw BackupError.invalidArchive }+        return data+    }++    private static func measured(_ url: URL, check: () throws -> Void) throws -> (UInt32, UInt32) {+        let handle = try FileHandle(forReadingFrom: url)+        defer { try? handle.close() }+        var size: UInt64 = 0+        var checksum: UInt32 = .max+        while let bytes = try handle.read(upToCount: chunkSize), !bytes.isEmpty {+            try check()+            size += UInt64(bytes.count)+            guard size < maximumBytes else { throw BackupError.tooLarge }+            checksum = CRC32.update(checksum, bytes)+        }+        return (UInt32(size), ~checksum)+    }++    private static func validName(_ name: String) throws {+        let parts = name.split(separator: "/", omittingEmptySubsequences: false)+        guard !name.isEmpty, name.utf8.count <= 256, !name.contains("\\"), !name.contains("\0"),+              parts.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }) else { throw BackupError.invalidArchive }+    }++    private static func exact(_ handle: FileHandle, count: Int) throws -> Data {+        var result = Data()+        while result.count < count {+            try Task.checkCancellation()+            guard let data = try handle.read(upToCount: min(chunkSize, count - result.count)), !data.isEmpty else {+                throw BackupError.invalidArchive+            }+            result.append(data)+        }+        return result+    }++    private static func localHeader(_ member: ArchiveMember) -> Data {+        var header = Data()+        header.le32(0x04034b50); header.le16(20); header.le16(0x0800); header.le16(0)+        header.le16(0); header.le16(33); header.le32(member.checksum)+        header.le32(member.size); header.le32(member.size); header.le16(UInt16(member.name.utf8.count)); header.le16(0)+        header.append(Data(member.name.utf8))+        return header+    }++    private static func centralHeader(_ member: ArchiveMember) -> Data {+        var header = Data()+        header.le32(0x02014b50); header.le16(20); header.le16(20); header.le16(0x0800); header.le16(0)+        header.le16(0); header.le16(33); header.le32(member.checksum); header.le32(member.size); header.le32(member.size)+        header.le16(UInt16(member.name.utf8.count)); header.le16(0); header.le16(0); header.le16(0); header.le16(0)+        header.le32(0); header.le32(member.offset); header.append(Data(member.name.utf8))+        return header+    }+}++nonisolated private enum CRC32 {+    static let table: [UInt32] = (0..<256).map { index in+        var value = UInt32(index)+        for _ in 0..<8 { value = value & 1 == 0 ? value >> 1 : (value >> 1) ^ 0xedb88320 }+        return value+    }+    static func update(_ initial: UInt32, _ data: Data) -> UInt32 {+        data.reduce(initial) { ($0 >> 8) ^ table[Int(($0 ^ UInt32($1)) & 0xff)] }+    }+}++nonisolated private extension Data {+    mutating func le16(_ value: UInt16) { var number = value.littleEndian; Swift.withUnsafeBytes(of: &number) { append(contentsOf: $0) } }+    mutating func le32(_ value: UInt32) { var number = value.littleEndian; Swift.withUnsafeBytes(of: &number) { append(contentsOf: $0) } }+    func u16(_ offset: Int) -> UInt16 { UInt16(self[offset]) | UInt16(self[offset + 1]) << 8 }+    func u32(_ offset: Int) -> UInt32 { UInt32(u16(offset)) | UInt32(u16(offset + 2)) << 16 }+}
Halo Family/Halo Family/Persistence/BackupCancellation.swift Added
diff --git a/Halo Family/Halo Family/Persistence/BackupCancellation.swift b/Halo Family/Halo Family/Persistence/BackupCancellation.swiftnew file mode 100644index 0000000..e066789--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupCancellation.swift	@@ -0,0 +1,14 @@+import Foundation++/// Core Data executes perform blocks on its own queue. Carry caller cancellation+/// explicitly to that queue, including the last check before the atomic save.+nonisolated final class BackupCancellation: @unchecked Sendable {+    private let lock = NSLock()+    private var cancelled = false++    func cancel() { lock.withLock { cancelled = true } }+    func check() throws {+        try Task.checkCancellation()+        if lock.withLock({ cancelled }) { throw CancellationError() }+    }+}
Halo Family/Halo Family/Persistence/BackupHistory.swift Added
diff --git a/Halo Family/Halo Family/Persistence/BackupHistory.swift b/Halo Family/Halo Family/Persistence/BackupHistory.swiftnew file mode 100644index 0000000..a16158d--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupHistory.swift	@@ -0,0 +1,131 @@+import CoreData+import Foundation++/// Historical snapshots can refer to rows that undo has since removed. Copy their identity+/// namespace too, without guessing current relationships or dropping the original accounts.+nonisolated struct BackupHistory {+    private static let fields: [String: [String]] = [+        "PersonMerge": ["beforeData", "afterData", "archivedData"],+        "MergeConnectionReview": ["reviewedData"],+        "PersonMergeRecovery": ["beforeData", "afterData"],+    ]+    private var snapshotPaths: [String] = []+    private var arrays: [UUID: [String: [UUID]]] = [:]++    init(backup: FamilyBackup, model: NSManagedObjectModel,+         check: () throws -> Void = { try Task.checkCancellation() }, payload: (String) throws -> Data) throws {+        var types = Dictionary(uniqueKeysWithValues: backup.records.map { ($0.id, $0.entity) })+        for record in backup.records {+            try check()+            for field in Self.fields[record.entity] ?? [] {+                try check()+                guard case .binary(let path) = record.attributes[field] else { throw BackupError.invalidArchive }+                let rows = try MergeSnapshot.decode(payload(path))+                snapshotPaths.append(path)+                for row in rows {+                    try check()+                    guard types[row.id] == nil || types[row.id] == row.entity else { throw BackupError.invalidArchive }+                    types[row.id] = row.entity+                }+            }+            for field in ["recoveryIDs", "mergeIDs"] {+                guard case .text(let text) = record.attributes[field] else { continue }+                guard let values = try? JSONDecoder().decode([UUID].self, from: Data(text.utf8)),+                      Set(values).count == values.count else { throw BackupError.invalidArchive }+                arrays[record.id, default: [:]][field] = values+            }+        }+        for path in snapshotPaths {+            try check()+            let rows = try MergeSnapshot.decode(payload(path))+            for row in rows { try check(); try Self.validate(row, familyID: backup.familyID, model: model, types: types) }+        }+    }++    func copied(_ backup: FamilyBackup, check: () throws -> Void = { try Task.checkCancellation() },+                payload: (String) throws -> Data) throws -> (FamilyBackup, [String: Data]) {+        let map = Dictionary(uniqueKeysWithValues: try identities(in: backup, check: check, payload: payload).map { ($0, UUID()) })+        func mapped(_ id: UUID) throws -> UUID {+            guard let result = map[id] else { throw BackupError.invalidArchive }+            return result+        }+        var payloads: [String: Data] = [:]+        for path in snapshotPaths {+            try check()+            let rows = try MergeSnapshot.decode(payload(path))+            payloads[path] = try MergeSnapshot.encode(rows.map { row in+                try check()+                return MergeRecord(id: try mapped(row.id), entity: row.entity,+                            attributes: try row.attributes.mapValues { value in+                                if case .uuid(let id) = value { return .uuid(try mapped(id)) }+                                return value+                            }, links: try row.links.mapValues { try $0.map(mapped).sorted { $0.uuidString < $1.uuidString } })+            }.sorted { $0.id.uuidString < $1.id.uuidString })+        }+        let records = try backup.records.map { record in+            try check()+            var attributes = try record.attributes.mapValues { value in+                if case .uuid(let id) = value { return PortableValue.uuid(try mapped(id)) }+                return value+            }+            for (field, ids) in arrays[record.id] ?? [:] {+                let data = try JSONEncoder().encode(ids.map(mapped))+                guard let text = String(data: data, encoding: .utf8) else { throw BackupError.invalidArchive }+                attributes[field] = .text(text)+            }+            if record.entity == "PersonMerge" { attributes["undoUnavailableAt"] = .date(Date()) }+            return PortableRecord(id: try mapped(record.id), entity: record.entity, attributes: attributes,+                                  relationships: try record.relationships.mapValues { try $0.map(mapped) })+        }+        return (FamilyBackup(formatVersion: backup.formatVersion, modelVersion: backup.modelVersion,+                             familyID: try mapped(backup.familyID), createdAt: backup.createdAt, records: records), payloads)+    }++    private func identities(in backup: FamilyBackup, check: () throws -> Void, payload: (String) throws -> Data) throws -> Set<UUID> {+        var identities = Set(backup.records.map(\.id))+        for record in backup.records {+            try check()+            for value in record.attributes.values { if case .uuid(let id) = value { identities.insert(id) } }+        }+        for path in snapshotPaths {+            try check()+            let rows = try MergeSnapshot.decode(payload(path))+            for row in rows {+                try check()+                identities.insert(row.id)+                for value in row.attributes.values { if case .uuid(let id) = value { identities.insert(id) } }+                for links in row.links.values { identities.formUnion(links) }+            }+        }+        for values in arrays.values { for ids in values.values { identities.formUnion(ids) } }+        return identities+    }++    private static func validate(_ row: MergeRecord, familyID: UUID, model: NSManagedObjectModel,+                                 types: [UUID: String]) throws {+        guard let entity = model.entitiesByName[row.entity], fields[row.entity] == nil, row.entity != "FamilySpace",+              row.attributes["id"] == .uuid(row.id), row.links["familySpace"] == [familyID],+              Set(row.links.keys) == Set(entity.relationshipsByName.keys) else { throw BackupError.invalidArchive }+        for (key, value) in row.attributes {+            guard let attribute = entity.attributesByName[key], PortableGraph.accepts(portable(value), attribute: attribute) else {+                throw BackupError.invalidArchive+            }+        }+        for (key, links) in row.links {+            guard let relationship = entity.relationshipsByName[key], relationship.isToMany || links.count <= 1,+                  Set(links).count == links.count,+                  links.allSatisfy({ types[$0] == relationship.destinationEntity?.name }) else { throw BackupError.invalidArchive }+        }+    }++    private static func portable(_ value: SnapshotValue) -> PortableValue {+        switch value {+        case .text(let value): .text(value)+        case .integer(let value): .number(value)+        case .decimal(let value): .decimal(value)+        case .flag(let value): .flag(value)+        case .date(let value): .date(value)+        case .uuid(let value): .uuid(value)+        }+    }+}
Halo Family/Halo Family/Persistence/BackupRepository.swift Added
diff --git a/Halo Family/Halo Family/Persistence/BackupRepository.swift b/Halo Family/Halo Family/Persistence/BackupRepository.swiftnew file mode 100644index 0000000..a4dfb1f--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupRepository.swift	@@ -0,0 +1,276 @@+import CoreData+import CryptoKit+import Foundation++nonisolated struct BackupPreview: Sendable {+    let archive: URL+    let backup: FamilyBackup+    let members: [ArchiveMember]+    let familyName: String+    let peopleCount: Int+    let eventCount: Int+    let payloadBytes: UInt64+    let fingerprint: Data+}++@MainActor+final class BackupRepository {+    #if os(iOS)+    nonisolated private static let payloadLimit: UInt64 = 128_000_000+    #else+    nonisolated private static let payloadLimit: UInt64 = 512_000_000+    #endif+    private let stack: PersistenceStack+    init(stack: PersistenceStack) { self.stack = stack }++    func export(familyID: NSManagedObjectID, readable: Bool = true) async throws -> URL {+        guard stack.role == .host else { throw GraphError.readOnly }+        let context = stack.container.newBackgroundContext()+        let model = stack.container.managedObjectModel+        let cancellation = BackupCancellation()+        return try await withTaskCancellationHandler { try await context.perform {+            try cancellation.check()+            try context.setQueryGenerationFrom(.current)+            guard familyID.entity.name == "FamilySpace", !familyID.isTemporaryID else { throw GraphError.invalidReference }+            let family = try context.existingObject(with: familyID)+            guard let uuid = family.value(forKey: "id") as? UUID else { throw BackupError.missingIdentity }+            let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)+            try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+            var delivered = false+            defer { if !delivered { try? FileManager.default.removeItem(at: folder) } }+            var files: [BackupFile] = []+            var records: [PortableRecord] = []+            for entity in model.entities.sorted(by: { ($0.name ?? "") < ($1.name ?? "") }) {+                guard let name = entity.name else { continue }+                let request = NSFetchRequest<NSManagedObject>(entityName: name)+                if name == "FamilySpace" { request.predicate = NSPredicate(format: "SELF == %@", familyID) } else if+                    entity.relationshipsByName["familySpace"] != nil {+                    request.predicate = NSPredicate(format: "familySpace == %@", familyID)+                } else { continue }+                for object in try context.fetch(request) {+                    try cancellation.check()+                    guard let id = object.value(forKey: "id") as? UUID else { throw BackupError.missingIdentity }+                    let record = try PortableGraph.record(object) { key, data in+                        let path = "payloads/\(id.uuidString)/\(key).bin"+                        let url = folder.appendingPathComponent(path)+                        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+                        try data.write(to: url, options: .atomic)+                        files.append(BackupFile(name: path, url: url))+                        return path+                    }+                    records.append(record)+                    context.refresh(object, mergeChanges: false)+                }+            }+            let backup = FamilyBackup(formatVersion: 1, modelVersion: 6, familyID: uuid, createdAt: Date(),+                                      records: records.sorted { $0.id.uuidString < $1.id.uuidString })+            try BackupValidation.validate(backup, model: model, check: cancellation.check)+            let manifest = folder.appendingPathComponent("family.json")+            let manifestData = try PortableGraph.encode(backup)+            guard manifestData.count <= 32_000_000 else { throw BackupError.tooLarge }+            try manifestData.write(to: manifest, options: .atomic)+            files.append(BackupFile(name: "family.json", url: manifest))+            if readable {+                let markdown = folder.appendingPathComponent("Family.md")+                try Self.markdown(backup).write(to: markdown, atomically: true, encoding: .utf8)+                files.append(BackupFile(name: "Family.md", url: markdown))+            }+            let archive = folder.appendingPathComponent("Halo Family Backup.zip")+            try cancellation.check()+            try BackupArchive.write(files, to: archive, check: cancellation.check)+            try cancellation.check()+            for file in files { try? FileManager.default.removeItem(at: file.url) }+            delivered = true+            return archive+        }+        } onCancel: { cancellation.cancel() }+    }++    func preview(_ archive: URL) async throws -> BackupPreview {+        let model = stack.container.managedObjectModel+        let task = Task.detached {+            let fingerprint = try Self.fingerprint(archive)+            let members = try BackupArchive.members(in: archive)+            let indexed = Dictionary(uniqueKeysWithValues: members.map { ($0.name, $0) })+            guard let manifest = indexed["family.json"] else { throw BackupError.invalidArchive }+            let data = try BackupArchive.read(manifest, from: archive, limit: 32_000_000)+            let backup = try PortableGraph.decode(FamilyBackup.self, data: data)+            try BackupValidation.validate(backup, model: model)+            let bytes = try Self.validatePayloads(backup, archive: archive, members: indexed)+            guard bytes <= Self.payloadLimit else { throw BackupError.tooLarge }+            _ = try BackupHistory(backup: backup, model: model) { path in+                try Self.payload(path, archive: archive, members: indexed)+            }+            let root = backup.records.first { $0.id == backup.familyID }+            let name: String+            if case .text(let value) = root?.attributes["name"] { name = value } else { name = "Family" }+            guard try Self.fingerprint(archive) == fingerprint else { throw BackupError.changed }+            return BackupPreview(archive: archive, backup: backup, members: members, familyName: name,+                                 peopleCount: backup.records.filter { $0.entity == "Person" }.count,+                                 eventCount: backup.records.filter { $0.entity == "Event" }.count, payloadBytes: bytes,+                                 fingerprint: fingerprint)+        }+        return try await withTaskCancellationHandler { try await task.value } onCancel: { task.cancel() }+    }++    func restore(_ preview: BackupPreview, asNewCopy: Bool) async throws -> NSManagedObjectID {+        guard stack.role == .host else { throw GraphError.readOnly }+        guard !stack.importingBackup else { throw BackupError.importing }+        // A single atomic context save avoids exposing a partially imported family. Bound its payload memory.+        guard preview.payloadBytes <= Self.payloadLimit else { throw BackupError.tooLarge }+        stack.importingBackup = true+        defer { stack.importingBackup = false }+        let container = stack.container+        let context = container.newBackgroundContext()+        context.transactionAuthor = stack.role.rawValue+        let cancellation = BackupCancellation()+        let result = try await withTaskCancellationHandler { try await context.perform {+            guard try Self.fingerprint(preview.archive, cancellation: cancellation) == preview.fingerprint else {+                throw BackupError.changed+            }+            let members = try BackupArchive.members(in: preview.archive)+            guard members.count == preview.members.count,+                  zip(members, preview.members).allSatisfy({ pair in+                      pair.0.name == pair.1.name && pair.0.size == pair.1.size && pair.0.checksum == pair.1.checksum+                  }) else {+                throw BackupError.changed+            }+            let model = container.managedObjectModel+            try BackupValidation.validate(preview.backup, model: model, check: cancellation.check)+            let indexed = Dictionary(uniqueKeysWithValues: members.map { ($0.name, $0) })+            let history = try BackupHistory(backup: preview.backup, model: model, check: cancellation.check) { path in+                try Self.payload(path, archive: preview.archive, members: indexed)+            }+            let prepared: (FamilyBackup, [String: Data])+            if asNewCopy {+                prepared = try history.copied(preview.backup, check: cancellation.check) { path in+                    try Self.payload(path, archive: preview.archive, members: indexed)+                }+            } else { prepared = (preview.backup, [:]) }+            let (backup, overrides) = prepared+            try Self.requireAbsent(backup.records.map(\.id), in: context, model: model, cancellation: cancellation)+            guard let store = container.persistentStoreCoordinator.persistentStores.first(where: {+                $0.url?.lastPathComponent == "Private.sqlite"+            }) else { throw GraphError.invalidReference }+            try cancellation.check()+            let objects = try Self.insert(backup.records, context: context, store: store, cancellation: cancellation) { path in+                if let data = overrides[path] { return data }+                return try Self.payload(path, archive: preview.archive, members: indexed)+            }+            try Self.link(backup.records, objects: objects)+            guard let root = objects[backup.familyID] else { throw BackupError.invalidArchive }+            if asNewCopy { root.setValue(preview.familyName + " (copy)", forKey: "name") }+            let inserted = Array(context.insertedObjects)+            guard try Self.fingerprint(preview.archive, cancellation: cancellation) == preview.fingerprint else {+                throw BackupError.changed+            }+            try cancellation.check()+            try context.save()+            return (root.objectID, inserted.map(\.objectID))+        }+        } onCancel: { cancellation.cancel() }+        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [NSInsertedObjectsKey: result.1], into: [container.viewContext])+        NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: container)+        return result.0+    }++    nonisolated private static func requireAbsent(_ ids: [UUID], in context: NSManagedObjectContext,+                                                  model: NSManagedObjectModel, cancellation: BackupCancellation) throws {+        // Bound SQL bind variables even for large archives. Existing rows are never overwritten.+        for entity in model.entities {+            guard let name = entity.name else { continue }+            for start in stride(from: 0, to: ids.count, by: 400) {+                try cancellation.check()+                let request = NSFetchRequest<NSManagedObject>(entityName: name)+                request.predicate = NSPredicate(format: "id IN %@", Array(ids[start..<min(start + 400, ids.count)]) as NSArray)+                request.fetchLimit = 1+                guard try context.count(for: request) == 0 else { throw BackupError.familyExists }+            }+        }+    }++    nonisolated private static func insert(_ records: [PortableRecord], context: NSManagedObjectContext,+                                           store: NSPersistentStore, cancellation: BackupCancellation,+                                           payload: (String) throws -> Data) throws -> [UUID: NSManagedObject] {+        var objects: [UUID: NSManagedObject] = [:]+        for record in records {+            try cancellation.check()+            let object = NSEntityDescription.insertNewObject(forEntityName: record.entity, into: context)+            context.assign(object, to: store)+            for (key, value) in record.attributes { object.setValue(try PortableGraph.value(value, binary: payload), forKey: key) }+            objects[record.id] = object+        }+        return objects+    }++    nonisolated private static func link(_ records: [PortableRecord], objects: [UUID: NSManagedObject]) throws {+        for record in records {+            guard let object = objects[record.id] else { throw BackupError.invalidArchive }+            for (key, links) in record.relationships {+                let targets = try links.map { id in+                    guard let target = objects[id] else { throw BackupError.invalidArchive }+                    return target+                }+                if object.entity.relationshipsByName[key]?.isToMany == true { object.setValue(NSSet(array: targets), forKey: key) } else {+                    object.setValue(targets.first, forKey: key)+                }+            }+        }+    }++    nonisolated private static func payload(_ path: String, archive: URL, members: [String: ArchiveMember]) throws -> Data {+        guard let member = members[path] else { throw BackupError.invalidArchive }+        return try BackupArchive.read(member, from: archive, limit: 32_000_000)+    }++    nonisolated private static func validatePayloads(_ backup: FamilyBackup, archive: URL,+                                                     members: [String: ArchiveMember]) throws -> UInt64 {+        var expected: Set<String> = ["family.json"]+        if members["Family.md"] != nil {+            expected.insert("Family.md")+            _ = try payload("Family.md", archive: archive, members: members)+        }+        var bytes: UInt64 = 0+        for record in backup.records {+            for (key, value) in record.attributes {+                guard case .binary(let path) = value else { continue }+                guard path == "payloads/\(record.id.uuidString)/\(key).bin", expected.insert(path).inserted,+                      let member = members[path] else { throw BackupError.invalidArchive }+                let data = try payload(path, archive: archive, members: members)+                try BackupValidation.payload(data, key: key, record: record)+                bytes += UInt64(member.size)+            }+        }+        guard expected == Set(members.keys) else { throw BackupError.invalidArchive }+        return bytes+    }++    nonisolated private static func fingerprint(_ archive: URL, cancellation: BackupCancellation? = nil) throws -> Data {+        let handle = try FileHandle(forReadingFrom: archive)+        defer { try? handle.close() }+        var hash = SHA256()+        var count: UInt64 = 0+        while let data = try handle.read(upToCount: 65_536), !data.isEmpty {+            try Task.checkCancellation()+            try cancellation?.check()+            count += UInt64(data.count)+            guard count <= BackupArchive.maximumBytes else { throw BackupError.tooLarge }+            hash.update(data: data)+        }+        return Data(hash.finalize())+    }++    nonisolated private static func markdown(_ backup: FamilyBackup) -> String {+        var lines = ["# Halo Family backup", "", "Created: \(backup.createdAt.formatted())", ""]+        let readable = ["Person", "Event", "Context", "PersonGroup", "RelationshipAssertion", "GiftRecord"]+        for record in backup.records where readable.contains(record.entity) {+            let title = ["displayName", "title", "name", "customLabel", "descriptionText"].compactMap { key -> String? in+                if case .text(let value) = record.attributes[key] { return value }+                return nil+            }.first ?? record.entity+            lines += ["## \(title.replacingOccurrences(of: "\n", with: " "))", "", "Type: \(record.entity)", ""]+            if case .text(let notes) = record.attributes["notes"] ?? record.attributes["note"], !notes.isEmpty { lines += [notes, ""] }+        }+        return lines.joined(separator: "\n")+    }+}
Halo Family/Halo Family/Persistence/BackupStaging.swift Added
diff --git a/Halo Family/Halo Family/Persistence/BackupStaging.swift b/Halo Family/Halo Family/Persistence/BackupStaging.swiftnew file mode 100644index 0000000..443cba1--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupStaging.swift	@@ -0,0 +1,28 @@+import Foundation++nonisolated enum BackupStaging {+    /// Own a bounded copy of the selected document. Later provider edits cannot change this preview.+    static func copy(_ selected: URL) throws -> URL {+        let access = selected.startAccessingSecurityScopedResource()+        defer { if access { selected.stopAccessingSecurityScopedResource() } }+        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)+        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+        do {+            let archive = folder.appendingPathComponent("Selected Backup.zip")+            guard FileManager.default.createFile(atPath: archive.path, contents: nil) else { throw BackupError.invalidArchive }+            let source = try FileHandle(forReadingFrom: selected), output = try FileHandle(forWritingTo: archive)+            defer { try? source.close(); try? output.close() }+            var bytes: UInt64 = 0+            while let data = try source.read(upToCount: 65_536), !data.isEmpty {+                try Task.checkCancellation()+                bytes += UInt64(data.count)+                guard bytes <= BackupArchive.maximumBytes else { throw BackupError.tooLarge }+                try output.write(contentsOf: data)+            }+            return archive+        } catch {+            try? FileManager.default.removeItem(at: folder)+            throw error+        }+    }+}
Halo Family/Halo Family/Persistence/BackupValidation.swift Added
diff --git a/Halo Family/Halo Family/Persistence/BackupValidation.swift b/Halo Family/Halo Family/Persistence/BackupValidation.swiftnew file mode 100644index 0000000..6f62c8b--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupValidation.swift	@@ -0,0 +1,161 @@+import CoreData+import Foundation++nonisolated enum BackupValidation {+    private static let requiredLinks: [String: [String]] = [+        "ChildProfile": ["person"], "Connection": ["child", "person"],+        "ConnectionContext": ["connection", "context"], "ConnectionOrigin": ["connection"],+        "OriginProposal": ["connection"], "ContextPerson": ["context", "person"],+        "ConnectionClosenessPeriod": ["connection"], "ConnectionStatusPeriod": ["connection"],+        "PersonRelationship": ["source", "target"], "RelationshipAssertion": ["source", "target"],+        "AddressLabel": ["target"], "GroupMembership": ["group", "person"],+        "EventPerson": ["event", "person"], "GiftRecord": ["event"], "EventAttachment": ["event", "asset"],+    ]++    static func validate(_ backup: FamilyBackup, model: NSManagedObjectModel,+                         check: () throws -> Void = { try Task.checkCancellation() }) throws {+        guard backup.formatVersion == 1, (1...6).contains(backup.modelVersion), backup.records.count <= 100_000 else {+            throw BackupError.unsupportedVersion+        }+        let indexed = try index(backup.records, check: check)+        let linkSets = Dictionary(uniqueKeysWithValues: backup.records.map { ($0.id, $0.relationships.mapValues { Set($0) }) })+        guard indexed[backup.familyID]?.entity == "FamilySpace",+              backup.records.filter({ $0.entity == "FamilySpace" }).count == 1 else { throw BackupError.invalidArchive }+        for record in backup.records {+            try check()+            guard let entity = model.entitiesByName[record.entity], record.attributes["id"] == .uuid(record.id) else {+                throw BackupError.invalidArchive+            }+            for (key, value) in record.attributes {+                guard let attribute = entity.attributesByName[key], PortableGraph.accepts(value, attribute: attribute) else {+                    throw BackupError.invalidArchive+                }+            }+            if record.id != backup.familyID, record.relationships["familySpace"] != [backup.familyID] {+                throw BackupError.invalidArchive+            }+            for (key, targets) in record.relationships {+                guard let relationship = entity.relationshipsByName[key], !relationship.isOrdered,+                      Set(targets).count == targets.count, relationship.isToMany || targets.count <= 1 else {+                    throw BackupError.invalidArchive+                }+                for target in targets {+                    guard let other = indexed[target], other.entity == relationship.destinationEntity?.name,+                          let inverse = relationship.inverseRelationship?.name,+                          linkSets[target]?[inverse]?.contains(record.id) == true else { throw BackupError.invalidArchive }+                }+            }+            try domain(record, indexed: indexed)+        }+        try acyclic(backup.records.filter { $0.entity == "Context" }, edge: "parent", check: check)+        try acyclic(backup.records.filter { $0.entity == "OriginProposal" }, edge: "predecessors", check: check)+    }++    static func index(_ records: [PortableRecord],+                      check: () throws -> Void = { try Task.checkCancellation() }) throws -> [UUID: PortableRecord] {+        var indexed: [UUID: PortableRecord] = [:]+        for record in records {+            try check()+            guard indexed.updateValue(record, forKey: record.id) == nil else { throw BackupError.invalidArchive }+        }+        return indexed+    }++    private static func domain(_ record: PortableRecord, indexed: [UUID: PortableRecord]) throws {+        let values = record.attributes+        func integer(_ key: String) -> Int? { if case .number(let value) = values[key] { return Int(exactly: value) }; return nil }+        func text(_ key: String) -> String? { if case .text(let value) = values[key] { return value }; return nil }+        for link in requiredLinks[record.entity] ?? [] {+            guard record.relationships[link]?.count == 1 else { throw BackupError.invalidArchive }+        }+        if case .date(let start) = values["startedAt"], case .date(let end) = values["endedAt"], end < start {+            throw BackupError.invalidArchive+        }+        switch record.entity {+        case "Person":+            let date = try PartialDate(year: integer("deathYear"), month: integer("deathMonth"), day: integer("deathDay"))+            guard date.year == nil && date.month == nil && date.day == nil || values["isDeceased"] == .flag(true) else {+                throw BackupError.invalidArchive+            }+        case "Event":+            if case .date(let start) = values["date"], case .date(let end) = values["endDate"], end < start {+                throw BackupError.invalidArchive+            }+        case "Asset": try asset(record)+        case "ConnectionOrigin", "OriginProposal":+            let context = record.relationships["context"] ?? [], event = record.relationships["event"] ?? []+            let narrative = text(record.entity == "ConnectionOrigin" ? "originDescription" : "narrative") ?? ""+            let cleared = values["isCleared"] == .flag(true)+            guard context.isEmpty || event.isEmpty,+                  cleared ? (context.isEmpty && event.isEmpty && narrative.isEmpty) :+                    (!context.isEmpty || !event.isEmpty || !narrative.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) else {+                throw BackupError.invalidArchive+            }+            for predecessor in record.relationships["predecessors"] ?? [] {+                guard indexed[predecessor]?.relationships["connection"] == record.relationships["connection"] else {+                    throw BackupError.invalidArchive+                }+            }+        case "ConnectionClosenessPeriod":+            guard let value = integer("value"), (1...10).contains(value) else { throw BackupError.invalidArchive }+        case "ConnectionStatusPeriod":+            guard ConnectionState(rawValue: text("state") ?? "") != nil else { throw BackupError.invalidArchive }+        case "EventPerson":+            guard InvitationState(rawValue: text("invitationState") ?? "unknown") != nil,+                  AttendanceState(rawValue: text("attendanceState") ?? "unknown") != nil else { throw BackupError.invalidArchive }+            if let roles = text("roles"), (try? JSONDecoder().decode([String].self, from: Data(roles.utf8))) == nil {+                throw BackupError.invalidArchive+            }+        case "GiftRecord":+            for attachment in record.relationships["attachments"] ?? [] {+                guard indexed[attachment]?.relationships["event"] == record.relationships["event"] else {+                    throw BackupError.invalidArchive+                }+            }+        default: break+        }+    }++    private static func asset(_ record: PortableRecord) throws {+        let photo = !(record.relationships["photoPerson"] ?? []).isEmpty+        let attachment = !(record.relationships["eventAttachment"] ?? []).isEmpty+        guard !photo || !attachment else { throw BackupError.invalidArchive }+        if photo || attachment {+            guard case .binary = record.attributes["data"] else { throw BackupError.invalidArchive }+        }+    }++    static func payload(_ data: Data, key: String, record: PortableRecord) throws {+        guard record.entity == "Asset", key == "data" else { return }+        let photo = !(record.relationships["photoPerson"] ?? []).isEmpty+        let attachment = !(record.relationships["eventAttachment"] ?? []).isEmpty+        let limit = photo ? ImageImport.photoLimit : attachment ? ImageImport.attachmentLimit : 32_000_000+        guard data.count <= limit, (!photo && !attachment) || !data.isEmpty else { throw BackupError.tooLarge }+        if case .number(let size) = record.attributes["byteCount"], size != Int64(data.count) {+            throw BackupError.invalidArchive+        }+    }++    private static func acyclic(_ records: [PortableRecord], edge: String, check: () throws -> Void) throws {+        var incoming = Dictionary(uniqueKeysWithValues: records.map { ($0.id, 0) })+        let indexed = Dictionary(uniqueKeysWithValues: records.map { ($0.id, $0) })+        for record in records {+            try check()+            for target in record.relationships[edge] ?? [] {+                guard indexed[target] != nil else { throw BackupError.invalidArchive }+                incoming[target, default: 0] += 1+            }+        }+        var ready = Set(incoming.filter { $0.value == 0 }.map(\.key))+        var processed = 0+        while let id = ready.popFirst() {+            try check()+            processed += 1+            for target in indexed[id]?.relationships[edge] ?? [] {+                incoming[target, default: 0] -= 1+                if incoming[target] == 0 { ready.insert(target) }+            }+        }+        guard processed == records.count else { throw BackupError.invalidArchive }+    }+}
Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift Added
diff --git a/Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift b/Halo Family/Halo Family/Persistence/ContextCategoryRepository.swiftnew file mode 100644index 0000000..0c0e425--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift	@@ -0,0 +1,88 @@+import CoreData+import Foundation++struct ContextCategoryRow: Identifiable, Equatable {+    let id: NSManagedObjectID+    let name: String+    let isArchived: Bool+}++@MainActor+extension FamilyRepository {+    static let starterCategories = ["School", "Playgroup", "Parent group", "Childcare", "Activities"]++    func seedCategories(family: NSManagedObject, in context: NSManagedObjectContext) throws {+        guard stack.container.managedObjectModel.entitiesByName["ContextCategory"] != nil else { return }+        let request = NSFetchRequest<NSManagedObject>(entityName: "ContextCategory")+        request.predicate = NSPredicate(format: "familySpace == %@", family)+        let existing = Set(try context.fetch(request).compactMap { ($0.value(forKey: "name") as? String)?.lowercased() })+        for name in Self.starterCategories where !existing.contains(name.lowercased()) {+            let category = insert("ContextCategory", in: context, store: try owningStore(of: family))+            category.setValue(name, forKey: "name")+            category.setValue(family, forKey: "familySpace")+        }+    }++    func addStarterCategories(familyID: NSManagedObjectID) throws {+        _ = try write { context in+            let family = try record(familyID, entity: "FamilySpace", in: context)+            try seedCategories(family: family, in: context)+            return family+        }+    }++    func contextCategories(in familyID: NSManagedObjectID) throws -> [ContextCategoryRow] {+        _ = try readable(familyID, entity: "FamilySpace")+        let request = NSFetchRequest<NSManagedObject>(entityName: "ContextCategory")+        request.predicate = NSPredicate(format: "familySpace == %@", familyID)+        request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]+        return try stack.container.viewContext.fetch(request).map(categoryRow)+    }++    func createCategory(name: String, familyID: NSManagedObjectID) throws -> NSManagedObjectID {+        let name = try validated(name)+        return try write { context in+            let family = try record(familyID, entity: "FamilySpace", in: context)+            let category = insert("ContextCategory", in: context, store: try owningStore(of: family))+            category.setValue(family, forKey: "familySpace")+            category.setValue(name, forKey: "name")+            return category+        }+    }++    func updateCategory(_ expected: ContextCategoryRow, name: String, archived: Bool) throws {+        let name = try validated(name)+        _ = try write { context in+            let category = try record(expected.id, entity: "ContextCategory", in: context)+            guard categoryRow(category) == expected else { throw MemoryError.changed }+            category.setValue(name, forKey: "name")+            category.setValue(archived ? (category.value(forKey: "archivedAt") as? Date ?? Date()) : nil, forKey: "archivedAt")+            return category+        }+    }++    func contextCategory(_ contextID: NSManagedObjectID) throws -> NSManagedObjectID? {+        (try readable(contextID, entity: "Context").value(forKey: "category") as? NSManagedObject)?.objectID+    }++    func setContextCategory(_ contextID: NSManagedObjectID, categoryID: NSManagedObjectID?,+                            expectedID: NSManagedObjectID?) throws {+        _ = try write { context in+            let source = try record(contextID, entity: "Context", in: context)+            let current = (source.value(forKey: "category") as? NSManagedObject)?.objectID+            guard current == expectedID else { throw MemoryError.changed }+            let category = try categoryID.map { try record($0, entity: "ContextCategory", in: context) }+            if let category {+                try requireSameFamily(category, family: family(of: source))+                guard category.value(forKey: "archivedAt") == nil || category.objectID == current else { throw MemoryError.changed }+            }+            source.setValue(category, forKey: "category")+            return source+        }+    }++    private func categoryRow(_ object: NSManagedObject) -> ContextCategoryRow {+        ContextCategoryRow(id: object.objectID, name: object.value(forKey: "name") as? String ?? "Unnamed",+                           isArchived: object.value(forKey: "archivedAt") != nil)+    }+}
Halo Family/Halo Family/Persistence/PeopleSearch.swift Added
diff --git a/Halo Family/Halo Family/Persistence/PeopleSearch.swift b/Halo Family/Halo Family/Persistence/PeopleSearch.swiftnew file mode 100644index 0000000..e0c9706--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PeopleSearch.swift	@@ -0,0 +1,88 @@+import CoreData+import Foundation++struct PersonContextRoleRow: Identifiable {+    let association: ContextPersonRow+    let contextPath: String+    let isArchived: Bool+    var id: NSManagedObjectID { association.id }+}++@MainActor+extension FamilyRepository {+    /// Each key path has at most one to-many traversal, supported by the SQLite store.+    /// Entered names and titles stay literal; this does not infer gender or family terminology.+    func peopleSearch(_ text: String, familyID: NSManagedObjectID) throws -> NSPredicate {+        let model = stack.container.managedObjectModel+        let scalar = ["displayName", "givenName", "familyName"]+        let paths = ["addressLabels.label", "contextLinks.role", "contextLinks.context.name",+                     "groupMemberships.group.name", "groupMemberships.role",+                     "relationshipAssertionFrom.customLabel", "relationshipAssertionFrom.target.displayName",+                     "relationshipAssertionTo.source.displayName", "personRelationshipFrom.kind",+                     "personRelationshipFrom.target.displayName", "personRelationshipTo.source.displayName"]+        guard let person = model.entitiesByName["Person"] else { throw GraphError.modelUnavailable }+        var predicates = scalar.filter { person.attributesByName[$0] != nil }.map {+            NSPredicate(format: "%K CONTAINS[cd] %@", $0, text)+        }+        for path in paths where validSearchPath(path, from: person) {+            predicates.append(NSPredicate(format: "ANY %K CONTAINS[cd] %@", path, text))+        }+        if person.relationshipsByName["personRelationshipFrom"] != nil {+            let kinds = StructuralKind.allCases.filter {+                $0.label.range(of: text, options: [.caseInsensitive, .diacriticInsensitive]) != nil+            }+            predicates.append(NSPredicate(format: "ANY personRelationshipFrom.kind IN %@", kinds.map(\.rawValue)))+            let symmetric = kinds.filter { $0 == .siblingOf || $0 == .partnerOf }.map(\.rawValue)+            predicates.append(NSPredicate(format: "ANY personRelationshipTo.kind IN %@", symmetric))+        }+        if model.entitiesByName["ConnectionContext"] != nil {+            // Context paths may be arbitrarily deep. Match the derived path once, then fetch+            // membership rows directly rather than joining two to-many relationships from Person.+            let contexts = try contexts(in: familyID).filter {+                $0.path.range(of: text, options: [.caseInsensitive, .diacriticInsensitive]) != nil+            }+            if !contexts.isEmpty {+                let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionContext")+                request.predicate = NSPredicate(format: "familySpace == %@ AND context IN %@", familyID, contexts.map(\.id))+                request.relationshipKeyPathsForPrefetching = ["connection.person"]+                let ids = Set(try stack.container.viewContext.fetch(request).compactMap {+                    ($0.value(forKeyPath: "connection.person") as? NSManagedObject)?.objectID+                })+                predicates.append(NSPredicate(format: "SELF IN %@", Array(ids)))+                let roles = NSFetchRequest<NSManagedObject>(entityName: "ContextPerson")+                roles.predicate = NSPredicate(format: "familySpace == %@ AND context IN %@", familyID, contexts.map(\.id))+                roles.relationshipKeyPathsForPrefetching = ["person"]+                let people = Set(try stack.container.viewContext.fetch(roles).compactMap {+                    ($0.value(forKey: "person") as? NSManagedObject)?.objectID+                })+                predicates.append(NSPredicate(format: "SELF IN %@", Array(people)))+            }+        }+        return NSCompoundPredicate(orPredicateWithSubpredicates: predicates)+    }++    func personContextRoles(_ personID: NSManagedObjectID) throws -> [PersonContextRoleRow] {+        _ = try readable(personID, entity: "Person")+        let request = NSFetchRequest<NSManagedObject>(entityName: "ContextPerson")+        request.predicate = NSPredicate(format: "person == %@", personID)+        request.relationshipKeyPathsForPrefetching = ["context", "person"]+        return try stack.container.viewContext.fetch(request).compactMap { row in+            guard let context = row.value(forKey: "context") as? NSManagedObject else { return nil }+            let association = ContextPersonRow(id: row.objectID, contextID: context.objectID, personID: personID,+                name: row.value(forKeyPath: "person.displayName") as? String ?? "Unnamed", role: row.value(forKey: "role") as? String ?? "",+                startedAt: row.value(forKey: "startedAt") as? Date, endedAt: row.value(forKey: "endedAt") as? Date)+            return PersonContextRoleRow(association: association, contextPath: contextPath(context),+                                        isArchived: context.value(forKey: "archivedAt") != nil)+        }.sorted { $0.contextPath.localizedStandardCompare($1.contextPath) == .orderedAscending }+    }++    private func validSearchPath(_ path: String, from root: NSEntityDescription) -> Bool {+        let keys = path.split(separator: ".").map(String.init)+        var entity = root+        for key in keys.dropLast() {+            guard let destination = entity.relationshipsByName[key]?.destinationEntity else { return false }+            entity = destination+        }+        return keys.last.map { entity.attributesByName[$0]?.attributeType == .stringAttributeType } ?? false+    }+}
Halo Family/Halo Family/Persistence/PortableGraph.swift Added
diff --git a/Halo Family/Halo Family/Persistence/PortableGraph.swift b/Halo Family/Halo Family/Persistence/PortableGraph.swiftnew file mode 100644index 0000000..d10d2b1--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PortableGraph.swift	@@ -0,0 +1,106 @@+import CoreData+import Foundation++nonisolated enum PortableValue: Codable, Equatable, Sendable {+    case text(String)+    case number(Int64)+    case decimal(Double)+    case flag(Bool)+    case date(Date)+    case uuid(UUID)+    case binary(String)+}++nonisolated struct PortableRecord: Codable, Equatable, Sendable {+    let id: UUID+    let entity: String+    var attributes: [String: PortableValue]+    var relationships: [String: [UUID]]+}++nonisolated struct FamilyBackup: Codable, Sendable {+    let formatVersion: Int+    let modelVersion: Int+    let familyID: UUID+    let createdAt: Date+    let records: [PortableRecord]+}++/// Canonical UUID references are independent of local Core Data object-ID URI/store paths.+nonisolated enum PortableGraph {+    static func record(_ object: NSManagedObject, binary: (String, Data) throws -> String) throws -> PortableRecord {+        guard let id = object.value(forKey: "id") as? UUID, let entity = object.entity.name else { throw BackupError.missingIdentity }+        var values: [String: PortableValue] = [:]+        for (name, attribute) in object.entity.attributesByName {+            guard let value = object.value(forKey: name) else { continue }+            switch attribute.attributeType {+            case .stringAttributeType: values[name] = .text(try cast(value))+            case .booleanAttributeType: values[name] = .flag((try cast(value) as NSNumber).boolValue)+            case .integer16AttributeType, .integer32AttributeType, .integer64AttributeType:+                values[name] = .number((try cast(value) as NSNumber).int64Value)+            case .doubleAttributeType, .floatAttributeType, .decimalAttributeType:+                values[name] = .decimal((try cast(value) as NSNumber).doubleValue)+            case .dateAttributeType: values[name] = .date(try cast(value))+            case .UUIDAttributeType: values[name] = .uuid(try cast(value))+            case .binaryDataAttributeType: values[name] = .binary(try binary(name, cast(value)))+            default: throw BackupError.unsupportedVersion+            }+        }+        var links: [String: [UUID]] = [:]+        for (name, relationship) in object.entity.relationshipsByName {+            let targets: [NSManagedObject]+            if relationship.isToMany { targets = Array((object.value(forKey: name) as? Set<NSManagedObject>) ?? []) } else {+                targets = (object.value(forKey: name) as? NSManagedObject).map { [$0] } ?? []+            }+            links[name] = try targets.map { target in+                guard let uuid = target.value(forKey: "id") as? UUID else { throw BackupError.missingIdentity }+                return uuid+            }.sorted { $0.uuidString < $1.uuidString }+        }+        return PortableRecord(id: id, entity: entity, attributes: values, relationships: links)+    }++    static func value(_ portable: PortableValue, binary: (String) throws -> Data) throws -> Any {+        switch portable {+        case .text(let value): value+        case .number(let value): NSNumber(value: value)+        case .decimal(let value): NSNumber(value: value)+        case .flag(let value): NSNumber(value: value)+        case .date(let value): value+        case .uuid(let value): value+        case .binary(let path): try binary(path)+        }+    }++    static func accepts(_ value: PortableValue, attribute: NSAttributeDescription) -> Bool {+        switch (value, attribute.attributeType) {+        case (.text, .stringAttributeType), (.flag, .booleanAttributeType),+             (.uuid, .UUIDAttributeType), (.binary, .binaryDataAttributeType): true+        case (.date(let date), .dateAttributeType): date.timeIntervalSinceReferenceDate.isFinite+        case (.number(let number), .integer16AttributeType): Int16(exactly: number) != nil+        case (.number(let number), .integer32AttributeType): Int32(exactly: number) != nil+        case (.number, .integer64AttributeType): true+        case (.decimal(let number), .doubleAttributeType), (.decimal(let number), .floatAttributeType),+             (.decimal(let number), .decimalAttributeType): number.isFinite+        default: false+        }+    }++    static func encode<T: Encodable>(_ value: T) throws -> Data {+        let encoder = JSONEncoder()+        encoder.outputFormatting = [.sortedKeys, .prettyPrinted]+        encoder.dateEncodingStrategy = .deferredToDate+        return try encoder.encode(value)+    }++    static func decode<T: Decodable>(_ type: T.Type, data: Data) throws -> T {+        let decoder = JSONDecoder()+        decoder.dateDecodingStrategy = .deferredToDate+        return try decoder.decode(type, from: data)+    }++    private static func cast<T>(_ value: Any) throws -> T {+        guard let value = value as? T else { throw BackupError.invalidArchive }+        return value+    }+}
Tests/HaloPersistenceTests/ContextCategoryTests.swift Added
diff --git a/Tests/HaloPersistenceTests/ContextCategoryTests.swift b/Tests/HaloPersistenceTests/ContextCategoryTests.swiftnew file mode 100644index 0000000..60f791f--- /dev/null+++ b/Tests/HaloPersistenceTests/ContextCategoryTests.swift@@ -0,0 +1,94 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct ContextCategoryTests {+    private func withStore(_ operation: (FamilyRepository, URL) throws -> Void) throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let stack = try PersistenceStack(directory: directory)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        try operation(FamilyRepository(stack: stack), directory)+    }++    @Test func newFamilyHasOrdinaryEditableScopedStarterCategories() throws {+        try withStore { graph, _ in+            let family = try graph.createFamily(name: "Synthetic family"), other = try graph.createFamily(name: "Other")+            let categories = try graph.contextCategories(in: family)+            #expect(Set(categories.map(\.name)) == Set(FamilyRepository.starterCategories))+            #expect(Set(categories.map(\.id)).isDisjoint(with: graph.contextCategories(in: other).map(\.id)))+            let school = try #require(categories.first { $0.name == "School" })+            try graph.updateCategory(school, name: "Learning", archived: false)+            #expect(try graph.contextCategories(in: family).first { $0.id == school.id }?.name == "Learning")+            #expect(try graph.contextCategories(in: other).contains { $0.name == "School" })+        }+    }++    @Test func archivingRetainsExistingLinkAndRejectsNewAssignment() throws {+        try withStore { graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let context = try graph.createContext(name: "Class", familyID: family)+            let category = try #require(try graph.contextCategories(in: family).first)+            try graph.setContextCategory(context, categoryID: category.id, expectedID: nil)+            try graph.updateCategory(category, name: category.name, archived: true)+            #expect(try graph.contextCategory(context) == category.id)+            let fresh = try graph.createContext(name: "New class", familyID: family)+            #expect(throws: MemoryError.self) { try graph.setContextCategory(fresh, categoryID: category.id, expectedID: nil) }+            #expect(try graph.contextCategory(fresh) == nil)+            try graph.setContextCategory(context, categoryID: nil, expectedID: category.id)+            #expect(try graph.contextCategory(context) == nil)+        }+    }++    @Test func staleCategoryAndContextEditsRetainNewerChoice() throws {+        try withStore { graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let context = try graph.createContext(name: "Class", familyID: family)+            let categories = try graph.contextCategories(in: family), first = try #require(categories.first)+            try graph.updateCategory(first, name: "Changed", archived: false)+            #expect(throws: MemoryError.self) { try graph.updateCategory(first, name: "Stale", archived: true) }+            try graph.setContextCategory(context, categoryID: first.id, expectedID: nil)+            #expect(throws: MemoryError.self) { try graph.setContextCategory(context, categoryID: nil, expectedID: nil) }+            #expect(try graph.contextCategory(context) == first.id)+        }+    }++    @Test func foreignCategoryAndBlankNameRejectWithoutWrites() throws {+        try withStore { graph, _ in+            let family = try graph.createFamily(name: "Synthetic family"), other = try graph.createFamily(name: "Other")+            let context = try graph.createContext(name: "Class", familyID: family)+            let foreign = try #require(try graph.contextCategories(in: other).first)+            #expect(throws: GraphError.self) { try graph.setContextCategory(context, categoryID: foreign.id, expectedID: nil) }+            #expect(throws: GraphError.self) { try graph.createCategory(name: " ", familyID: family) }+            #expect(try graph.contextCategory(context) == nil)+            #expect(try graph.contextCategories(in: family).count == 5)+        }+    }++    @Test func explicitStarterActionDoesNotReviveArchivedOrDuplicateExistingLabels() throws {+        try withStore { graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let category = try #require(try graph.contextCategories(in: family).first)+            try graph.updateCategory(category, name: category.name, archived: true)+            try graph.addStarterCategories(familyID: family); try graph.addStarterCategories(familyID: family)+            #expect(try graph.contextCategories(in: family).count == 5)+            #expect(try graph.contextCategories(in: family).first { $0.id == category.id }?.isArchived == true)+        }+    }++    @Test func existingMigratedFamilyReceivesNoImplicitCategoryWrites() throws {+        try withStore { _, directory in+            let oldDirectory = directory.appendingPathComponent("Old")+            do {+                let old = try PersistenceStack(directory: oldDirectory, model: PersistenceStack.loadModel(version: "HaloModelV4"))+                _ = try FamilyRepository(stack: old).createFamily(name: "Earlier synthetic family")+            }+            let current = try PersistenceStack(directory: oldDirectory), graph = FamilyRepository(stack: current)+            let family = try #require(try graph.families().first)+            #expect(try graph.contextCategories(in: family.id).isEmpty)+            try graph.addStarterCategories(familyID: family.id)+            #expect(try graph.contextCategories(in: family.id).count == 5)+        }+    }+}
Tests/HaloPersistenceTests/FamilyBackupTests.swift Added
diff --git a/Tests/HaloPersistenceTests/FamilyBackupTests.swift b/Tests/HaloPersistenceTests/FamilyBackupTests.swiftnew file mode 100644index 0000000..8f52527--- /dev/null+++ b/Tests/HaloPersistenceTests/FamilyBackupTests.swift@@ -0,0 +1,341 @@+import CoreData+import CoreGraphics+import ImageIO+import Testing+import UniformTypeIdentifiers+@testable import HaloPersistence++@MainActor+struct FamilyBackupTests {+    private func withStore(_ body: (PersistenceStack, FamilyRepository, URL) async throws -> Void) async throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let stack = try PersistenceStack(directory: directory)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        try await body(stack, FamilyRepository(stack: stack), directory)+    }++    @Test func portableRoundTripRetainsSparseGraphPayloadsAndStableIdentities() async throws {+        try await withStore { stack, graph, directory in+            let family = try graph.createFamily(name: "Synthetic source")+            let child = try graph.addChild(name: "Child", familyID: family)+            let connection = try graph.quickCapture(name: "Peer", childID: child)+            let context = try graph.createContext(name: "Class", familyID: family)+            _ = try graph.addMembership(connectionID: connection, contextID: context)+            let payload = Data([1, 3, 5, 7])+            let asset = try await AssetRepository(stack: stack).save(data: payload, familyID: family)+            let service = BackupRepository(stack: stack)+            let archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            #expect(preview.peopleCount == 2); #expect(preview.payloadBytes == 4)+            let originalFamily = try #require(try graph.readable(family, entity: "FamilySpace").value(forKey: "id") as? UUID)+            let target = try PersistenceStack(directory: directory.appendingPathComponent("Restore"))+            let restored = try await BackupRepository(stack: target).restore(preview, asNewCopy: false)+            let restoredGraph = FamilyRepository(stack: target)+            #expect(try restoredGraph.readable(restored, entity: "FamilySpace").value(forKey: "id") as? UUID == originalFamily)+            #expect(try restoredGraph.people(in: restored).map(\.name) == ["Child", "Peer"])+            let request = NSFetchRequest<NSManagedObject>(entityName: "Asset")+            let imported = try #require(try target.container.viewContext.fetch(request).first)+            #expect(imported.value(forKey: "id") as? UUID == graph.readable(asset, entity: "Asset").value(forKey: "id") as? UUID)+            #expect(try await AssetRepository(stack: target).data(for: imported.objectID) == payload)+            let reopened = try PersistenceStack(directory: directory.appendingPathComponent("Restore"))+            #expect(try FamilyRepository(stack: reopened).families().count == 1)+        }+    }++    @Test func existingIdentityStopsRestoreWithoutPartialRowsOrOverwrite() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            _ = try graph.addPerson(name: "Original", familyID: family)+            let service = BackupRepository(stack: stack)+            let archive = try await service.export(familyID: family, readable: false)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            await #expect(throws: BackupError.self) { try await service.restore(preview, asNewCopy: false) }+            #expect(try graph.families().count == 1); #expect(try graph.people(in: family).map(\.name) == ["Original"])+            let copy = try await service.restore(preview, asNewCopy: true)+            #expect(copy != family); #expect(try graph.families().map(\.name) == ["Synthetic family", "Synthetic family (copy)"])+            #expect(try graph.people(in: copy).map(\.name) == ["Original"])+        }+    }++    @Test func changedPreviewAndParallelImportGuardCannotCreateRows() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let service = BackupRepository(stack: stack)+            let archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            let handle = try FileHandle(forWritingTo: archive)+            try handle.seekToEnd(); try handle.write(contentsOf: Data([0])); try handle.close()+            await #expect(throws: BackupError.self) { try await service.restore(preview, asNewCopy: true) }+            stack.importingBackup = true+            await #expect(throws: BackupError.self) { try await service.restore(preview, asNewCopy: true) }+            stack.importingBackup = false+            #expect(try graph.families().count == 1)+        }+    }++    @Test func copiedMergeHistoryUsesNewNamespaceAndRestoreRetainsGuardedUndo() async throws {+        try await withStore { stack, graph, directory in+            let family = try graph.createFamily(name: "Synthetic family")+            let source = try graph.addPerson(name: "Source", familyID: family)+            let kept = try graph.addPerson(name: "Kept", familyID: family)+            let audit = try graph.mergePeople(graph.mergePreview(sourceID: source, survivorID: kept), choices: PersonMergeChoices())+            let service = BackupRepository(stack: stack)+            let archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            let originalIDs = Set(preview.backup.records.map(\.id))+            let copy = try await service.restore(preview, asNewCopy: true)+            let copiedObject = try graph.readable(copy, entity: "FamilySpace")+            let copiedRows = try MergeSnapshot.records(family: copiedObject, in: stack.container.viewContext)+            #expect(originalIDs.isDisjoint(with: copiedRows.map(\.id)))+            let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMerge")+            request.predicate = NSPredicate(format: "familySpace == %@", copy)+            let copiedAudit = try #require(try stack.container.viewContext.fetch(request).first)+            #expect(copiedAudit.value(forKey: "undoUnavailableAt") != nil)+            let history = try MergeSnapshot.decode(copiedAudit.value(forKey: "beforeData") as? Data)+            #expect(originalIDs.isDisjoint(with: history.map(\.id)))+            #expect(history.allSatisfy { $0.links["familySpace"] == [copiedObject.value(forKey: "id") as? UUID].compactMap { $0 } })+            #expect(try graph.mergeConflicts(in: copy).isEmpty)+            #expect(throws: MergeError.self) { try graph.undoPersonMerge(copiedAudit.objectID) }+            let restoredStack = try PersistenceStack(directory: directory.appendingPathComponent("Restore"))+            let restored = try await BackupRepository(stack: restoredStack).restore(preview, asNewCopy: false)+            request.predicate = NSPredicate(format: "familySpace == %@", restored)+            let restoredAudit = try #require(try restoredStack.container.viewContext.fetch(request).first)+            #expect(restoredAudit.value(forKey: "id") as? UUID == graph.readable(audit, entity: "PersonMerge").value(forKey: "id") as? UUID)+            try FamilyRepository(stack: restoredStack).undoPersonMerge(restoredAudit.objectID)+            #expect(try FamilyRepository(stack: restoredStack).people(in: restored).count == 2)+        }+    }++    @Test func exportExcludesDeviceContactMappingsAndOtherFamilies() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family"), other = try graph.createFamily(name: "Other family")+            let person = try graph.addPerson(name: "Included", familyID: family)+            _ = try graph.addPerson(name: "Excluded", familyID: other)+            let identity = try graph.contactIdentity(person)+            _ = try await stack.localContactLinks().link("synthetic-device-secret", familyID: identity.familyID,+                                                       personID: identity.personID)+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            #expect(preview.peopleCount == 1)+            let encoded = try #require(String(data: PortableGraph.encode(preview.backup), encoding: .utf8))+            #expect(!encoded.contains("Excluded")); #expect(!encoded.contains("synthetic-device-secret"))+        }+    }++    @Test func malformedGraphAndHistoryCannotReachImport() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let person = try graph.addPerson(name: "Synthetic person", familyID: family)+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            var records = preview.backup.records+            let index = try #require(records.firstIndex { $0.entity == "Person" })+            records[index].relationships["familySpace"] = [UUID()]+            let malformed = FamilyBackup(formatVersion: 1, modelVersion: 6, familyID: preview.backup.familyID,+                                         createdAt: Date(), records: records)+            #expect(throws: BackupError.self) { try BackupValidation.validate(malformed, model: stack.container.managedObjectModel) }+            let row = try MergeSnapshot.record(graph.readable(person, entity: "Person"))+            let invalid = MergeRecord(id: row.id, entity: row.entity, attributes: row.attributes,+                                      links: row.links.merging(["familySpace": [UUID()]]) { _, next in next })+            let historyRecord = PortableRecord(id: UUID(), entity: "MergeConnectionReview",+                                               attributes: ["reviewedData": .binary("synthetic")], relationships: [:])+            let history = FamilyBackup(formatVersion: 1, modelVersion: 6, familyID: preview.backup.familyID, createdAt: Date(),+                                       records: preview.backup.records + [historyRecord])+            #expect(throws: BackupError.self) {+                try BackupHistory(backup: history, model: stack.container.managedObjectModel) { _ in try MergeSnapshot.encode([invalid]) }+            }+        }+    }++    @Test func zipRejectsTraversalTruncationExtraMembersAndCorruptPayload() async throws {+        try await withStore { stack, graph, directory in+            let source = directory.appendingPathComponent("Synthetic.txt")+            try Data("hello".utf8).write(to: source)+            #expect(throws: BackupError.self) {+                try BackupArchive.write([BackupFile(name: "../outside", url: source)], to: directory.appendingPathComponent("bad.zip"))+            }+            let zip = directory.appendingPathComponent("valid.zip")+            try BackupArchive.write([BackupFile(name: "Synthetic.txt", url: source)], to: zip)+            let member = try #require(try BackupArchive.members(in: zip).first)+            let handle = try FileHandle(forWritingTo: zip)+            try handle.seek(toOffset: 30 + UInt64(member.name.utf8.count)); try handle.write(contentsOf: Data([255])); try handle.close()+            #expect(throws: BackupError.self) { try BackupArchive.read(member, from: zip, limit: 100) }+            try Data([1, 2, 3]).write(to: zip)+            #expect(throws: BackupError.self) { try BackupArchive.members(in: zip) }+            let family = try graph.createFamily(name: "Synthetic family")+            let service = BackupRepository(stack: stack)+            let archive = try await service.export(familyID: family, readable: false)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let manifest = try #require(try BackupArchive.members(in: archive).first)+            let json = directory.appendingPathComponent("family.json")+            try BackupArchive.read(manifest, from: archive, limit: 32_000_000).write(to: json)+            let extra = directory.appendingPathComponent("extra.zip")+            let files = [BackupFile(name: "family.json", url: json), BackupFile(name: "unexpected.txt", url: source)]+            try BackupArchive.write(files, to: extra)+            await #expect(throws: BackupError.self) { try await service.preview(extra) }+        }+    }++    @Test func widgetAndIntentCannotExportOrRestoreFamily() async throws {+        try await withStore { stack, graph, directory in+            let family = try graph.createFamily(name: "Synthetic family")+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            for role in [PersistenceRole.widget, .appIntent] {+                let other = try PersistenceStack(directory: directory, role: role)+                let restricted = BackupRepository(stack: other)+                await #expect(throws: GraphError.self) { try await restricted.export(familyID: family) }+                await #expect(throws: GraphError.self) { try await restricted.restore(preview, asNewCopy: true) }+            }+        }+    }++    @Test func photoOwnershipEnforcesPayloadPresenceAndSizeDespiteSpoofedKind() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let person = try graph.addPerson(name: "Synthetic person", familyID: family)+            let assetID = try await AssetRepository(stack: stack).save(data: Data([1]), familyID: family)+            let object = try graph.readable(person, entity: "Person")+            object.setValue(try graph.readable(assetID, entity: "Asset"), forKey: "primaryPhoto")+            try stack.container.viewContext.save()+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            var records = preview.backup.records+            let index = try #require(records.firstIndex { $0.entity == "Asset" })+            records[index].attributes["kind"] = .text("generic")+            #expect(throws: BackupError.self) {+                try BackupValidation.payload(Data(repeating: 1, count: ImageImport.photoLimit + 1), key: "data", record: records[index])+            }+            records[index].attributes["data"] = nil+            let malformed = FamilyBackup(formatVersion: 1, modelVersion: 6, familyID: preview.backup.familyID,+                                         createdAt: Date(), records: records)+            #expect(throws: BackupError.self) { try BackupValidation.validate(malformed, model: stack.container.managedObjectModel) }+        }+    }++    @Test func copiedArchivedAccountsDoNotAppearAsNewLateImports() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let child = try graph.addChild(name: "Child", familyID: family)+            let source = try graph.addPerson(name: "Source", familyID: family), kept = try graph.addPerson(name: "Kept", familyID: family)+            let first = try graph.connect(personID: source, childID: child)+            _ = try graph.connect(personID: kept, childID: child)+            for index in 0..<8 {+                let context = try graph.createContext(name: "Context \(index)", familyID: family)+                _ = try graph.addMembership(connectionID: first, contextID: context)+            }+            let merge = try graph.mergePreview(sourceID: source, survivorID: kept)+            let overlap = try #require(merge.overlaps.first)+            var choice = PersonMergeChoices()+            choice.connections[overlap.id] = MergeConnectionChoices(originID: overlap.origins.first?.id,+                closenessID: overlap.closeness.first?.id, statusID: overlap.statuses.first?.id)+            _ = try graph.mergePeople(merge, choices: choice)+            #expect(try graph.lateMergeAccounts(in: family).isEmpty)+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            let copy = try await service.restore(preview, asNewCopy: true)+            #expect(try graph.lateMergeAccounts(in: copy).isEmpty)+        }+    }++    @Test func completeSharedMemoryRestoresIntoPrivateStorageWithoutLosingAccounts() async throws {+        try await withStore { stack, graph, directory in+            let records = try await sharedMemory(stack: stack, graph: graph)+            let family = try #require(records["family"])+            let before = try MergeSnapshot.records(family: graph.readable(family, entity: "FamilySpace"), in: stack.container.viewContext)+            let assets = AssetRepository(stack: stack)+            let photoBytes = try await assets.data(for: #require(records["photo"]))+            let pdfBytes = try await assets.data(for: #require(records["pdf"]))+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            let target = try PersistenceStack(directory: directory.appendingPathComponent("Restored memory"))+            let restored = try await BackupRepository(stack: target).restore(preview, asNewCopy: false)+            #expect(restored.persistentStore == target.privateStore)+            let imported = FamilyRepository(stack: target)+            #expect(try MergeSnapshot.records(family: imported.readable(restored, entity: "FamilySpace"),+                                             in: target.container.viewContext) == before)+            let people = try imported.people(in: restored)+            let peer = try #require(people.first { $0.name == "Peer" })+            #expect(try imported.sensitiveDetails(peer.id).date == PartialDate(year: 2024, month: 2))+            #expect(try imported.addressLabels(for: peer.id).first?.label == "Family nickname")+            let connection = try #require(try imported.connections(to: peer.id).first)+            #expect(try imported.originHistory(for: connection.id).count == 2)+            #expect(try imported.origin(for: connection.id)?.narrative == "Met at the party")+            let event = try #require(try imported.events(in: restored).first)+            #expect(try imported.participants(event.id).first?.attendance == .attended)+            #expect(try imported.participants(event.id).first?.invitation == .unknown)+            #expect(try imported.gifts(event.id).first?.description == "Book")+            #expect(try imported.gifts(event.id).first?.recipients == ["Peer"])+            let context = try #require(try imported.contexts(in: restored).first)+            #expect(try imported.contextPeople(context.id).first?.role == "Coach")+            let restoredAssets = AssetRepository(stack: target)+            #expect(try await restoredAssets.data(for: #require(imported.primaryPhoto(peer.id))) == photoBytes)+            let attachment = try #require(try imported.attachments(event.id).first)+            #expect(try await restoredAssets.data(for: attachment.assetID) == pdfBytes)+        }+    }++    private func sharedMemory(stack: PersistenceStack, graph: FamilyRepository) async throws -> [String: NSManagedObjectID] {+        let context = stack.container.viewContext+        let family = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+        context.assign(family, to: stack.sharedStore)+        family.setValue(UUID(), forKey: "id"); family.setValue("Synthetic shared memory", forKey: "name")+        try context.save()+        let familyID = family.objectID+        let child = try graph.addChild(name: "Child", familyID: familyID)+        let peer = try graph.addPerson(name: "Peer", familyID: familyID), coach = try graph.addPerson(name: "Coach", familyID: familyID)+        let connection = try graph.connect(personID: peer, childID: child)+        let source = try graph.createContext(name: "Class", familyID: familyID)+        _ = try graph.addMembership(connectionID: connection, contextID: source)+        _ = try graph.associatePerson(coach, contextID: source, role: "Coach")+        let event = try graph.createEvent(title: "Party", date: Date(timeIntervalSince1970: 1000), familyID: familyID)+        try graph.saveOrigin(connectionID: connection, input: OriginInput(contextID: source, narrative: "First account"),+                             expectedOrigin: nil)+        try graph.saveOrigin(connectionID: connection, input: OriginInput(eventID: event, narrative: "Met at the party"),+                             expectedOrigin: graph.origin(for: connection))+        try graph.setSensitiveDetails(peer, deceased: true, date: PartialDate(year: 2024, month: 2), expected: graph.sensitiveDetails(peer))+        try graph.addFamilyFact(sourceID: coach, targetID: peer, kind: .parentOf)+        try graph.addFamilyFact(sourceID: coach, targetID: peer, kind: nil, label: "Entered title")+        try graph.addAddressLabel(targetID: peer, label: "Family nickname")+        let group = try graph.createGroup(name: "Household", familyID: familyID)+        try graph.addGroupMember(peer, groupID: group, role: "Member")+        try graph.saveParticipant(eventID: event, personID: peer, roles: ["Guest"], invitation: .unknown, attendance: .attended)+        let assets = AssetRepository(stack: stack)+        let photo = try await assets.importPhoto(Self.imageData(), filename: "Synthetic.png", personID: peer)+        let pdf = try await assets.importAttachment(Self.pdfData(), filename: "Synthetic invitation.pdf", eventID: event)+        let attachment = try #require(try graph.attachments(event).first)+        try graph.addGift(eventID: event, input: GiftInput(description: "Book", givers: [coach], groups: [group],+                                                         recipients: [peer], attachments: [attachment.id], note: "Synthetic note"))+        return ["family": familyID, "photo": photo, "pdf": pdf]+    }++    private static func imageData() throws -> Data {+        let bitmap = try #require(CGContext(data: nil, width: 8, height: 8, bitsPerComponent: 8, bytesPerRow: 32,+                                           space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))+        bitmap.setFillColor(CGColor(gray: 0.5, alpha: 1)); bitmap.fill(CGRect(x: 0, y: 0, width: 8, height: 8))+        let image = try #require(bitmap.makeImage()), data = NSMutableData()+        let output = try #require(CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil))+        CGImageDestinationAddImage(output, image, nil)+        #expect(CGImageDestinationFinalize(output))+        return data as Data+    }++    private static func pdfData() throws -> Data {+        let data = NSMutableData(), consumer = try #require(CGDataConsumer(data: data))+        var page = CGRect(x: 0, y: 0, width: 100, height: 100)+        let pdf = try #require(CGContext(consumer: consumer, mediaBox: &page, nil))+        pdf.beginPDFPage(nil); pdf.setFillColor(CGColor(gray: 0.5, alpha: 1)); pdf.fill(page); pdf.endPDFPage(); pdf.closePDF()+        return data as Data+    }+}
Tests/HaloPersistenceTests/PeopleSearchTests.swift Added
diff --git a/Tests/HaloPersistenceTests/PeopleSearchTests.swift b/Tests/HaloPersistenceTests/PeopleSearchTests.swiftnew file mode 100644index 0000000..e1fd62a--- /dev/null+++ b/Tests/HaloPersistenceTests/PeopleSearchTests.swift@@ -0,0 +1,90 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct PeopleSearchTests {+    private func withStore(_ operation: (FamilyRepository) throws -> Void) throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let stack = try PersistenceStack(directory: directory)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        try operation(FamilyRepository(stack: stack))+    }++    @Test func namesEnteredTitlesAndHouseholdsMatchWithoutCrossFamilyResults() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic family"), other = try graph.createFamily(name: "Other")+            let person = try graph.addPerson(name: "Sofía", familyID: family)+            _ = try graph.addPerson(name: "Sofía", familyID: other)+            let child = try graph.addPerson(name: "Child", familyID: family)+            try graph.addAddressLabel(targetID: person, label: "姨姨")+            try graph.addFamilyFact(sourceID: person, targetID: child, kind: nil, label: "Auntie May")+            let group = try graph.createGroup(name: "River household", familyID: family)+            try graph.addGroupMember(person, groupID: group)+            _ = try graph.write { context in+                let object = try graph.record(person, entity: "Person", in: context)+                object.setValue("Chen", forKey: "familyName")+                return object+            }+            for term in ["sofi", "姨", "Auntie", "River", "chen"] {+                #expect(try graph.people(in: family, search: term).map(\.id) == [person])+            }+        }+    }++    @Test func nestedContextsFindPeersAndRolesWithHistoricalMembershipRetained() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic family")+            let child = try graph.addChild(name: "Child", familyID: family)+            let connection = try graph.quickCapture(name: "Peer", childID: child)+            let peer = try graph.personID(for: connection), adult = try graph.addPerson(name: "Adult", familyID: family)+            let school = try graph.createContext(name: "River school", familyID: family)+            let classroom = try graph.createContext(name: "Prep A", familyID: family, parentID: school)+            let membership = try graph.addMembership(connectionID: connection, contextID: classroom)+            _ = try graph.associatePerson(adult, contextID: classroom, role: "Teacher")+            for term in ["Prep", "River school"] {+                #expect(try Set(graph.people(in: family, search: term).map(\.id)) == [peer, adult])+            }+            #expect(try graph.people(in: family, search: "teacher").map(\.id) == [adult])+            try graph.endMembership(membership, at: Date())+            try graph.archiveContext(classroom, archived: true)+            #expect(try Set(graph.people(in: family, search: "Prep").map(\.id)) == [peer, adult])+        }+    }++    @Test func relatedNamesSearchRetainsDeceasedExplicitlyAndExcludesRoutineSuggestions() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic family")+            let parent = try graph.addPerson(name: "Adult", familyID: family), child = try graph.addPerson(name: "Noah", familyID: family)+            try graph.addFamilyFact(sourceID: parent, targetID: child, kind: .parentOf)+            #expect(try Set(graph.people(in: family, search: "Noah").map(\.id)) == [parent, child])+            #expect(try graph.people(in: family, search: "parentOf").map(\.id) == [parent])+            #expect(try graph.people(in: family, search: "Parent of").map(\.id) == [parent])+            try graph.setSensitiveDetails(parent, deceased: true, date: PartialDate(year: 2024), expected: graph.sensitiveDetails(parent))+            #expect(try graph.people(in: family, search: "Parent").contains { $0.id == parent })+            #expect(try graph.people(in: family, search: "Parent", includeDeceased: false).contains { $0.id == parent } == false)+        }+    }++    @Test func personRolesShowMultipleDatedAndArchivedAssociationsWithStaleEditGuard() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic family")+            let person = try graph.addPerson(name: "Adult", familyID: family)+            let context = try graph.createContext(name: "Swimming", familyID: family)+            _ = try graph.associatePerson(person, contextID: context, role: "Coach", startedAt: Date(timeIntervalSince1970: 1000))+            _ = try graph.associatePerson(person, contextID: context, role: "Parent")+            let roles = try graph.personContextRoles(person)+            #expect(Set(roles.map { $0.association.role }) == ["Coach", "Parent"])+            let original = try #require(roles.first { $0.association.role == "Coach" }?.association)+            try graph.archiveContext(context, archived: true)+            #expect(try graph.personContextRoles(person).allSatisfy(\.isArchived))+            try graph.updateRole(original.id, role: "Head coach", startedAt: original.startedAt,+                                          endedAt: nil, expected: original)+            #expect(throws: GraphError.self) {+                try graph.updateRole(original.id, role: "Stale", startedAt: nil, endedAt: nil, expected: original)+            }+            #expect(try graph.personContextRoles(person).contains { $0.association.role == "Head coach" })+        }+    }+}

Docs (5)

CHANGELOG.md Modified
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d3c81de..fd29831 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,16 @@  ### Added +- Versioned family JSON/payload ZIP backup, optional readable summary and native+  preview with atomic absent-family or explicit fresh-identity copy import.+- Guarded historical identity remapping, retained merge accounts, ownership-derived+  asset limits, bounded ZIP validation and cancellation cleanup of owned staging.+- Editable Context categories with scoped starters, retained archived links and stale+  edit checks; richer People search and Person-level dated Context role visibility.+- Eleven backup, six category and four search synthetic cases. With Contacts the+  current source batch declares 106 cases/14 suites, pending its scheduled runtime gate.++ - Optional native Apple Contacts link/create controls and device-only linked-state/   unlink UI; bounded host-only mappings retain both contacts through Person merge. - Six synthetic local contact-link cases; this source checkpoint has 85 declared
README.md Modified
diff --git a/README.md b/README.mdindex 2e81cd0..d68ee51 100644--- a/README.md+++ b/README.md@@ -169,3 +169,25 @@ installing either replaces the other on that device.  SwiftLint follows the Prism project's rules. After `make lint-fix`, review the changes before building, particularly changes inside SwiftUI result builders.++## Backup, categories and richer search++Open **Family spaces → Backup and import** to create a versioned ZIP of the selected+family or preview a backup. Export includes all shared notes, Sensitive Details and+app-owned assets. Keep the file somewhere appropriate for that content. Device-local+Apple Contacts identifiers are excluded. A restored family starts in your Private+store and is not shared automatically.++Choose a new copy (fresh identities, retained history with old merge undo disabled)+or restore original identities only when none exist in the local stores. Existing+families are never overwritten. Only Halo's stored ZIP format is accepted; archive,+manifest, record and payload limits are listed in the current evidence document.+The whole-account absence of records on another device is not established locally.++Manage editable labels under **Contexts → Manage categories**, then choose a label+in a Context's detail. New families receive School, Playgroup, Parent group, Childcare+and Activities. Older families can add missing starters explicitly. Archived labels+remain attached to existing Contexts. People search covers names, entered titles,+roles, households, related names and nested Context paths. Person details also show+multiple dated Context roles. The current 106-case source batch awaits its runtime+gate; the last verified checkpoint remains 79 cases and both Debug builds.
docs/halo_family_design_pack/04-build-plan.md Modified
diff --git a/docs/halo_family_design_pack/04-build-plan.md b/docs/halo_family_design_pack/04-build-plan.mdindex 77a2ca2..2d1c1bf 100644--- a/docs/halo_family_design_pack/04-build-plan.md+++ b/docs/halo_family_design_pack/04-build-plan.md@@ -2,6 +2,42 @@  **Status:** Full application implementation in progress; release gates remain separate +### Backup, categories and search source checkpoint — 2026-10-07 UTC++The source on verified V6 now adds versioned JSON plus payload ZIP export, an+optional Markdown summary, native preview/import and an atomic Private-store+restore. Existing identities in either local store reject original-identity+restore; an explicit copy receives a fresh identity namespace, including historical+merge references. Competing accounts remain retained. Historical merge undo is+disabled in copied families; absent-family restore retains its existing guards.+Apple Contacts mappings are excluded. Native selection/export requires only the+user-selected document; no real family export or Contacts operation ran here.++Context categories are ordinary editable labels: five starters in newly created+families, explicit starter addition for older families, stale-edit checks and archive+without dropping Context links. People search now includes structured names,+entered family/address titles, roles, groups, related names and nested Context paths.+Person details display every Context role and optional date, including history.+Search does not infer gender or culturally specific titles.++This source batch declares **106 tests/14 suites**: six Contacts, eleven backup,+six category and four search cases above the verified 79. Strict lint passes+**0/74 files**; compilation/tests/native runtime are pending the shared-Mac slot.+Fixture-only role references use the actual `.appIntent` enum case; the earlier+Contacts draft's `.intent` spelling was not compiled. Four independent source+reviews identified ownership-derived photo limits, indexed inverse validation,+streamed history validation, copied UUID ordering and cancellation/staging cleanup;+those corrections are implemented. All four final source reviews are clear.++Backup limits are explicit: stored ZIP32 only, 1 GB/10,000 members, 32 MB manifest,+100,000 current records, 16 MB per merge snapshot, and aggregate preview/restore+payloads of 128 MB on iOS / 512 MB on macOS. Photo/Event payload limits follow+actual ownership (4 MB/20 MB), independently of mutable kind metadata. Absence+checks cover these local stores, not unseen records on another CloudKit device.+No native UI, live CloudKit, no-account/account-change/share-removal or production+schema evidence is claimed. Extensions and lifecycle work remain active; graph+visualisation still has its real-data prerequisite, and class rollover remains v2.+ ### Contacts source checkpoint — 2026-10-07 UTC  Phase 7 source integrated onto verified V6 implements optional native Contact
docs/halo_family_design_pack/10-initial-implementation-results.md Modified
diff --git a/docs/halo_family_design_pack/10-initial-implementation-results.md b/docs/halo_family_design_pack/10-initial-implementation-results.mdindex 378f07f..c830607 100644--- a/docs/halo_family_design_pack/10-initial-implementation-results.md+++ b/docs/halo_family_design_pack/10-initial-implementation-results.md@@ -1,5 +1,41 @@ # Implementation evidence +## Backup, categories and search source checkpoint — 2026-10-07 UTC++The source on verified V6 now adds versioned JSON plus payload ZIP export, an+optional Markdown summary, native preview/import and an atomic Private-store+restore. Existing identities in either local store reject original-identity+restore; an explicit copy receives a fresh identity namespace, including historical+merge references. Competing accounts remain retained. Historical merge undo is+disabled in copied families; absent-family restore retains its existing guards.+Apple Contacts mappings are excluded. Native selection/export requires only the+user-selected document; no real family export or Contacts operation ran here.++Context categories are ordinary editable labels: five starters in newly created+families, explicit starter addition for older families, stale-edit checks and archive+without dropping Context links. People search now includes structured names,+entered family/address titles, roles, groups, related names and nested Context paths.+Person details display every Context role and optional date, including history.+Search does not infer gender or culturally specific titles.++This source batch declares **106 tests/14 suites**: six Contacts, eleven backup,+six category and four search cases above the verified 79. Strict lint passes+**0/74 files**; compilation/tests/native runtime are pending the shared-Mac slot.+Fixture-only role references use the actual `.appIntent` enum case; the earlier+Contacts draft's `.intent` spelling was not compiled. Four independent source+reviews identified ownership-derived photo limits, indexed inverse validation,+streamed history validation, copied UUID ordering and cancellation/staging cleanup;+those corrections are implemented. All four final source reviews are clear.++Backup limits are explicit: stored ZIP32 only, 1 GB/10,000 members, 32 MB manifest,+100,000 current records, 16 MB per merge snapshot, and aggregate preview/restore+payloads of 128 MB on iOS / 512 MB on macOS. Photo/Event payload limits follow+actual ownership (4 MB/20 MB), independently of mutable kind metadata. Absence+checks cover these local stores, not unseen records on another CloudKit device.+No native UI, live CloudKit, no-account/account-change/share-removal or production+schema evidence is claimed. Extensions and lifecycle work remain active; graph+visualisation still has its real-data prerequisite, and class rollover remains v2.+ ## Contacts source checkpoint — 2026-10-07 UTC  Optional native Contacts selection/create routes and linked-state/unlink UI are
docs/halo_family_design_pack/CHANGELOG.md Modified
diff --git a/docs/halo_family_design_pack/CHANGELOG.md b/docs/halo_family_design_pack/CHANGELOG.mdindex 1799f1a..3430fbb 100644--- a/docs/halo_family_design_pack/CHANGELOG.md+++ b/docs/halo_family_design_pack/CHANGELOG.md@@ -40,3 +40,6 @@ Source: the user-supplied `kids_relationship_app_design_current.zip` dated 22 Se - Preserved unresolved product/schema choices; clarified attachment association ambiguity and temporal concurrency as decision gates.  Documentation consistency and ZIP integrity were checked. No application build, automated application test or device validation was run for this documentation revision. Historical spike results retain their original scope; no-iCloud-account validation remains deferred.++- 2026-10-07: Record backup/import, editable categories, richer search and Person role+  source with exact pending verification inventory. Preserve V6 verified evidence.