Retained merge accounts, guarded undo and visible recovery. Local synthetic gate verified; full application continues.
Local V6 source verified
The 79-case synthetic suite and sequential make check pass. Four final read-only reviews are clear. Native UI and actual CloudKit transport are unrun; Contacts is isolated outside this gate and remaining application work continues.
Pass rate: 100% (79 of 79)
New tests: 65
Diff coverage: 96% (3752 of 3922 added lines)
Two similar names can be separate people. Merge only after reviewing the details. Earlier accounts remain visible in history. Undo restores the earlier references while affected records still match.
A merge redirects references in one local transaction, retains source records and saves affected metadata snapshots. Overlapping relationships require explicit origin/status/closeness choices. Late imported accounts are transferred as alternatives only when their metadata was not already reviewed.
UUID-indexed metadata skips binary payload reads. Affected-row equality guards undo, and source snapshots guard late-account review. Audit graph components, cycles and causal recovery UUIDs expose opposing or delayed aliases. These local checks do not establish a CloudKit CAS or global transaction.
Completeness: Phase6 domain and platform compilation verified; native runtime/transport unrun. Contacts source is separate; backup/extensions/lifecycle remain.
Halo Family/Halo Family/Persistence/PersonMergeRepository.swift
Why it matters. Preserve stable identities and competing accounts.
What to look at. Preview snapshots, mandatory overlap choices, archived originals and affected metadata audits.
Halo Family/Halo Family/Persistence/PersonMergeHistory.swift
Why it matters. Avoid replaying earlier references over newer edits.
What to look at. Compare affected after rows, restore original metadata, retain audit evidence.
Halo Family/Halo Family/Persistence/MergeAccountReview.swift
Why it matters. Imported accounts must remain visible after source archival.
What to look at. Ordered account indexes, only unseen/changed alternatives, same-context repeat/stale guards.
Halo Family/Halo Family/Persistence/MergeConflictRecovery.swift
Why it matters. Prevent hidden identities from alias cycles and delayed recovery replay.
What to look at. Audit components, unsupported aliases, retained recovery history and causal recovery acknowledgements.
Decision2 and Q5 retain original accounts and stable IDs; transfer new competing values as alternatives.
Q6 exposes separate identities and keeps current references. It is distinct from affected-record undo. New explicit merges acknowledge observed recovery UUIDs.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| P2 | Stale archived record writes | Stale archived record writes | Corrected in source; focused synthetic regression or bounded indexing covers the behavior. Final reviewer recheck clear. |
| P2 | Self child Connections | Self child Connections | Corrected in source; focused synthetic regression or bounded indexing covers the behavior. Final reviewer recheck clear. |
| P2 | Hidden late accounts | Hidden late accounts | Corrected in source; focused synthetic regression or bounded indexing covers the behavior. Final reviewer recheck clear. |
| P2 | Opposing/replayed aliases | Opposing/replayed aliases | Corrected in source; focused synthetic regression or bounded indexing covers the behavior. Final reviewer recheck clear. |
| P2 | Repeated or unrelated late copies | Repeated or unrelated late copies | Corrected in source; focused synthetic regression or bounded indexing covers the behavior. Final reviewer recheck clear. |
| P2 | Synthetic absence treated as origin clear | Synthetic absence treated as origin clear | Corrected in source; focused synthetic regression or bounded indexing covers the behavior. Final reviewer recheck clear. |
| P2 | Repeated account snapshot scans | Repeated account snapshot scans | Corrected in source; focused synthetic regression or bounded indexing covers the behavior. Final reviewer recheck clear. |
Source: local run at 2026-10-07T02:49:39.983713+00:00 · snapshot 00abc8260cb24742aaca7910e9ada4a205fae3bf (dirty working tree)
Baseline: none
Execution: passed · JUnit: 1 file · Coverage: 1 file · Baseline: absent
Coverage scope: as the project configures it
Totals: 79 passed · 0 failed · 0 skipped · 0 errored · 0 flaky
Derived by declaration name, from the diff (no baseline run).
Aggregate diff coverage: 96% (3752 of 3922 measurable added lines).
Head 94.1% (4383 of 4658 lines)
28 of 70 changed files matched coverage data.
CHANGELOG.md — no candidateHalo Family/Halo Family/ChildOverviewView.swift — no candidateHalo Family/Halo Family/ConnectionDetailView.swift — no candidateHalo Family/Halo Family/ConnectionStateEditor.swift — no candidateHalo Family/Halo Family/ContentView.swift — no candidateHalo Family/Halo Family/ContextRoleEditor.swift — no candidateHalo Family/Halo Family/ContextsView.swift — no candidateHalo Family/Halo Family/EventDetailView.swift — no candidateHalo Family/Halo Family/EventsView.swift — no candidateHalo Family/Halo Family/FamilyKnowledgeViews.swift — no candidateHalo Family/Halo Family/FamilyManagerView.swift — no candidateHalo Family/Halo Family/FamilyReviewView.swift — no candidateHalo Family/Halo Family/FamilySharingView.swift — no candidateHalo Family/Halo Family/FamilyWorkspaceView.swift — no candidateHalo Family/Halo Family/FormComponents.swift — no candidateHalo Family/Halo Family/MergeConflictReviewView.swift — no candidateHalo Family/Halo Family/MyApp.swift — no candidateHalo Family/Halo Family/PeopleView.swift — no candidateHalo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversion — no candidateHalo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contents — no candidateHalo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contents — no candidateHalo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contents — no candidateHalo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV6.xcdatamodel/contents — no candidateHalo Family/Halo Family/PersonMergeHistoryView.swift — no candidateHalo Family/Halo Family/PersonMergeView.swift — no candidateHalo Family/Halo Family/PhotoAssetViews.swift — no candidateHalo Family/Halo Family/ShareInvitations.swift — no candidateHalo Family/Halo Family/TemporalConflictReview.swift — no candidateHalo Family/Halo-Family-Info.plist — no candidateMakefile — no candidateREADME.md — no candidatedocs/halo_family_design_pack/00-design-document.md — no candidatedocs/halo_family_design_pack/01-data-model.md — no candidatedocs/halo_family_design_pack/02-technical-architecture.md — no candidatedocs/halo_family_design_pack/03-open-questions.md — no candidatedocs/halo_family_design_pack/04-build-plan.md — no candidatedocs/halo_family_design_pack/06-attachment-photo-storage.md — no candidatedocs/halo_family_design_pack/09-implementation-handoff.md — no candidatedocs/halo_family_design_pack/10-initial-implementation-results.md — no candidatedocs/halo_family_design_pack/CHANGELOG.md — no candidatedocs/halo_family_design_pack/README.md — no candidatedocs/halo_family_design_pack/decision_log.md — no candidateFiles 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 8c5262f.
70 files: 57 code · 13 docs. Click to expand.
diff --git a/Halo Family/Halo Family/ChildOverviewView.swift b/Halo Family/Halo Family/ChildOverviewView.swiftnew file mode 100644index 0000000..39f509d--- /dev/null+++ b/Halo Family/Halo Family/ChildOverviewView.swift @@ -0,0 +1,149 @@+import Combine+import CoreData+import SwiftUI++struct ChildOverviewView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ @State private var children: [GraphRow] = []+ @State private var childID: NSManagedObjectID?+ @State private var connections: [GraphRow] = []+ @State private var states: [NSManagedObjectID: ConnectionStateSnapshot] = [:]+ @State private var showLostContact = false+ @State private var addingChild = false+ @State private var capturing = false+ @State private var failure: String?++ private var visibleConnections: [GraphRow] {+ connections.filter { showLostContact || states[$0.id]?.state != .lostContact || states[$0.id]?.statusNeedsReview == true }+ .sorted {+ let left = states[$0.id]?.closenessValue ?? 0+ let right = states[$1.id]?.closenessValue ?? 0+ return left == right ? $0.name.localizedStandardCompare($1.name) == .orderedAscending : left > right+ }+ }++ var body: some View {+ List {+ Section {+ Picker("Child", selection: $childID) {+ Text("Choose a child").tag(nil as NSManagedObjectID?)+ ForEach(children) { Text($0.name).tag(Optional($0.id)) }+ }+ .accessibilityIdentifier("children.selection")+ Button("Add a child", systemImage: "plus") { addingChild = true }+ }+ if childID != nil {+ Section {+ Button("Remember someone", systemImage: "person.badge.plus") { capturing = true }+ .accessibilityIdentifier("children.capture")+ Toggle("Include lost contact and historical people", isOn: $showLostContact)+ }+ Section("People they know") {+ ForEach(visibleConnections) { connection in+ NavigationLink {+ ConnectionDetailView(repository: repository, familyID: familyID, connection: connection)+ } label: {+ VStack(alignment: .leading, spacing: 4) {+ Text(connection.name)+ if let state = states[connection.id] {+ if state.statusNeedsReview || state.closenessNeedsReview {+ Label("Relationship needs review", systemImage: "exclamationmark.bubble")+ .font(.caption).foregroundStyle(.secondary)+ } else {+ if let choice = state.closeness { Text(choice.label).font(.caption).foregroundStyle(.secondary) }+ if state.state == .lostContact { Text("Lost contact").font(.caption).foregroundStyle(.secondary) }+ }+ }+ }+ }+ }+ if visibleConnections.isEmpty {+ Text("A name or description is enough to start. You can add the details later.").foregroundStyle(.secondary)+ }+ }+ }+ }+ .navigationTitle(children.first(where: { $0.id == childID })?.name ?? "Children")+ .task { reload() }+ .onChange(of: childID) { reload() }+ .onChange(of: showLostContact) { reload() }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in reload() }+ .sheet(isPresented: $addingChild, onDismiss: reload) {+ NameEntrySheet(title: "Add a child", field: "Child’s name", actionTitle: "Add child") { name in+ childID = try repository.addChild(name: name, familyID: familyID)+ }+ }+ .sheet(isPresented: $capturing, onDismiss: reload) {+ if let childID {+ NameEntrySheet(title: "Remember someone", field: "Name or description", actionTitle: "Save person") { name in+ _ = try repository.quickCapture(name: name, childID: childID)+ }+ }+ }+ .graphFailure($failure)+ }++ private func reload() {+ do {+ children = try repository.children(in: familyID)+ if !children.contains(where: { $0.id == childID }) { childID = children.first?.id }+ connections = try childID.map { try repository.connections(for: $0, includeDeceased: showLostContact) } ?? []+ states = try repository.connectionStates(connections.map(\.id))+ } catch { failure = error.localizedDescription }+ }+}++struct NameEntrySheet: View {+ let title: String+ let field: String+ let actionTitle: String+ let save: (String) throws -> Void+ @State private var name = ""+ @State private var failure: String?+ @FocusState private var focused: Bool+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ NavigationStack {+ Group {+ #if os(macOS)+ MacFormSection(title) {+ Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 14) {+ MacFormRow("Name") { nameField }+ }+ }+ .padding(24)+ .frame(minWidth: 380, maxWidth: 650)+ #else+ Form {+ nameField+ }+ #endif+ }+ .navigationTitle(title)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button(actionTitle, action: performSave)+ .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ .accessibilityIdentifier("capture.save")+ }+ }+ }+ .frame(minWidth: 300, minHeight: 180)+ .task { focused = true }+ .graphFailure($failure)+ }++ private var nameField: some View {+ TextField(field, text: $name).focused($focused).accessibilityIdentifier("capture.name")+ .onSubmit { performSave() }+ }++ private func performSave() {+ guard !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }+ do { try save(name); dismiss() } catch { failure = error.localizedDescription }+ }+}
diff --git a/Halo Family/Halo Family/ConnectionDetailView.swift b/Halo Family/Halo Family/ConnectionDetailView.swiftnew file mode 100644index 0000000..1c02954--- /dev/null+++ b/Halo Family/Halo Family/ConnectionDetailView.swift @@ -0,0 +1,231 @@+import Combine+import CoreData+import SwiftUI++struct ConnectionDetailView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let connection: GraphRow+ var readOnly = false+ @State private var archived = false+ @State private var personID: NSManagedObjectID?+ @State private var memberships: [MembershipRow] = []+ @State private var contexts: [ContextRow] = []+ @State private var contextID: NSManagedObjectID?+ @State private var origin: OriginRow?+ @State private var originConflicts: [OriginProposalRow] = []+ @State private var originHeads: Set<UUID> = []+ @State private var relationshipState: ConnectionStateSnapshot?+ @State private var editingState = false+ @State private var editingOrigin = false+ @State private var failure: String?++ var body: some View {+ Form {+ if readOnly || archived {+ Section { Text("This earlier relationship is retained as read-only merge history.") }+ }+ if let personID {+ NavigationLink("Person details") {+ PersonDetailView(repository: repository, familyID: familyID, personID: personID)+ }+ }+ Section("First meeting") {+ if !originConflicts.isEmpty {+ Label("First meeting needs review", systemImage: "person.2.badge.gearshape")+ Text("Different accounts have been kept. Choose which to use; the alternatives stay in the history.")+ .foregroundStyle(.secondary)+ ForEach(originConflicts) { proposal in+ VStack(alignment: .leading) {+ if proposal.isCleared { Text("First meeting not recorded") }+ if let source = proposal.sourceName { Text(source) }+ if !proposal.narrative.isEmpty { Text(proposal.narrative) }+ Button("Use this account") {+ perform {+ try repository.resolveOrigin(connectionID: connection.id,+ choosing: proposal.id, expectedHeads: originHeads)+ }+ }+ .disabled(readOnly || archived)+ }+ }+ } else if let origin {+ if let source = origin.sourceName { Text(source) }+ if !origin.narrative.isEmpty { Text(origin.narrative) }+ } else {+ Text("Not recorded").foregroundStyle(.secondary)+ }+ Button(origin == nil ? "Record first meeting" : "Edit first meeting") { editingOrigin = true }+ .disabled(!originConflicts.isEmpty || readOnly || archived)+ }+ if let relationshipState {+ Section("Relationship") {+ Text(relationshipState.statusNeedsReview ? "Status needs review" : relationshipState.state.label)+ if !relationshipState.note.isEmpty { Text(relationshipState.note) }+ if relationshipState.closenessNeedsReview {+ Text("Closeness needs review")+ } else if let choice = relationshipState.closeness {+ Text(choice.label)+ } else if let value = relationshipState.closenessValue {+ Text("Closeness: \(value) of 10")+ }+ Button("Edit relationship") { editingState = true }.disabled(readOnly || archived)+ }+ }+ Section("Contexts") {+ if memberships.isEmpty { Text("No memberships recorded.").foregroundStyle(.secondary) }+ ForEach(memberships) { membership in+ VStack(alignment: .leading, spacing: 8) {+ Text(membership.name)+ if let endedAt = membership.endedAt {+ Text("Ended \(endedAt.formatted(date: .abbreviated, time: .omitted))")+ .font(.caption).foregroundStyle(.secondary)+ } else {+ if membership.isArchived { Text("Archived context").font(.caption).foregroundStyle(.secondary) }+ Button("End membership today") {+ perform { try repository.endMembership(membership.id, at: Date()) }+ }+ .disabled(readOnly || archived)+ }+ }+ }+ Picker("Add context", selection: $contextID) {+ Text("Choose a context").tag(nil as NSManagedObjectID?)+ ForEach(contexts.filter { !$0.isArchived }) { Text($0.path).tag(Optional($0.id)) }+ }+ .disabled(readOnly || archived)+ Button("Add membership") {+ guard let contextID else { return }+ perform {+ _ = try repository.addMembership(connectionID: connection.id, contextID: contextID)+ self.contextID = nil+ }+ }+ .disabled(contextID == nil || readOnly || archived)+ }+ }+ .navigationTitle(connection.name)+ .task { perform {} }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in+ perform {}+ }+ .sheet(isPresented: $editingOrigin, onDismiss: { perform {} }, content: {+ OriginEditor(repository: repository, familyID: familyID, connectionID: connection.id,+ original: origin, headIDs: originHeads)+ })+ .sheet(isPresented: $editingState, onDismiss: { perform {} }, content: {+ if let relationshipState {+ ConnectionStateEditor(repository: repository, connectionID: connection.id, initial: relationshipState)+ }+ })+ .graphFailure($failure)+ }++ private func perform(_ action: () throws -> Void) {+ do {+ try action()+ let current = try repository.readable(connection.id, entity: "Connection")+ archived = current.entity.attributesByName["archivedAt"] != nil && current.value(forKey: "archivedAt") != nil+ personID = try repository.personID(for: connection.id)+ memberships = try repository.memberships(for: connection.id)+ contexts = try repository.contexts(in: familyID)+ let overview = try repository.originOverview(for: connection.id)+ origin = overview.origin+ originConflicts = overview.conflicts+ originHeads = overview.headIDs+ relationshipState = try repository.connectionState(connection.id)+ } catch { failure = error.localizedDescription }+ }+}++private struct OriginEditor: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let connectionID: NSManagedObjectID+ @State private var baseline: OriginRow?+ @State private var baselineHeads: Set<UUID>+ @State private var kind = "Description"+ @State private var contextID: NSManagedObjectID?+ @State private var eventID: NSManagedObjectID?+ @State private var narrative = ""+ @State private var contexts: [ContextRow] = []+ @State private var events: [EventRow] = []+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss++ init(repository: FamilyRepository, familyID: NSManagedObjectID, connectionID: NSManagedObjectID,+ original: OriginRow?, headIDs: Set<UUID>) {+ self.repository = repository+ self.familyID = familyID+ self.connectionID = connectionID+ _baseline = State(initialValue: original)+ _baselineHeads = State(initialValue: headIDs)+ }++ var body: some View {+ NavigationStack {+ Form {+ Section("First meeting") {+ Picker("Source", selection: $kind) {+ Text("Description").tag("Description")+ Text("Context").tag("Context")+ Text("Event").tag("Event")+ }+ if kind == "Context" {+ Picker("Context", selection: $contextID) {+ Text("Choose a context").tag(nil as NSManagedObjectID?)+ ForEach(contexts) { Text($0.path).tag(Optional($0.id)) }+ }+ }+ if kind == "Event" {+ Picker("Event", selection: $eventID) {+ Text("Choose an event").tag(nil as NSManagedObjectID?)+ ForEach(events) { Text($0.label).tag(Optional($0.id)) }+ }+ }+ TextField("How they met", text: $narrative, axis: .vertical)+ }+ if let baseline {+ Button("Clear first meeting", role: .destructive) {+ perform {+ try repository.clearOrigin(connectionID: connectionID, expectedOrigin: baseline)+ dismiss()+ }+ }+ }+ }+ .navigationTitle("First meeting")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") {+ perform {+ let input = OriginInput(contextID: kind == "Context" ? contextID : nil,+ eventID: kind == "Event" ? eventID : nil, narrative: narrative)+ try repository.saveOrigin(connectionID: connectionID, input: input,+ expectedOrigin: baseline, expectedHeads: baselineHeads)+ dismiss()+ }+ }+ }+ }+ }+ .frame(minWidth: 300, minHeight: 350)+ .task {+ perform {+ contexts = try repository.contexts(in: familyID)+ events = try repository.events(in: familyID)+ contextID = baseline?.contextID+ eventID = baseline?.eventID+ narrative = baseline?.narrative ?? ""+ kind = contextID != nil ? "Context" : eventID != nil ? "Event" : "Description"+ }+ }+ .graphFailure($failure)+ }++ private func perform(_ action: () throws -> Void) {+ do { try action() } catch { failure = error.localizedDescription }+ }+}
diff --git a/Halo Family/Halo Family/ConnectionStateEditor.swift b/Halo Family/Halo Family/ConnectionStateEditor.swiftnew file mode 100644index 0000000..950d099--- /dev/null+++ b/Halo Family/Halo Family/ConnectionStateEditor.swift @@ -0,0 +1,157 @@+import CoreData+import SwiftUI++struct ConnectionStateEditor: View {+ let repository: FamilyRepository+ let connectionID: NSManagedObjectID+ @State private var initialValue: Int16?+ @State private var choice: ClosenessChoice?+ @State private var state: ConnectionState+ @State private var note: String+ @State private var expectedClosenessID: NSManagedObjectID?+ @State private var expectedStatusID: NSManagedObjectID?+ @State private var closenessConflict: Bool+ @State private var statusConflict: Bool+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss++ init(repository: FamilyRepository, connectionID: NSManagedObjectID, initial: ConnectionStateSnapshot) {+ self.repository = repository+ self.connectionID = connectionID+ _initialValue = State(initialValue: initial.closenessValue)+ _choice = State(initialValue: initial.closeness)+ _state = State(initialValue: initial.state)+ _note = State(initialValue: initial.note)+ _expectedClosenessID = State(initialValue: initial.closenessID)+ _expectedStatusID = State(initialValue: initial.statusID)+ _closenessConflict = State(initialValue: initial.closenessNeedsReview)+ _statusConflict = State(initialValue: initial.statusNeedsReview)+ }++ var body: some View {+ NavigationStack {+ Group {+ #if os(macOS)+ macForm+ #else+ Form {+ Section("Closeness") {+ if closenessConflict { closenessReview }+ closenessPicker+ saveCloseness+ }+ Section("Contact") {+ if statusConflict { statusReview }+ statusPicker+ noteField+ saveStatus+ }+ }+ #endif+ }+ .navigationTitle("Relationship")+ .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }+ }+ .frame(minWidth: 300, minHeight: 350)+ .graphFailure($failure)+ }++ private var closenessReview: some View {+ TemporalConflictReview(repository: repository, connectionID: connectionID, closeness: true) {+ let saved = try repository.connectionState(connectionID)+ initialValue = saved.closenessValue+ choice = saved.closeness+ expectedClosenessID = saved.closenessID+ closenessConflict = saved.closenessNeedsReview+ }+ }++ private var statusReview: some View {+ TemporalConflictReview(repository: repository, connectionID: connectionID, closeness: false) {+ let saved = try repository.connectionState(connectionID)+ state = saved.state+ note = saved.note+ expectedStatusID = saved.statusID+ statusConflict = saved.statusNeedsReview+ }+ }++ private var closenessPicker: some View {+ Picker("Closeness", selection: $choice) {+ Text(initialValue.map { "Recorded value: \($0) of 10" } ?? "Not assessed").tag(nil as ClosenessChoice?)+ ForEach(ClosenessChoice.allCases) { Text($0.label).tag(Optional($0)) }+ }+ .disabled(closenessConflict)+ .accessibilityIdentifier("relationship.closeness")+ }++ private var statusPicker: some View {+ Picker("Status", selection: $state) {+ ForEach(ConnectionState.allCases, id: \.self) { Text($0.label).tag($0) }+ }+ .disabled(statusConflict)+ .accessibilityIdentifier("relationship.status")+ }++ private var noteField: some View {+ TextField("Explanation, if useful", text: $note, axis: .vertical)+ .disabled(statusConflict)+ .accessibilityIdentifier("relationship.note")+ }++ private var saveCloseness: some View {+ Button("Save closeness") {+ guard let choice else { return }+ perform {+ try repository.setCloseness(choice, connectionID: connectionID, expectedID: expectedClosenessID)+ expectedClosenessID = try repository.connectionState(connectionID).closenessID+ }+ }+ .disabled(choice == nil || closenessConflict)+ .accessibilityIdentifier("relationship.saveCloseness")+ }++ private var saveStatus: some View {+ Button("Save contact status") {+ perform {+ try repository.setConnectionState(state, note: note, connectionID: connectionID, expectedID: expectedStatusID)+ let saved = try repository.connectionState(connectionID)+ expectedStatusID = saved.statusID+ note = saved.note+ }+ }+ .disabled(statusConflict)+ .accessibilityIdentifier("relationship.saveStatus")+ }++ #if os(macOS)+ private var macForm: some View {+ ScrollView {+ VStack(alignment: .leading, spacing: 24) {+ MacFormSection("Closeness") {+ if closenessConflict { closenessReview }+ Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 14) {+ MacFormRow("Closeness") { closenessPicker.labelsHidden().pickerStyle(.menu).fixedSize() }+ MacFormRow("") { saveCloseness }+ }+ }+ MacFormSection("Contact") {+ if statusConflict { statusReview }+ Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 14) {+ MacFormRow("Status") { statusPicker.labelsHidden().pickerStyle(.menu).fixedSize() }+ MacFormRow("Explanation") { noteField }+ MacFormRow("") { saveStatus }+ }+ }+ }+ .padding(24)+ .frame(maxWidth: 650, alignment: .leading)+ }+ .frame(minWidth: 440)+ }+ #endif++ private func perform(_ action: () throws -> Void) {+ do { try action() } catch { failure = error.localizedDescription }+ }+}
diff --git a/Halo Family/Halo Family/ContentView.swift b/Halo Family/Halo Family/ContentView.swiftindex a88f14b..1326a1b 100644--- a/Halo Family/Halo Family/ContentView.swift +++ b/Halo Family/Halo Family/ContentView.swift @@ -1,15 +1,14 @@ import SwiftUI-import Combine-import CoreData struct ContentView: View { @State private var repository: FamilyRepository? @State private var failure: String?+ private let invitations = ShareInvitations.shared var body: some View { Group { if let repository {- FamilyCaptureView(repository: repository)+ FamilyWorkspaceView(repository: repository) } else if let failure { ContentUnavailableView { Label("Unable to open your data", systemImage: "externaldrive.badge.exclamationmark")@@ -23,130 +22,34 @@ struct ContentView: View { } } .task { await load() }+ .safeAreaInset(edge: .bottom) {+ if let issue = invitations.issue {+ VStack {+ Text(issue)+ Button("Retry invitation") { Task { await invitations.retry() } }+ .disabled(invitations.isAccepting)+ }+ .padding()+ .background(.regularMaterial)+ }+ } } private func load() async { guard repository == nil else { return } do {+ #if DEBUG+ if let directory = try SyntheticLaunch.directory() {+ repository = FamilyRepository(stack: try PersistenceStack(directory: directory))+ } else {+ repository = FamilyRepository(stack: try await .production())+ }+ #else repository = FamilyRepository(stack: try await .production())+ #endif failure = nil } catch { failure = error.localizedDescription } } }--private struct FamilyCaptureView: View {- let repository: FamilyRepository- @State private var families: [GraphRow] = []- @State private var children: [GraphRow] = []- @State private var connections: [GraphRow] = []- @State private var familyID: NSManagedObjectID?- @State private var childID: NSManagedObjectID?- @State private var familyName = ""- @State private var childName = ""- @State private var personName = ""- @State private var failure: String?- @Environment(\.scenePhase) private var scenePhase-- var body: some View {- NavigationStack {- Form {- if let issue = repository.stack.issue {- Section("Data refresh") {- Text(issue)- Button("Retry") { Task { await repository.stack.refreshHistory() } }- }- }- if let issue = repository.stack.syncIssue {- Section("iCloud") { Text(issue) }- }- Section("Family") {- if !families.isEmpty {- Picker("Family", selection: $familyID) {- Text("Choose a family").tag(nil as NSManagedObjectID?)- ForEach(families) { Text($0.name).tag(Optional($0.id)) }- }- }- TextField("Family name", text: $familyName)- Button("Create family") {- perform {- familyID = try repository.createFamily(name: familyName)- familyName = ""- }- }- .disabled(familyName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)- }- if let familyID {- Section("Children") {- Picker("Child", selection: $childID) {- Text("Choose a child").tag(nil as NSManagedObjectID?)- ForEach(children) { Text($0.name).tag(Optional($0.id)) }- }- TextField("Child’s name", text: $childName)- Button("Add child") {- perform {- childID = try repository.addChild(name: childName, familyID: familyID)- childName = ""- }- }- .disabled(childName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)- }- }- if let childID {- Section("Someone they know") {- TextField("Name or description", text: $personName)- Button("Save person") {- perform {- _ = try repository.quickCapture(name: personName, childID: childID)- personName = ""- }- }- .disabled(personName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)- }- Section("People") {- if connections.isEmpty {- Text("Add a name to start remembering their connections.")- .foregroundStyle(.secondary)- }- ForEach(connections) { Text($0.name) }- }- }- }- .navigationTitle("Halo Family")- .formStyle(.grouped)- .alert("Couldn’t save or load", isPresented: Binding(- get: { failure != nil }, set: { if !$0 { failure = nil } }- )) {- Button("OK") { failure = nil }- } message: {- Text(failure ?? "")- }- }- .task { perform {} }- .onChange(of: familyID) { perform {} }- .onChange(of: childID) { perform {} }- .onChange(of: scenePhase) {- if scenePhase == .active {- Task { await repository.stack.refreshHistory(); perform {} }- }- }- .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh)- .receive(on: DispatchQueue.main)) { _ in perform {} }- .onReceive(NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave)- .receive(on: DispatchQueue.main)) { _ in perform {} }- }-- private func perform(_ action: () throws -> Void) {- do {- try action()- families = try repository.families()- if !families.contains(where: { $0.id == familyID }) { familyID = families.first?.id }- children = try familyID.map { try repository.children(in: $0) } ?? []- if !children.contains(where: { $0.id == childID }) { childID = children.first?.id }- connections = try childID.map { try repository.connections(for: $0) } ?? []- } catch {- failure = error.localizedDescription- }- }-}
diff --git a/Halo Family/Halo Family/ContextRoleEditor.swift b/Halo Family/Halo Family/ContextRoleEditor.swiftnew file mode 100644index 0000000..829cb7c--- /dev/null+++ b/Halo Family/Halo Family/ContextRoleEditor.swift @@ -0,0 +1,90 @@+import CoreData+import SwiftUI++struct ContextRoleEditor: View {+ let repository: FamilyRepository+ @State private var baseline: ContextPersonRow+ @State private var role: String+ @State private var hasStart: Bool+ @State private var hasEnd: Bool+ @State private var startedAt: Date+ @State private var endedAt: Date+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss++ init(repository: FamilyRepository, original: ContextPersonRow) {+ self.repository = repository+ _baseline = State(initialValue: original)+ _role = State(initialValue: original.role)+ _hasStart = State(initialValue: original.startedAt != nil)+ _hasEnd = State(initialValue: original.endedAt != nil)+ _startedAt = State(initialValue: original.startedAt ?? original.endedAt ?? Date())+ _endedAt = State(initialValue: original.endedAt ?? Date())+ }++ var body: some View {+ NavigationStack {+ Group {+ #if os(macOS)+ macForm+ #else+ Form {+ Text(baseline.name)+ TextField("Role", text: $role)+ Toggle("Start date known", isOn: $hasStart)+ if hasStart { DatePicker("From", selection: $startedAt, displayedComponents: .date) }+ Toggle("End date known", isOn: $hasEnd)+ if hasEnd { DatePicker("Until", selection: $endedAt, displayedComponents: .date) }+ if hasStart && hasEnd && endedAt < startedAt {+ Text("The end date must not be earlier than the start date.").foregroundStyle(.red)+ }+ }+ #endif+ }+ .navigationTitle("Role and dates")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") {+ do {+ try repository.updateRole(baseline.id, role: role, startedAt: hasStart ? startedAt : nil,+ endedAt: hasEnd ? endedAt : nil, expected: baseline)+ dismiss()+ } catch { failure = error.localizedDescription }+ }+ .disabled(hasStart && hasEnd && endedAt < startedAt)+ }+ }+ }+ .frame(minWidth: 300, minHeight: 300)+ .graphFailure($failure)+ }++ #if os(macOS)+ private var macForm: some View {+ ScrollView {+ MacFormSection("Role and dates") {+ Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 14) {+ MacFormRow("Person") { Text(baseline.name) }+ MacFormRow("Role") { TextField("Role", text: $role).accessibilityLabel("Role") }+ MacFormRow("Start known") { Toggle("Start date known", isOn: $hasStart).labelsHidden() }+ if hasStart {+ MacFormRow("From") { DatePicker("From", selection: $startedAt, displayedComponents: .date).labelsHidden() }+ }+ MacFormRow("End known") { Toggle("End date known", isOn: $hasEnd).labelsHidden() }+ if hasEnd {+ MacFormRow("Until") { DatePicker("Until", selection: $endedAt, displayedComponents: .date).labelsHidden() }+ }+ }+ if hasStart && hasEnd && endedAt < startedAt {+ Text("The end date must not be earlier than the start date.").foregroundStyle(.red)+ .padding(.leading, 116)+ }+ }+ .padding(24)+ .frame(maxWidth: 650, alignment: .leading)+ }+ .frame(minWidth: 420)+ }+ #endif+}
diff --git a/Halo Family/Halo Family/ContextsView.swift b/Halo Family/Halo Family/ContextsView.swiftnew file mode 100644index 0000000..92ea3a7--- /dev/null+++ b/Halo Family/Halo Family/ContextsView.swift @@ -0,0 +1,160 @@+import Combine+import CoreData+import SwiftUI++struct ContextsView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ @State private var contexts: [ContextRow] = []+ @State private var showArchived = false+ @State private var parentID: NSManagedObjectID?+ @State private var name = ""+ @State private var failure: String?++ var body: some View {+ Form {+ Section("Contexts") {+ Toggle("Include archived", isOn: $showArchived)+ ForEach(contexts.filter { showArchived || !$0.isArchived }) { context in+ NavigationLink {+ ContextDetailView(repository: repository, familyID: familyID, context: context)+ } label: {+ VStack(alignment: .leading) {+ Text(context.path)+ if context.isArchived { Text("Archived").font(.caption).foregroundStyle(.secondary) }+ }+ }+ }+ }+ Section("New context") {+ TextField("Name", text: $name)+ Picker("Inside", selection: $parentID) {+ Text("Top level").tag(nil as NSManagedObjectID?)+ ForEach(contexts.filter { !$0.isArchived }) { Text($0.path).tag(Optional($0.id)) }+ }+ Button("Create context") {+ perform {+ _ = try repository.createContext(name: name, familyID: familyID, parentID: parentID)+ name = ""+ }+ }+ .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }+ .navigationTitle("Contexts")+ .task { perform {} }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in+ perform {}+ }+ .graphFailure($failure)+ }++ private func perform(_ action: () throws -> Void) {+ do { try action(); contexts = try repository.contexts(in: familyID) } catch { failure = error.localizedDescription }+ }+}++private struct ContextDetailView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let context: ContextRow+ @State private var archived = false+ @State private var connections: [ContextConnectionRow] = []+ @State private var associations: [ContextPersonRow] = []+ @State private var people: [GraphRow] = []+ @State private var personID: NSManagedObjectID?+ @State private var failure: String?+ @State private var role = ""+ @State private var hasStart = false+ @State private var hasEnd = false+ @State private var startedAt = Date()+ @State private var endedAt = Date()+ @State private var editingAssociation: ContextPersonRow?++ var body: some View {+ Form {+ Section {+ Text(context.path)+ Button(archived ? "Restore context" : "Archive context") {+ perform { try repository.archiveContext(context.id, archived: !archived) }+ }+ }+ Section("Peer connections") {+ ForEach(connections) { membership in+ NavigationLink {+ ConnectionDetailView(repository: repository, familyID: familyID,+ connection: GraphRow(id: membership.connectionID, name: membership.personName))+ } label: {+ VStack(alignment: .leading) {+ Text(membership.personName)+ Text("Known by \(membership.childName)").foregroundStyle(.secondary)+ if let start = membership.startedAt {+ Text("From \(start.formatted(date: .abbreviated, time: .omitted))").font(.caption)+ }+ if let end = membership.endedAt {+ Text("Until \(end.formatted(date: .abbreviated, time: .omitted))").font(.caption)+ }+ }+ }+ }+ if connections.isEmpty { Text("No memberships recorded.").foregroundStyle(.secondary) }+ }+ Section("Relevant people") {+ ForEach(associations) { association in+ NavigationLink {+ PersonDetailView(repository: repository, familyID: familyID, personID: association.personID)+ } label: {+ VStack(alignment: .leading) {+ Text(association.name)+ if !association.role.isEmpty { Text(association.role).foregroundStyle(.secondary) }+ if let start = association.startedAt { Text("From \(start.formatted(date: .abbreviated, time: .omitted))") }+ if let end = association.endedAt { Text("Until \(end.formatted(date: .abbreviated, time: .omitted))") }+ }+ }+ Button("Edit role or dates") { editingAssociation = association }+ }+ Picker("Person", selection: $personID) {+ Text("Choose a person").tag(nil as NSManagedObjectID?)+ ForEach(people) { Text($0.name).tag(Optional($0.id)) }+ }+ TextField("Role, such as teacher or coach", text: $role)+ Toggle("Start date known", isOn: $hasStart)+ if hasStart { DatePicker("From", selection: $startedAt, displayedComponents: .date) }+ Toggle("End date known", isOn: $hasEnd)+ if hasEnd { DatePicker("Until", selection: $endedAt, displayedComponents: .date) }+ Button("Associate person") {+ guard let personID else { return }+ perform {+ _ = try repository.associatePerson(personID, contextID: context.id, role: role,+ startedAt: hasStart ? startedAt : nil, endedAt: hasEnd ? endedAt : nil)+ role = ""+ hasStart = false+ hasEnd = false+ }+ }+ .disabled(personID == nil)+ }+ }+ .navigationTitle(context.name)+ .sheet(item: $editingAssociation, onDismiss: { perform {} }, content: { association in+ ContextRoleEditor(repository: repository, original: association)+ })+ .task { perform {} }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in+ perform {}+ }+ .graphFailure($failure)+ }++ private func perform(_ action: () throws -> Void) {+ do {+ try action()+ archived = try repository.contextIsArchived(context.id)+ connections = try repository.contextConnections(context.id)+ associations = try repository.contextPeople(context.id)+ people = try repository.people(in: familyID)+ } catch { failure = error.localizedDescription }+ }+}
diff --git a/Halo Family/Halo Family/EventDetailView.swift b/Halo Family/Halo Family/EventDetailView.swiftnew file mode 100644index 0000000..45db971--- /dev/null+++ b/Halo Family/Halo Family/EventDetailView.swift @@ -0,0 +1,355 @@+import Combine+import CoreData+import SwiftUI+import UniformTypeIdentifiers++struct EventDetailView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let eventID: NSManagedObjectID+ @State private var event: EventRow?+ @State private var participants: [ParticipantRow] = []+ @State private var gifts: [GiftRow] = []+ @State private var attachments: [AttachmentRow] = []+ @State private var editing = false+ @State private var addingPerson = false+ @State private var selectedPerson: ParticipantRow?+ @State private var addingGift = false+ @State private var selectedGift: GiftRow?+ @State private var importing = false+ @State private var working = false+ @State private var importTask: Task<Void, Never>?+ @State private var failure: String?++ var body: some View {+ MemoryForm {+ if let event {+ MemorySection("Social event") {+ Text(event.title).font(.headline)+ if let date = event.date { Text(date, format: .dateTime.day().month().year()) }+ if !event.type.isEmpty { Text(event.type).foregroundStyle(.secondary) }+ if !event.notes.isEmpty { Text(event.notes) }+ Button("Edit event") { editing = true }+ Button(event.isArchived ? "Restore event" : "Archive event") {+ perform { try repository.archiveEvent(eventID, archived: !event.isArchived) }+ }+ }+ MemorySection("People") {+ ForEach(participants) { participant in+ Button { selectedPerson = participant } label: {+ VStack(alignment: .leading, spacing: 4) {+ Text(participant.name)+ if !participant.roles.isEmpty { Text(participant.roles.sorted().joined(separator: ", ")).font(.caption) }+ Text("Invitation: \(participant.invitation.label) · Attendance: \(participant.attendance.label)")+ .font(.caption).foregroundStyle(.secondary)+ }+ }+ }+ Button("Add person to event") { addingPerson = true }+ Text("Participation records invitations and attendance separately. " ++ "It does not create a friendship or first-meeting record.")+ .font(.caption).foregroundStyle(.secondary)+ }+ MemorySection("Gifts") {+ ForEach(gifts) { gift in+ VStack(alignment: .leading, spacing: 4) {+ Text(gift.description)+ if !gift.givers.isEmpty { Text("From: \(gift.givers.joined(separator: ", "))").font(.caption) }+ if !gift.recipients.isEmpty { Text("To: \(gift.recipients.joined(separator: ", "))").font(.caption) }+ if !gift.note.isEmpty { Text(gift.note) }+ Button("Edit gift") { selectedGift = gift }+ ForEach(attachments.filter { gift.attachmentIDs.contains($0.id) }) { attachment in+ AttachmentPreview(assets: AssetRepository(stack: repository.stack), attachment: attachment)+ }+ }+ }+ Button("Record a gift") { addingGift = true }+ }+ MemorySection("Invitations and attachments") {+ ForEach(attachments) { attachment in+ AttachmentPreview(assets: AssetRepository(stack: repository.stack), attachment: attachment)+ }+ Button("Import image or PDF") { importing = true }.disabled(working)+ if working { ProgressView("Saving attachment…") }+ Text("App-owned JPEG, PNG or PDF copies, up to 20 MB. Image location metadata is removed.")+ .font(.caption).foregroundStyle(.secondary)+ }+ } else { ProgressView() }+ }+ .navigationTitle(event?.title ?? "Social event")+ .task { perform {} }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in perform {} }+ .sheet(isPresented: $editing, onDismiss: { perform {} }, content: {+ if let event { EventEditor(repository: repository, familyID: familyID, initial: event) }+ })+ .sheet(isPresented: $addingPerson, onDismiss: { perform {} }, content: {+ ParticipantEditor(repository: repository, familyID: familyID, eventID: eventID, initial: nil)+ })+ .sheet(item: $selectedPerson, onDismiss: { perform {} }, content: { initial in+ ParticipantEditor(repository: repository, familyID: familyID, eventID: eventID, initial: initial)+ })+ .sheet(isPresented: $addingGift, onDismiss: { perform {} }, content: {+ GiftEditor(repository: repository, familyID: familyID, eventID: eventID, attachments: attachments)+ })+ .sheet(item: $selectedGift, onDismiss: { perform {} }, content: { initial in+ GiftEditor(repository: repository, familyID: familyID, eventID: eventID, attachments: attachments, initial: initial)+ })+ .fileImporter(isPresented: $importing, allowedContentTypes: [.jpeg, .png, .pdf]) { result in+ do {+ let url = try result.get()+ guard !working else { return }+ working = true+ importTask = Task {+ defer { working = false; importTask = nil }+ do {+ let data = try await Task.detached { try ImportedFile.read(url) }.value+ _ = try await AssetRepository(stack: repository.stack)+ .importAttachment(data, filename: url.lastPathComponent, eventID: eventID)+ perform {}+ } catch { if !Task.isCancelled { failure = error.localizedDescription } }+ }+ } catch { failure = error.localizedDescription }+ }+ .onDisappear { importTask?.cancel() }+ .graphFailure($failure)+ }++ private func perform(_ action: () throws -> Void) {+ do {+ try action()+ let fresh = try repository.event(eventID)+ let people = try repository.participants(eventID)+ let gifts = try repository.gifts(eventID)+ let attachments = try repository.attachments(eventID)+ event = fresh; participants = people; self.gifts = gifts; self.attachments = attachments+ } catch { failure = error.localizedDescription }+ }+}++private struct EventEditor: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ @State private var initial: EventRow+ @State private var title: String+ @State private var date: Date+ @State private var dateKnown: Bool+ @State private var type: String+ @State private var notes: String+ @State private var subjectID: NSManagedObjectID?+ @State private var contextID: NSManagedObjectID?+ @State private var people: [GraphRow] = []+ @State private var contexts: [ContextRow] = []+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss++ init(repository: FamilyRepository, familyID: NSManagedObjectID, initial: EventRow) {+ self.repository = repository; self.familyID = familyID; _initial = State(initialValue: initial)+ _title = State(initialValue: initial.title); _date = State(initialValue: initial.date ?? Date())+ _dateKnown = State(initialValue: initial.date != nil)+ _type = State(initialValue: initial.type); _notes = State(initialValue: initial.notes)+ _subjectID = State(initialValue: initial.subjectID); _contextID = State(initialValue: initial.contextID)+ }+ var body: some View {+ NavigationStack {+ MemoryForm {+ MemorySection("Social memory") {+ MemoryField("Title") { TextField("Title", text: $title) }+ if initial.date == nil {+ MemoryField("Known date") { Toggle("Record a known date", isOn: $dateKnown) }+ }+ if dateKnown {+ MemoryField("Date") { DatePicker("Date", selection: $date, displayedComponents: .date) }+ }+ MemoryField("Type") { TextField("Type, such as birthday (optional)", text: $type) }+ MemoryField("Subject") {+ Picker("Subject", selection: $subjectID) {+ Text("Not recorded").tag(nil as NSManagedObjectID?)+ ForEach(people) { Text($0.name).tag(Optional($0.id)) }+ }+ }+ MemoryField("Context") {+ Picker("Context", selection: $contextID) {+ Text("Not recorded").tag(nil as NSManagedObjectID?)+ ForEach(contexts) { Text($0.path).tag(Optional($0.id)) }+ }+ }+ MemoryField("Notes") { TextField("Notes", text: $notes, axis: .vertical) }+ }+ }+ .navigationTitle("Edit event")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") {+ do {+ try repository.updateEvent(initial.id, title: title, date: dateKnown ? date : nil, type: type, notes: notes,+ links: (subjectID, contextID), expected: initial)+ dismiss()+ } catch { failure = error.localizedDescription }+ }.disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }+ }+ .frame(minWidth: 320, minHeight: 420)+ .task {+ do {+ people = try repository.people(in: familyID)+ contexts = try repository.contexts(in: familyID)+ } catch { failure = error.localizedDescription }+ }+ .graphFailure($failure)+ }+}++private struct ParticipantEditor: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let eventID: NSManagedObjectID+ let initial: ParticipantRow?+ @State private var people: [GraphRow] = []+ @State private var personID: NSManagedObjectID?+ @State private var roles: String+ @State private var invitation: InvitationState+ @State private var attendance: AttendanceState+ @State private var note: String+ @State private var includeHistorical = false+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss++ init(repository: FamilyRepository, familyID: NSManagedObjectID, eventID: NSManagedObjectID, initial: ParticipantRow?) {+ self.repository = repository; self.familyID = familyID; self.eventID = eventID; self.initial = initial+ _personID = State(initialValue: initial?.personID)+ _roles = State(initialValue: initial?.roles.sorted().joined(separator: ", ") ?? "")+ _invitation = State(initialValue: initial?.invitation ?? .unknown)+ _attendance = State(initialValue: initial?.attendance ?? .unknown); _note = State(initialValue: initial?.note ?? "")+ }+ var body: some View {+ NavigationStack {+ MemoryForm {+ MemorySection("Participation") {+ if let initial { Text(initial.name).font(.headline) } else {+ Toggle("Include historical people", isOn: $includeHistorical)+ MemoryField("Person") {+ Picker("Person", selection: $personID) {+ Text("Choose a person").tag(nil as NSManagedObjectID?)+ ForEach(people) { Text($0.name).tag(Optional($0.id)) }+ }+ }+ }+ MemoryField("Roles") { TextField("Roles, separated by commas", text: $roles) }+ MemoryField("Invitation") {+ Picker("Invitation", selection: $invitation) {+ ForEach(InvitationState.allCases, id: \.self) { Text($0.label).tag($0) }+ }+ }+ MemoryField("Attendance") {+ Picker("Attendance", selection: $attendance) {+ ForEach(AttendanceState.allCases, id: \.self) { Text($0.label).tag($0) }+ }+ }+ MemoryField("Note") { TextField("Note", text: $note, axis: .vertical) }+ }+ }+ .navigationTitle("Event person")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") {+ guard let personID else { return }+ do {+ try repository.saveParticipant(eventID: eventID, personID: personID,+ roles: Set(roles.components(separatedBy: ",")), invitation: invitation,+ attendance: attendance, note: note, expected: initial)+ dismiss()+ } catch { failure = error.localizedDescription }+ }.disabled(personID == nil)+ }+ }+ }+ .frame(minWidth: 320, minHeight: 420)+ .task { reload() }+ .onChange(of: includeHistorical) { reload() }+ .graphFailure($failure)+ }+ private func reload() {+ do {+ let existing = Set(try repository.participants(eventID).map(\.personID))+ people = try repository.people(in: familyID, includeDeceased: includeHistorical).filter { !existing.contains($0.id) }+ } catch { failure = error.localizedDescription }+ }+}++private struct GiftEditor: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let eventID: NSManagedObjectID+ let attachments: [AttachmentRow]+ @State private var people: [GraphRow] = []+ @State private var groups: [GraphRow] = []+ @State private var input = GiftInput(description: "")+ @State private var initial: GiftRow?+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss+ init(repository: FamilyRepository, familyID: NSManagedObjectID, eventID: NSManagedObjectID,+ attachments: [AttachmentRow], initial: GiftRow? = nil) {+ self.repository = repository; self.familyID = familyID; self.eventID = eventID; self.attachments = attachments+ _initial = State(initialValue: initial)+ if let initial {+ _input = State(initialValue: GiftInput(description: initial.description, givers: initial.giverIDs, groups: initial.groupIDs,+ recipients: initial.recipientIDs, attachments: initial.attachmentIDs, note: initial.note))+ }+ }+ var body: some View {+ NavigationStack {+ MemoryForm {+ MemorySection("Gift") {+ MemoryField("Description") { TextField("What was given?", text: $input.description) }+ MemoryField("Note") { TextField("Note", text: $input.note, axis: .vertical) }+ }+ MemorySection("From") {+ PersonSelection(rows: people, selection: $input.givers)+ PersonSelection(rows: groups, selection: $input.groups)+ }+ MemorySection("To") { PersonSelection(rows: people, selection: $input.recipients) }+ if !attachments.isEmpty {+ MemorySection("Event attachments") {+ PersonSelection(rows: attachments.map { GraphRow(id: $0.id, name: $0.title) }, selection: $input.attachments)+ }+ }+ }+ .navigationTitle("Record gift")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") {+ do {+ try repository.saveGift(eventID: eventID, input: input, expected: initial)+ dismiss()+ } catch { failure = error.localizedDescription }+ }.disabled(input.description.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }+ }+ .frame(minWidth: 320, minHeight: 440)+ .task {+ do {+ people = try repository.people(in: familyID)+ groups = try repository.groups(in: familyID)+ } catch { failure = error.localizedDescription }+ }+ .graphFailure($failure)+ }+}++struct PersonSelection: View {+ let rows: [GraphRow]+ @Binding var selection: Set<NSManagedObjectID>+ var body: some View {+ ForEach(rows) { row in+ Toggle(row.name, isOn: Binding(get: { selection.contains(row.id) }, set: { chosen in+ if chosen { selection.insert(row.id) } else { selection.remove(row.id) }+ }))+ }+ }+}
diff --git a/Halo Family/Halo Family/EventsView.swift b/Halo Family/Halo Family/EventsView.swiftnew file mode 100644index 0000000..804dcdc--- /dev/null+++ b/Halo Family/Halo Family/EventsView.swift @@ -0,0 +1,63 @@+import Combine+import CoreData+import SwiftUI++struct EventsView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ @State private var events: [EventRow] = []+ @State private var title = ""+ @State private var notes = ""+ @State private var date = Date()+ @State private var dateKnown = false+ @State private var failure: String?+ @State private var includeArchived = false++ var body: some View {+ MemoryForm {+ MemorySection("Social memories") {+ Toggle("Include archived events", isOn: $includeArchived)+ ForEach(events) { event in+ NavigationLink(event.label) {+ EventDetailView(repository: repository, familyID: familyID, eventID: event.id)+ }+ }+ if events.isEmpty { Text("No events recorded.").foregroundStyle(.secondary) }+ }+ MemorySection("Record an event") {+ TextField("Title, such as a birthday or playdate", text: $title)+ Toggle("I know the date", isOn: $dateKnown)+ if dateKnown { DatePicker("Date", selection: $date, displayedComponents: .date) }+ TextField("Notes", text: $notes, axis: .vertical)+ Button("Save event") {+ perform {+ _ = try repository.createEvent(title: title, date: date, notes: notes, familyID: familyID)+ title = ""+ notes = ""+ dateKnown = false+ }+ }+ .disabled(!dateKnown || title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ if !dateKnown {+ Text("When the meeting date is unknown, record a description on the connection instead.")+ .foregroundStyle(.secondary)+ }+ }+ }+ .navigationTitle("Events")+ .task { perform {} }+ .onChange(of: includeArchived) { perform {} }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in+ perform {}+ }+ .graphFailure($failure)+ }++ private func perform(_ action: () throws -> Void) {+ do {+ try action()+ events = try repository.events(in: familyID, includeArchived: includeArchived)+ } catch { failure = error.localizedDescription }+ }+}
diff --git a/Halo Family/Halo Family/FamilyKnowledgeViews.swift b/Halo Family/Halo Family/FamilyKnowledgeViews.swiftnew file mode 100644index 0000000..cb9cd77--- /dev/null+++ b/Halo Family/Halo Family/FamilyKnowledgeViews.swift @@ -0,0 +1,371 @@+import Combine+import CoreData+import SwiftUI++struct SensitiveDetailsView: View {+ let repository: FamilyRepository+ let personID: NSManagedObjectID+ @State private var initial: SensitiveSnapshot+ @State private var deceased: Bool+ @State private var year: String+ @State private var month: String+ @State private var day: String+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss++ init(repository: FamilyRepository, personID: NSManagedObjectID, initial: SensitiveSnapshot) {+ self.repository = repository; self.personID = personID; _initial = State(initialValue: initial)+ _deceased = State(initialValue: initial.isDeceased)+ _year = State(initialValue: initial.date.year.map(String.init) ?? "")+ _month = State(initialValue: initial.date.month.map(String.init) ?? "")+ _day = State(initialValue: initial.date.day.map(String.init) ?? "")+ }++ var body: some View {+ NavigationStack {+ MemoryForm {+ MemorySection("Sensitive details") {+ Toggle("This person has died", isOn: $deceased).accessibilityIdentifier("sensitive.deceased")+ if deceased {+ Text("Record only what is known. The date is optional; year and month can stand alone.")+ .foregroundStyle(.secondary)+ MemoryField("Year") { TextField("Year", text: $year) }+ MemoryField("Month") { TextField("Month (1–12)", text: $month) }+ MemoryField("Day") { TextField("Day", text: $day) }+ }+ Text("Existing relationships and social memories are preserved. These details are shared with invited co-parents.")+ .font(.caption).foregroundStyle(.secondary)+ }+ }+ .navigationTitle("Sensitive details")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) { Button("Save") { save() } }+ }+ }+ .frame(minWidth: 320, minHeight: 350)+ .graphFailure($failure)+ }++ private func save() {+ do {+ func number(_ input: String) throws -> Int? {+ let value = input.trimmingCharacters(in: .whitespacesAndNewlines)+ if value.isEmpty { return nil }+ guard let number = Int(value) else { throw MemoryError.invalidDate }+ return number+ }+ let date = try deceased ? PartialDate(year: number(year), month: number(month), day: number(day)) : PartialDate()+ try repository.setSensitiveDetails(personID, deceased: deceased, date: date, expected: initial)+ dismiss()+ } catch { failure = error.localizedDescription }+ }+}++struct FamilyKnowledgeView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let personID: NSManagedObjectID+ @State private var people: [GraphRow] = []+ @State private var facts: [FamilyFactRow] = []+ @State private var includeArchived = false+ @State private var derived: [DerivedKinshipRow] = []+ @State private var labels: [AddressLabelRow] = []+ @State private var editingLabel: AddressLabelRow?+ @State private var groups: [GraphRow] = []+ @State private var targetID: NSManagedObjectID?+ @State private var kind: StructuralKind? = .parentOf+ @State private var customLabel = ""+ @State private var nature = ""+ @State private var note = ""+ @State private var started = false+ @State private var ended = false+ @State private var startDate = Date()+ @State private var endDate = Date()+ @State private var address = ""+ @State private var language = ""+ @State private var script = ""+ @State private var usedByPerson: NSManagedObjectID?+ @State private var usedByGroup: NSManagedObjectID?+ @State private var failure: String?++ var body: some View {+ MemoryForm {+ MemorySection("Family knowledge") {+ Toggle("Include facts archived by a merge", isOn: $includeArchived)+ ForEach(facts) { fact in+ VStack(alignment: .leading, spacing: 6) {+ Text("\(fact.source) → \(fact.target): \(fact.label)")+ if !fact.nature.isEmpty { Text(fact.nature).font(.caption).foregroundStyle(.secondary) }+ if !fact.note.isEmpty { Text(fact.note) }+ if fact.isArchived { Text("Archived during merge").font(.caption).foregroundStyle(.secondary) }+ if let start = fact.startedAt { Text("From \(start.formatted(date: .abbreviated, time: .omitted))").font(.caption) }+ if let end = fact.endedAt {+ Text("Until \(end.formatted(date: .abbreviated, time: .omitted))").font(.caption)+ } else if !fact.isArchived {+ Button("End this relationship today") { perform { try repository.endFamilyFact(fact.id, at: Date()) } }+ }+ }+ }+ if facts.isEmpty {+ Text("Record the family knowledge you have. A complete family tree is optional.").foregroundStyle(.secondary)+ }+ }+ if !derived.isEmpty {+ MemorySection("Derived from known family facts") {+ ForEach(derived) { relative in+ Text("\(relative.name): \(relative.label)")+ }+ Text("These paths do not change entered relationships or family address labels.")+ .font(.caption).foregroundStyle(.secondary)+ }+ }+ MemorySection("Add a relationship from this person") {+ MemoryField("To") {+ Picker("To", selection: $targetID) {+ Text("Choose a person").tag(nil as NSManagedObjectID?)+ ForEach(people.filter { $0.id != personID }) { Text($0.name).tag(Optional($0.id)) }+ }+ }+ MemoryField("Relationship") {+ Picker("Relationship", selection: $kind) {+ Text("Entered description").tag(nil as StructuralKind?)+ ForEach(StructuralKind.allCases, id: \.self) { Text($0.label).tag(Optional($0)) }+ }+ }+ if kind == nil {+ MemoryField("Description") { TextField("Such as grandmother or second cousin", text: $customLabel) }+ } else {+ MemoryField("Nature") {+ Picker("Nature", selection: $nature) {+ Text("Not recorded").tag("")+ ForEach(["biological", "adoptive", "step", "foster", "unknown"], id: \.self) { Text($0.capitalized).tag($0) }+ }+ }+ }+ OptionalDates(knownStart: $started, knownEnd: $ended, start: $startDate, end: $endDate)+ MemoryField("Note") { TextField("Note", text: $note, axis: .vertical) }+ Button("Save relationship") {+ guard let targetID else { return }+ perform {+ try repository.addFamilyFact(sourceID: personID, targetID: targetID, kind: kind, label: customLabel,+ nature: nature, dates: (started ? startDate : nil, ended ? endDate : nil), note: note)+ self.targetID = nil; customLabel = ""; note = ""+ }+ }+ .disabled(targetID == nil || (kind == nil && customLabel.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty))+ }+ MemorySection("What people call them") {+ ForEach(labels) { label in+ VStack(alignment: .leading) {+ Text("\(label.usedBy): \(label.label)")+ if !label.language.isEmpty || !label.script.isEmpty {+ Text([label.language, label.script].filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption)+ }+ Button("Edit label") { editingLabel = label }+ }+ }+ MemoryField("Label") { TextField("Family title or name", text: $address) }+ MemoryField("Used by") {+ Picker("Used by person", selection: $usedByPerson) {+ Text("General or group").tag(nil as NSManagedObjectID?)+ ForEach(people) { Text($0.name).tag(Optional($0.id)) }+ }+ }+ if usedByPerson == nil {+ MemoryField("Group") {+ Picker("Used by group", selection: $usedByGroup) {+ Text("General").tag(nil as NSManagedObjectID?)+ ForEach(groups) { Text($0.name).tag(Optional($0.id)) }+ }+ }+ }+ MemoryField("Language") { TextField("Language (optional)", text: $language) }+ MemoryField("Script") { TextField("Script (optional)", text: $script) }+ Button("Add address label") {+ perform {+ try repository.addAddressLabel(targetID: personID, label: address, usedByPerson: usedByPerson,+ usedByGroup: usedByPerson == nil ? usedByGroup : nil, language: language,+ script: script)+ address = ""+ }+ }+ .disabled(address.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ NavigationLink("Groups and households") { GroupsView(repository: repository, familyID: familyID) }+ }+ .navigationTitle("Family")+ .onChange(of: includeArchived) { perform {} }+ .sheet(item: $editingLabel, content: { initial in+ AddressLabelEditor(repository: repository, initial: initial)+ })+ .task { perform {} }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in perform {} }+ .graphFailure($failure)+ }++ private func perform(_ action: () throws -> Void) {+ do {+ try action()+ people = try repository.people(in: familyID)+ facts = try repository.familyFacts(for: personID, includeArchived: includeArchived)+ derived = try repository.derivedKinship(for: personID)+ labels = try repository.addressLabels(for: personID)+ groups = try repository.groups(in: familyID)+ } catch { failure = error.localizedDescription }+ }+}++private struct AddressLabelEditor: View {+ let repository: FamilyRepository+ @State private var initial: AddressLabelRow+ @State private var label: String+ @State private var language: String+ @State private var script: String+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss+ init(repository: FamilyRepository, initial: AddressLabelRow) {+ self.repository = repository+ _initial = State(initialValue: initial)+ _label = State(initialValue: initial.label)+ _language = State(initialValue: initial.language)+ _script = State(initialValue: initial.script)+ }+ var body: some View {+ NavigationStack {+ MemoryForm {+ MemorySection("Address label") {+ Text("Used by: \(initial.usedBy)").foregroundStyle(.secondary)+ MemoryField("Label") { TextField("Label", text: $label) }+ MemoryField("Language") { TextField("Language", text: $language) }+ MemoryField("Script") { TextField("Script", text: $script) }+ }+ }+ .navigationTitle("Edit label")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") {+ do {+ try repository.updateAddressLabel(initial.id, label: label, language: language, script: script,+ expected: initial)+ dismiss()+ } catch { failure = error.localizedDescription }+ }.disabled(label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }+ }+ .frame(minWidth: 320, minHeight: 300)+ .graphFailure($failure)+ }+}++struct OptionalDates: View {+ @Binding var knownStart: Bool+ @Binding var knownEnd: Bool+ @Binding var start: Date+ @Binding var end: Date+ var body: some View {+ Toggle("Start date known", isOn: $knownStart)+ if knownStart { MemoryField("From") { DatePicker("From", selection: $start, displayedComponents: .date) } }+ Toggle("End date known", isOn: $knownEnd)+ if knownEnd { MemoryField("Until") { DatePicker("Until", selection: $end, displayedComponents: .date) } }+ }+}++struct GroupsView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ @State private var groups: [GraphRow] = []+ @State private var name = ""+ @State private var failure: String?+ var body: some View {+ MemoryForm {+ MemorySection("Groups and households") {+ ForEach(groups) { group in+ NavigationLink(group.name) { GroupDetailView(repository: repository, familyID: familyID, group: group) }+ }+ MemoryField("Name") { TextField("Group name", text: $name) }+ Button("Add group") {+ perform { _ = try repository.createGroup(name: name, familyID: familyID); name = "" }+ }.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }+ .navigationTitle("Groups")+ .task { perform {} }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in perform {} }+ .graphFailure($failure)+ }+ private func perform(_ action: () throws -> Void) {+ do { try action(); groups = try repository.groups(in: familyID) } catch { failure = error.localizedDescription }+ }+}++private struct GroupDetailView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let group: GraphRow+ @State private var members: [GroupMemberRow] = []+ @State private var people: [GraphRow] = []+ @State private var personID: NSManagedObjectID?+ @State private var role = ""+ @State private var started = false+ @State private var ended = false+ @State private var start = Date()+ @State private var end = Date()+ @State private var failure: String?+ var body: some View {+ MemoryForm {+ MemorySection("Members") {+ ForEach(members) { member in+ NavigationLink {+ PersonDetailView(repository: repository, familyID: familyID, personID: member.personID)+ } label: {+ VStack(alignment: .leading) {+ Text(member.name)+ if !member.role.isEmpty { Text(member.role).font(.caption) }+ if let end = member.endedAt { Text("Until \(end.formatted(date: .abbreviated, time: .omitted))").font(.caption) }+ }+ }+ if member.endedAt == nil {+ Button("End \(member.name)'s membership today") {+ perform { try repository.endGroupMembership(member.id, at: Date()) }+ }+ }+ }+ }+ MemorySection("Add member") {+ MemoryField("Person") {+ Picker("Person", selection: $personID) {+ Text("Choose a person").tag(nil as NSManagedObjectID?)+ ForEach(people) { Text($0.name).tag(Optional($0.id)) }+ }+ }+ MemoryField("Role") { TextField("Role (optional)", text: $role) }+ OptionalDates(knownStart: $started, knownEnd: $ended, start: $start, end: $end)+ Button("Add member") {+ guard let personID else { return }+ perform {+ try repository.addGroupMember(personID, groupID: group.id, role: role,+ startedAt: started ? start : nil, endedAt: ended ? end : nil)+ self.personID = nil; role = ""+ }+ }.disabled(personID == nil)+ }+ }+ .navigationTitle(group.name)+ .task { perform {} }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in perform {} }+ .graphFailure($failure)+ }+ private func perform(_ action: () throws -> Void) {+ do {+ try action()+ members = try repository.groupMembers(group.id)+ people = try repository.people(in: familyID)+ } catch { failure = error.localizedDescription }+ }+}
diff --git a/Halo Family/Halo Family/FamilyManagerView.swift b/Halo Family/Halo Family/FamilyManagerView.swiftnew file mode 100644index 0000000..d8442c7--- /dev/null+++ b/Halo Family/Halo Family/FamilyManagerView.swift @@ -0,0 +1,100 @@+import Combine+import CoreData+import SwiftUI++struct FamilyManagerView: View {+ let repository: FamilyRepository+ @Binding var selectedFamilyID: NSManagedObjectID?+ @State private var families: [GraphRow] = []+ @State private var name = ""+ @State private var sharing: FamilySharing?+ @State private var shareSession: FamilyShare?+ @State private var preparingShare = false+ @State private var preparation: Task<Void, Never>?+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ NavigationStack {+ Form {+ Section("Your family spaces") {+ ForEach(families) { family in+ Button {+ selectedFamilyID = family.id+ dismiss()+ } label: {+ HStack {+ Text(family.name)+ Spacer()+ if family.id == selectedFamilyID { Image(systemName: "checkmark") }+ }+ }+ .disabled(preparingShare)+ }+ }+ Section("New family space") {+ TextField("Family name", text: $name).accessibilityIdentifier("family.name")+ Button("Create family") {+ do {+ selectedFamilyID = try repository.createFamily(name: name)+ dismiss()+ } catch { failure = error.localizedDescription }+ }+ .disabled(preparingShare || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ .accessibilityIdentifier("family.create")+ }+ 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, " ++ "including notes, photos and Sensitive Details. There are no private-per-parent notes.")+ .font(.callout).foregroundStyle(.secondary)+ Button(preparingShare ? "Preparing invitation…" : "Share family") {+ guard !preparingShare else { return }+ preparingShare = true+ preparation = Task {+ defer { preparingShare = false; preparation = nil }+ do {+ try Task.checkCancellation()+ let service = sharing ?? FamilySharing(stack: repository.stack)+ sharing = service+ let session = try await service.prepare(familyID: selectedFamilyID)+ try Task.checkCancellation()+ shareSession = session+ } catch {+ if !Task.isCancelled { failure = error.localizedDescription }+ }+ }+ }+ .disabled(preparingShare)+ }+ }+ }+ .navigationTitle("Family spaces")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button(preparingShare ? "Cancel invitation" : "Done") {+ preparation?.cancel()+ dismiss()+ }+ }+ }+ }+ .frame(minWidth: 320, minHeight: 320)+ .task { reload() }+ .interactiveDismissDisabled(preparingShare)+ .onDisappear { preparation?.cancel() }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in reload() }+ .sheet(item: $shareSession) { session in+ if let sharing {+ FamilySharingView(session: session, sharing: sharing) { failure = $0 }+ .frame(minWidth: 300, minHeight: 200)+ }+ }+ .graphFailure($failure)+ }++ private func reload() {+ do { families = try repository.families() } catch { failure = error.localizedDescription }+ }+}
diff --git a/Halo Family/Halo Family/FamilyReviewView.swift b/Halo Family/Halo Family/FamilyReviewView.swiftnew file mode 100644index 0000000..ec0bc97--- /dev/null+++ b/Halo Family/Halo Family/FamilyReviewView.swift @@ -0,0 +1,111 @@+import Combine+import CoreData+import SwiftUI++struct FamilyReviewView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ @State private var people: [GraphRow] = []+ @State private var connections: [ConnectionReviewRow] = []+ @State private var duplicates: [DuplicatePersonPair] = []+ @State private var selectedDuplicate: DuplicatePersonPair?+ @State private var mergeIssues = false+ @AppStorage("halo.duplicateSuggestions.hidden") private var hiddenDuplicates = "[]"+ @State private var failure: String?+ @State private var loaded = false+ private var visibleDuplicates: [DuplicatePersonPair] {+ let hidden = Set((try? JSONDecoder().decode([String].self, from: Data(hiddenDuplicates.utf8))) ?? [])+ return duplicates.filter { !hidden.contains($0.id) }+ }++ var body: some View {+ List {+ if let failure {+ Section("Review could not be refreshed") {+ Text(failure)+ Button("Retry review", action: reload)+ }+ }+ if !loaded && failure == nil { ProgressView("Loading review…") }+ if loaded && failure == nil && people.isEmpty && connections.isEmpty && visibleDuplicates.isEmpty && !mergeIssues {+ ContentUnavailableView("All caught up", systemImage: "checkmark.circle",+ description: Text("New captures and different relationship accounts appear here."))+ }+ if mergeIssues {+ Section("Merge accounts need review") {+ NavigationLink("Review competing merges and late relationship accounts") {+ MergeConflictReviewView(repository: repository, familyID: familyID)+ }+ }+ }+ if !people.isEmpty {+ Section("Details to fill in") {+ ForEach(people) { person in+ NavigationLink(person.name) {+ PersonDetailView(repository: repository, familyID: familyID, personID: person.id)+ }+ }+ }+ }+ if !connections.isEmpty {+ Section("Different accounts") {+ ForEach(connections) { connection in+ NavigationLink {+ ConnectionDetailView(repository: repository, familyID: familyID,+ connection: GraphRow(id: connection.id, name: connection.name))+ } label: {+ VStack(alignment: .leading, spacing: 4) {+ Text(connection.name)+ Text("Known by \(connection.childName)").font(.caption).foregroundStyle(.secondary)+ if connection.originNeedsReview { Text("First meeting needs review").font(.caption) }+ if connection.relationshipNeedsReview { Text("Relationship needs review").font(.caption) }+ }+ }+ }+ }+ }+ if !visibleDuplicates.isEmpty {+ Section("Similar names") {+ Text("These may be separate people. Review the records before choosing to merge.")+ .font(.caption).foregroundStyle(.secondary)+ ForEach(visibleDuplicates) { pair in+ VStack(alignment: .leading) {+ Button("Review \(pair.source.name) and \(pair.survivor.name)") { selectedDuplicate = pair }+ Button("Hide this suggestion on this device") {+ var ids = Set((try? JSONDecoder().decode([String].self, from: Data(hiddenDuplicates.utf8))) ?? [])+ ids.insert(pair.id)+ if let data = try? JSONEncoder().encode(ids.sorted()), let text = String(data: data, encoding: .utf8) {+ hiddenDuplicates = text+ }+ }.font(.caption)+ }+ }+ }+ }+ Section("History") {+ NavigationLink("Merge history") { PersonMergeHistoryView(repository: repository, familyID: familyID) }+ }+ }+ .navigationTitle("Review")+ .task { reload() }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in reload() }+ .sheet(item: $selectedDuplicate, onDismiss: reload) { pair in+ PersonMergeView(repository: repository, familyID: familyID, sourceID: pair.source.id, preferredSurvivor: pair.survivor.id)+ }+ }++ private func reload() {+ do {+ let refreshedPeople = try repository.people(in: familyID, needsReview: true)+ let refreshedConnections = try repository.reviewConnections(in: familyID)+ let refreshedDuplicates = try repository.likelyDuplicates(in: familyID)+ mergeIssues = try !repository.mergeConflicts(in: familyID).isEmpty || !repository.lateMergeAccounts(in: familyID).isEmpty+ people = refreshedPeople+ connections = refreshedConnections+ duplicates = refreshedDuplicates+ loaded = true+ failure = nil+ } catch { failure = error.localizedDescription }+ }+}
diff --git a/Halo Family/Halo Family/FamilySharingView.swift b/Halo Family/Halo Family/FamilySharingView.swiftnew file mode 100644index 0000000..e039980--- /dev/null+++ b/Halo Family/Halo Family/FamilySharingView.swift @@ -0,0 +1,102 @@+import CloudKit+import SwiftUI++#if os(iOS)+import UIKit++struct FamilySharingView: UIViewControllerRepresentable {+ let session: FamilyShare+ let sharing: FamilySharing+ let onFailure: (String) -> Void++ func makeCoordinator() -> Coordinator { Coordinator(parent: self) }++ func makeUIViewController(context: Context) -> UICloudSharingController {+ let controller = UICloudSharingController(share: session.share, container: session.container)+ controller.availablePermissions = [.allowPrivate, .allowReadWrite]+ controller.delegate = context.coordinator+ return controller+ }++ func updateUIViewController(_ controller: UICloudSharingController, context: Context) {}++ final class Coordinator: NSObject, UICloudSharingControllerDelegate {+ let parent: FamilySharingView+ init(parent: FamilySharingView) { self.parent = parent }++ func itemTitle(for controller: UICloudSharingController) -> String? { parent.session.title }++ func cloudSharingController(_ controller: UICloudSharingController, failedToSaveShareWithError error: Error) {+ parent.onFailure(error.localizedDescription)+ }++ func cloudSharingControllerDidSaveShare(_ controller: UICloudSharingController) {+ guard let share = controller.share else { return }+ Task {+ do { try await parent.sharing.persist(share, familyID: parent.session.familyID) } catch {+ parent.onFailure(error.localizedDescription)+ }+ }+ }++ func cloudSharingControllerDidStopSharing(_ controller: UICloudSharingController) {+ parent.onFailure("Sharing has stopped. The family’s access has changed.")+ }+ }+}+#elseif os(macOS)+import AppKit++struct FamilySharingView: NSViewRepresentable {+ let session: FamilyShare+ let sharing: FamilySharing+ let onFailure: (String) -> Void++ func makeCoordinator() -> Coordinator { Coordinator(parent: self) }++ func makeNSView(context: Context) -> NSButton {+ let button = NSButton(title: "Invite a co-parent", target: context.coordinator, action: #selector(Coordinator.open))+ return button+ }++ func updateNSView(_ view: NSButton, context: Context) {}++ final class Coordinator: NSObject, NSCloudSharingServiceDelegate {+ let parent: FamilySharingView+ private var service: NSSharingService?+ init(parent: FamilySharingView) { self.parent = parent }++ @objc func open() {+ guard let service = NSSharingService(named: .cloudSharing) else {+ parent.onFailure("The system sharing service is unavailable.")+ return+ }+ self.service = service+ service.delegate = self+ let provider = NSItemProvider()+ provider.registerCloudKitShare(parent.session.share, container: parent.session.container)+ service.perform(withItems: [provider])+ }++ func options(for service: NSSharingService, share provider: NSItemProvider) -> NSSharingService.CloudKitOptions {+ [.allowPrivate, .allowReadWrite]+ }++ func sharingService(_ service: NSSharingService, didSave share: CKShare) {+ Task {+ do { try await parent.sharing.persist(share, familyID: parent.session.familyID) } catch {+ parent.onFailure(error.localizedDescription)+ }+ }+ }++ func sharingService(_ service: NSSharingService, didCompleteForItems items: [Any], error: Error?) {+ if let error { parent.onFailure(error.localizedDescription) }+ }++ func sharingService(_ service: NSSharingService, didStopSharing share: CKShare) {+ parent.onFailure("Sharing has stopped. The family’s access has changed.")+ }+ }+}+#endif
diff --git a/Halo Family/Halo Family/FamilyWorkspaceView.swift b/Halo Family/Halo Family/FamilyWorkspaceView.swiftnew file mode 100644index 0000000..d174b34--- /dev/null+++ b/Halo Family/Halo Family/FamilyWorkspaceView.swift @@ -0,0 +1,135 @@+import Combine+import CoreData+import SwiftUI++nonisolated private enum WorkspaceSection: String, CaseIterable, Identifiable, Hashable, Sendable {+ case children, people, contexts, events, review+ var id: Self { self }+ var title: String {+ switch self {+ case .children: "Children"+ case .people: "People"+ case .contexts: "Contexts"+ case .events: "Events"+ case .review: "Review"+ }+ }+ var symbol: String {+ switch self {+ case .children: "person.2"+ case .people: "person.crop.circle"+ case .contexts: "square.stack.3d.up"+ case .events: "photo.on.rectangle.angled"+ case .review: "tray"+ }+ }+}++/// Selection and navigation belong to this window. Changing family resets its routes.+struct FamilyWorkspaceView: View {+ let repository: FamilyRepository+ @State private var families: [GraphRow] = []+ @State private var selectedFamilyID: NSManagedObjectID?+ @State private var managingFamily = false+ @State private var failure: String?+ @Environment(\.scenePhase) private var scenePhase++ private var selectedFamily: GraphRow? { families.first { $0.id == selectedFamilyID } }++ var body: some View {+ Group {+ if let family = selectedFamily {+ WorkspaceSections(repository: repository, family: family) { managingFamily = true }+ .id(family.id)+ } else {+ ContentUnavailableView {+ Label("Remember their people", systemImage: "person.2.circle")+ } description: {+ Text("Start a family space, add your children, and capture a name whenever someone new comes up.")+ } actions: {+ Button("Create a family") { managingFamily = true }.buttonStyle(.borderedProminent)+ }+ }+ }+ .task { reload() }+ .safeAreaInset(edge: .bottom) {+ if let issue = repository.stack.issue {+ VStack {+ Text(issue)+ Button("Retry data refresh") { Task { await repository.stack.refreshHistory() } }+ }+ .padding().background(.regularMaterial)+ }+ if let issue = repository.stack.syncIssue {+ Label(issue, systemImage: "icloud.slash").padding().background(.regularMaterial)+ }+ }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in reload() }+ .onChange(of: scenePhase) {+ if scenePhase == .active { Task { await repository.stack.refreshHistory(); reload() } }+ }+ .sheet(isPresented: $managingFamily, onDismiss: reload) {+ FamilyManagerView(repository: repository, selectedFamilyID: $selectedFamilyID)+ }+ .graphFailure($failure)+ }++ private func reload() {+ do {+ families = try repository.families()+ if !families.contains(where: { $0.id == selectedFamilyID }) { selectedFamilyID = families.first?.id }+ } catch { failure = error.localizedDescription }+ }+}++private struct WorkspaceSections: View {+ let repository: FamilyRepository+ let family: GraphRow+ let manageFamily: () -> Void+ #if os(macOS)+ @State private var selection: WorkspaceSection? = .children+ #else+ @State private var selection: WorkspaceSection = .children+ #endif++ var body: some View {+ #if os(macOS)+ NavigationSplitView {+ List(WorkspaceSection.allCases, selection: $selection) { section in+ Label(section.title, systemImage: section.symbol).tag(section)+ }+ .navigationTitle(family.name)+ .toolbar { familyButton }+ } detail: {+ NavigationStack { destination(selection ?? .children).toolbar { familyButton } }+ .id(selection)+ }+ #else+ TabView(selection: $selection) {+ ForEach(WorkspaceSection.allCases) { section in+ Tab(section.title, systemImage: section.symbol, value: section) {+ NavigationStack { destination(section).toolbar { familyButton } }+ }+ }+ }+ #endif+ }++ private var familyButton: some ToolbarContent {+ ToolbarItem(placement: .automatic) {+ Button(action: manageFamily) { Label(family.name, systemImage: "house") }+ .accessibilityIdentifier("workspace.family")+ }+ }++ @ViewBuilder private func destination(_ section: WorkspaceSection) -> some View {+ switch section {+ case .children: ChildOverviewView(repository: repository, familyID: family.id)+ case .people: PeopleView(repository: repository, familyID: family.id)+ case .contexts: ContextsView(repository: repository, familyID: family.id)+ case .events: EventsView(repository: repository, familyID: family.id)+ case .review: FamilyReviewView(repository: repository, familyID: family.id)+ }+ }+}
diff --git a/Halo Family/Halo Family/FormComponents.swift b/Halo Family/Halo Family/FormComponents.swiftnew file mode 100644index 0000000..aa22aea--- /dev/null+++ b/Halo Family/Halo Family/FormComponents.swift @@ -0,0 +1,81 @@+import SwiftUI++struct MemoryForm<Content: View>: View {+ @ViewBuilder var content: () -> Content+ var body: some View {+ #if os(macOS)+ ScrollView { VStack(alignment: .leading, spacing: 24, content: content).padding(24).frame(maxWidth: 750) }+ #else+ Form(content: content)+ #endif+ }+}++struct MemorySection<Content: View>: View {+ let title: String+ @ViewBuilder var content: () -> Content+ init(_ title: String, @ViewBuilder content: @escaping () -> Content) { self.title = title; self.content = content }+ var body: some View {+ #if os(macOS)+ MacFormSection(title, content: content)+ #else+ Section(title, content: content)+ #endif+ }+}++struct MemoryField<Content: View>: View {+ let title: String+ @ViewBuilder var content: () -> Content+ init(_ title: String, @ViewBuilder content: @escaping () -> Content) { self.title = title; self.content = content }+ var body: some View {+ #if os(macOS)+ Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16) {+ MacFormRow(title) { content().labelsHidden() }+ }+ #else+ content()+ #endif+ }+}++#if os(macOS)+struct MacFormRow<Content: View>: View {+ let label: String+ @ViewBuilder var content: () -> Content++ init(_ label: String, @ViewBuilder content: @escaping () -> Content) {+ self.label = label+ self.content = content+ }++ var body: some View {+ GridRow {+ Text(label).foregroundStyle(.secondary).frame(width: 100, alignment: .trailing)+ content().frame(maxWidth: .infinity, alignment: .leading)+ }+ }+}++struct MacFormSection<Content: View>: View {+ let title: String+ @ViewBuilder var content: () -> Content++ init(_ title: String, @ViewBuilder content: @escaping () -> Content) {+ self.title = title+ self.content = content+ }++ var body: some View {+ VStack(alignment: .leading, spacing: 12) {+ Text(title).font(.headline)+ VStack(alignment: .leading, spacing: 14, content: content)+ .padding(18)+ .background {+ RoundedRectangle(cornerRadius: 16).fill(.clear)+ .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 16))+ }+ }+ }+}+#endif
diff --git a/Halo Family/Halo Family/MergeConflictReviewView.swift b/Halo Family/Halo Family/MergeConflictReviewView.swiftnew file mode 100644index 0000000..021a25a--- /dev/null+++ b/Halo Family/Halo Family/MergeConflictReviewView.swift @@ -0,0 +1,78 @@+import Combine+import CoreData+import SwiftUI++struct MergeConflictReviewView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ @State private var conflicts: [PersonMergeConflict] = []+ @State private var lateAccounts: [LateMergeAccounts] = []+ @State private var confirming: PersonMergeConflict?+ @State private var showingConfirmation = false+ @State private var failure: String?++ var body: some View {+ MemoryForm {+ ForEach(conflicts) { conflict in+ MemorySection("Competing merge accounts") {+ ForEach(conflict.people) { person in+ NavigationLink(person.name) {+ PersonDetailView(repository: repository, familyID: familyID, personID: person.id)+ }+ }+ Text("These merges disagree or form a circular alias. Both identities and all merge accounts are retained.")+ Text("Recovery shows the separate people again and marks their details for review. " ++ "It keeps the currently saved notes, photos and references. Earlier values remain in merge history; " ++ "this recovery does not undo or overwrite intervening edits.")+ Button("Show separate people for review") { confirming = conflict; showingConfirmation = true }+ }+ }+ ForEach(lateAccounts) { account in+ MemorySection("Earlier relationship changed: \(account.name)") {+ Text("Additional or changed accounts arrived after the merge. The original records remain in history.")+ NavigationLink("Read earlier relationship accounts") {+ ConnectionDetailView(repository: repository, familyID: familyID,+ connection: GraphRow(id: account.id, name: account.name), readOnly: true)+ }+ if account.targetID != nil {+ Text("Bring these accounts into the kept relationship as alternatives, then choose values in Review.")+ Button("Bring accounts into the kept relationship for review") { review(account) }+ } else {+ Text("This relationship was archived because it would describe the child knowing themselves. " ++ "The additional accounts can stay in history without creating a current self-relationship.")+ Button("Keep these accounts in history") { review(account) }+ }+ }+ }+ if conflicts.isEmpty && lateAccounts.isEmpty { Text("No competing merges or late relationship accounts need review.") }+ MemorySection("History") {+ NavigationLink("Read all merge history") { PersonMergeHistoryView(repository: repository, familyID: familyID) }+ }+ }+ .navigationTitle("Review merges")+ .task { reload() }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in reload() }+ .confirmationDialog("Show separate identities and keep current references?", isPresented: $showingConfirmation) {+ Button("Recover separate people") {+ guard let preview = confirming else { return }+ do { try repository.recoverCompetingMerges(preview); confirming = nil; reload() } catch {+ failure = error.localizedDescription+ }+ }+ }+ .graphFailure($failure)+ }++ private func review(_ account: LateMergeAccounts) {+ do { try repository.reviewLateMergeAccounts(account); reload() } catch { failure = error.localizedDescription }+ }++ private func reload() {+ do {+ let conflicts = try repository.mergeConflicts(in: familyID)+ let accounts = try repository.lateMergeAccounts(in: familyID)+ self.conflicts = conflicts; lateAccounts = accounts+ } catch { failure = error.localizedDescription }+ }+}
diff --git a/Halo Family/Halo Family/MyApp.swift b/Halo Family/Halo Family/MyApp.swiftindex e047ba3..27ff629 100644--- a/Halo Family/Halo Family/MyApp.swift +++ b/Halo Family/Halo Family/MyApp.swift @@ -1,6 +1,12 @@ import SwiftUI @main struct MyApp: App {+ #if os(iOS)+ @UIApplicationDelegateAdaptor(HaloApplicationDelegate.self) private var delegate+ #elseif os(macOS)+ @NSApplicationDelegateAdaptor(HaloApplicationDelegate.self) private var delegate+ #endif+ var body: some Scene { WindowGroup { ContentView()
diff --git a/Halo Family/Halo Family/PeopleView.swift b/Halo Family/Halo Family/PeopleView.swiftnew file mode 100644index 0000000..0cac35a--- /dev/null+++ b/Halo Family/Halo Family/PeopleView.swift @@ -0,0 +1,204 @@+import CoreData+import SwiftUI+import Combine++struct PeopleView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ @State private var people: [GraphRow] = []+ @State private var search = ""+ @State private var reviewOnly = false+ @State private var name = ""+ @State private var failure: String?++ var body: some View {+ Form {+ Section {+ Toggle("Needs review only", isOn: $reviewOnly)+ ForEach(people) { person in+ NavigationLink(person.name) {+ PersonDetailView(repository: repository, familyID: familyID, personID: person.id)+ }+ }+ if people.isEmpty { Text("No people match this view.").foregroundStyle(.secondary) }+ }+ Section("Add a person") {+ TextField("Name or description", text: $name)+ Button("Add person") {+ perform {+ _ = try repository.addPerson(name: name, familyID: familyID)+ name = ""+ }+ }+ .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ Section("History") {+ NavigationLink("Merge history") { PersonMergeHistoryView(repository: repository, familyID: familyID) }+ }+ }+ .navigationTitle("People")+ .searchable(text: $search, prompt: "Search names")+ .task { perform {} }+ .onChange(of: search) { perform {} }+ .onChange(of: reviewOnly) { perform {} }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in+ perform {}+ }+ .graphFailure($failure)+ }++ private func perform(_ action: () throws -> Void) {+ do {+ try action()+ people = try repository.people(in: familyID, search: search, needsReview: reviewOnly)+ } catch { failure = error.localizedDescription }+ }+}++struct PersonDetailView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let personID: NSManagedObjectID+ @State private var name = ""+ @State private var notes = ""+ @State private var needsReview = false+ @State private var children: [GraphRow] = []+ @State private var connections: [GraphRow] = []+ @State private var childID: NSManagedObjectID?+ @State private var failure: String?+ @State private var loaded = false+ @State private var baseline: PersonDetail?+ @State private var photoID: NSManagedObjectID?+ @State private var sensitive: SensitiveSnapshot?+ @State private var editingSensitive = false+ @State private var events: [EventRow] = []+ @State private var merging = false+ @State private var mergedIntoID: NSManagedObjectID?+ @State private var mergeConflict = false++ var body: some View {+ MemoryForm {+ if mergeConflict {+ MemorySection("Competing merges") {+ Text("Different merge accounts involve this person. Review them before making further changes.")+ NavigationLink("Review merges") { MergeConflictReviewView(repository: repository, familyID: familyID) }+ }+ }+ if let mergedIntoID {+ MemorySection("Merged record") {+ Text("This earlier record is retained in merge history.")+ NavigationLink("Open the kept person") {+ PersonDetailView(repository: repository, familyID: familyID, personID: mergedIntoID)+ }+ }+ }+ MemorySection("Person") {+ if let photoID { AssetThumbnail(assets: AssetRepository(stack: repository.stack), assetID: photoID).id(photoID) }+ TextField("Name or description", text: $name)+ TextField("Notes", text: $notes, axis: .vertical)+ Toggle("Needs review", isOn: $needsReview)+ Button("Save details") {+ guard let baseline else { return }+ perform {+ try repository.updatePerson(personID, name: name, notes: notes, needsReview: needsReview, expected: baseline)+ let saved = try repository.person(personID)+ self.baseline = saved+ name = saved.name+ notes = saved.notes+ needsReview = saved.needsReview+ }+ }+ .disabled(!loaded || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ DisclosureGroup("Photo") {+ PhotoImportControls(repository: repository, personID: personID)+ if photoID != nil {+ Button("Remove primary photo") { perform { try repository.removePhoto(personID) } }+ }+ }+ }+ .disabled(mergedIntoID != nil || mergeConflict)+ MemorySection("Relationships") {+ NavigationLink("Family knowledge and address labels") {+ FamilyKnowledgeView(repository: repository, familyID: familyID, personID: personID)+ }+ ForEach(connections) { connection in+ NavigationLink("Known by \(connection.name)") {+ ConnectionDetailView(repository: repository, familyID: familyID,+ connection: GraphRow(id: connection.id, name: name))+ }+ }+ Picker("Child", selection: $childID) {+ Text("Choose a child").tag(nil as NSManagedObjectID?)+ ForEach(children) { Text($0.name).tag(Optional($0.id)) }+ }+ Button("Connect existing person") {+ guard let childID else { return }+ perform { _ = try repository.connect(personID: personID, childID: childID) }+ }+ .disabled(childID == nil)+ }+ .disabled(mergedIntoID != nil || mergeConflict)+ if !events.isEmpty {+ MemorySection("Social event history") {+ ForEach(events) { event in+ NavigationLink(event.label) { EventDetailView(repository: repository, familyID: familyID, eventID: event.id) }+ }+ }+ }+ }+ .navigationTitle(name.isEmpty ? "Person" : name)+ .toolbar {+ Menu {+ if mergedIntoID == nil && !mergeConflict {+ Button("Sensitive details") {+ perform { sensitive = try repository.sensitiveDetails(personID); editingSensitive = true }+ }+ Button("Merge with another person") { merging = true }+ }+ } label: { Image(systemName: "ellipsis") }+ }+ .sheet(isPresented: $editingSensitive, onDismiss: { perform {} }, content: {+ if let sensitive { SensitiveDetailsView(repository: repository, personID: personID, initial: sensitive) }+ })+ .sheet(isPresented: $merging, onDismiss: { perform {} }, content: {+ PersonMergeView(repository: repository, familyID: familyID, sourceID: personID)+ })+ .task {+ perform {}+ }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in perform {} }+ .graphFailure($failure)+ }++ private func perform(_ action: () throws -> Void) {+ do {+ try action()+ let current = try repository.person(personID)+ if baseline == nil || (name == baseline?.name && notes == baseline?.notes && needsReview == baseline?.needsReview) {+ name = current.name+ notes = current.notes+ needsReview = current.needsReview+ baseline = current+ }+ children = try repository.children(in: familyID)+ connections = try repository.connections(to: personID)+ photoID = try repository.primaryPhoto(personID)+ events = try repository.socialEvents(for: personID)+ mergeConflict = try repository.mergeConflicts(in: familyID).contains { $0.people.contains { $0.id == personID } }+ mergedIntoID = mergeConflict ? nil : try repository.mergedPersonTarget(personID)+ loaded = true+ } catch { failure = error.localizedDescription }+ }+}++extension View {+ func graphFailure(_ failure: Binding<String?>) -> some View {+ alert("Couldn’t save or load", isPresented: Binding(+ get: { failure.wrappedValue != nil }, set: { if !$0 { failure.wrappedValue = nil } }+ )) {+ Button("OK") { failure.wrappedValue = nil }+ } message: { Text(failure.wrappedValue ?? "") }+ }+}
diff --git a/Halo Family/Halo Family/Persistence/AssetRepository.swift b/Halo Family/Halo Family/Persistence/AssetRepository.swiftindex 93540c2..c45c162 100644--- a/Halo Family/Halo Family/Persistence/AssetRepository.swift +++ b/Halo Family/Halo Family/Persistence/AssetRepository.swift @@ -1,24 +1,29 @@ import CoreData import Foundation -/// Encoded payloads stay Core Data-managed. Decoding and product-specific size policy belong to future import features.+/// Encoded payloads stay Core Data-managed; import decoding and saves run off the main thread. @MainActor final class AssetRepository { private let stack: PersistenceStack+ var container: NSPersistentContainer { stack.container } init(stack: PersistenceStack) { self.stack = stack } func save(data: Data, familyID: NSManagedObjectID, replacing assetID: NSManagedObjectID? = nil) async throws -> NSManagedObjectID {+ guard stack.role != .widget else { throw GraphError.readOnly }+ let cloud = stack.container as? NSPersistentCloudKitContainer let context = stack.container.newBackgroundContext() context.transactionAuthor = stack.role.rawValue- return try await context.perform {+ let result = try await context.perform { guard familyID.entity.name == "FamilySpace", !familyID.isTemporaryID else { throw GraphError.invalidReference } let family = try context.existingObject(with: familyID) guard let store = family.objectID.persistentStore else { throw GraphError.invalidReference }+ try Self.requireEditable(family, cloud: cloud) let asset: NSManagedObject if let assetID { guard assetID.entity.name == "Asset", !assetID.isTemporaryID else { throw GraphError.invalidReference } asset = try context.existingObject(with: assetID)+ try Self.requireEditable(asset, cloud: cloud) guard let owner = asset.value(forKey: "familySpace") as? NSManagedObject, owner.objectID == familyID, asset.objectID.persistentStore == store else { throw GraphError.differentFamily } } else {@@ -30,8 +35,109 @@ final class AssetRepository { } asset.setValue(data, forKey: "data") asset.setValue(Date(), forKey: "modifiedAt")+ if asset.entity.attributesByName["contentRevision"] != nil { asset.setValue(UUID(), forKey: "contentRevision") }+ let inserted = Array(context.insertedObjects)+ let updated = Array(context.updatedObjects) try context.save()- return asset.objectID+ return (asset.objectID, inserted.map(\.objectID), updated.map(\.objectID))+ }+ publish(inserted: result.1, updated: result.2)+ return result.0+ }++ func importPhoto(_ data: Data, filename: String, personID: NSManagedObjectID) async throws -> NSManagedObjectID {+ guard stack.role != .widget else { throw GraphError.readOnly }+ let prepared = try await Task.detached(priority: .userInitiated) {+ try ImageImport.prepare(data, filename: filename, photo: true)+ }.value+ return try await importAsset(prepared, ownerID: personID, photo: true)+ }++ func importAttachment(_ data: Data, filename: String, eventID: NSManagedObjectID) async throws -> NSManagedObjectID {+ guard stack.role != .widget else { throw GraphError.readOnly }+ let prepared = try await Task.detached(priority: .userInitiated) {+ try ImageImport.prepare(data, filename: filename, photo: false)+ }.value+ return try await importAsset(prepared, ownerID: eventID, photo: false)+ }++ private func importAsset(_ prepared: PreparedAsset, ownerID: NSManagedObjectID, photo: Bool) async throws -> NSManagedObjectID {+ guard stack.role != .widget else { throw GraphError.readOnly }+ try Task.checkCancellation()+ let cloud = stack.container as? NSPersistentCloudKitContainer+ let context = stack.container.newBackgroundContext()+ context.transactionAuthor = stack.role.rawValue+ let result = try await context.perform {+ guard ownerID.entity.name == (photo ? "Person" : "Event"), !ownerID.isTemporaryID else { throw GraphError.invalidReference }+ let owner = try context.existingObject(with: ownerID)+ try Self.requireEditable(owner, cloud: cloud)+ if photo, owner.value(forKey: "mergedInto") != nil { throw MergeError.changed }+ guard let family = owner.value(forKey: "familySpace") as? NSManagedObject,+ let store = family.objectID.persistentStore, store == ownerID.persistentStore else { throw GraphError.differentFamily }+ try Self.requireEditable(family, cloud: cloud)+ let asset = NSEntityDescription.insertNewObject(forEntityName: "Asset", into: context)+ context.assign(asset, to: store)+ asset.setValue(UUID(), forKey: "id")+ asset.setValue(family, forKey: "familySpace")+ asset.setValue(prepared.data, forKey: "data")+ asset.setValue(prepared.filename, forKey: "filename")+ asset.setValue(prepared.contentType, forKey: "contentType")+ asset.setValue(prepared.data.count, forKey: "byteCount")+ asset.setValue(prepared.width, forKey: "pixelWidth")+ asset.setValue(prepared.height, forKey: "pixelHeight")+ asset.setValue(photo ? "personPhoto" : "eventAttachment", forKey: "kind")+ asset.setValue(Date(), forKey: "createdAt")+ asset.setValue(Date(), forKey: "modifiedAt")+ asset.setValue(UUID(), forKey: "contentRevision")+ if photo {+ owner.setValue(asset, forKey: "primaryPhoto")+ owner.setValue(Date(), forKey: "modifiedAt")+ } else {+ let attachment = NSEntityDescription.insertNewObject(forEntityName: "EventAttachment", into: context)+ context.assign(attachment, to: store)+ attachment.setValue(UUID(), forKey: "id")+ attachment.setValue(family, forKey: "familySpace")+ attachment.setValue(owner, forKey: "event")+ attachment.setValue(asset, forKey: "asset")+ attachment.setValue(prepared.filename, forKey: "title")+ attachment.setValue("document", forKey: "kind")+ attachment.setValue(Date(), forKey: "createdAt")+ }+ let inserted = Array(context.insertedObjects)+ let updated = Array(context.updatedObjects)+ try Task.checkCancellation()+ try context.save()+ return (asset.objectID, inserted.map(\.objectID), updated.map(\.objectID))+ }+ publish(inserted: result.1, updated: result.2)+ return result.0+ }++ private func publish(inserted: [NSManagedObjectID], updated: [NSManagedObjectID]) {+ NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [NSInsertedObjectsKey: inserted, NSUpdatedObjectsKey: updated],+ into: [stack.container.viewContext])+ NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: stack.container)+ }++ /// Fetch metadata alone so a cached thumbnail does not first materialize the full binary payload.+ func revision(for assetID: NSManagedObjectID) async throws -> String {+ let context = stack.container.newBackgroundContext()+ return try await context.perform {+ guard assetID.entity.name == "Asset", !assetID.isTemporaryID else { throw GraphError.invalidReference }+ let request = NSFetchRequest<NSDictionary>(entityName: "Asset")+ request.resultType = .dictionaryResultType+ request.predicate = NSPredicate(format: "SELF == %@", assetID)+ request.propertiesToFetch = ["contentRevision", "modifiedAt"]+ request.fetchLimit = 1+ guard let metadata = try context.fetch(request).first else { throw GraphError.invalidReference }+ return "\(assetID.uriRepresentation().absoluteString)|\(metadata["contentRevision"] ?? "legacy")|\(metadata["modifiedAt"] ?? "")"+ }+ }++ nonisolated private static func requireEditable(_ object: NSManagedObject, cloud: NSPersistentCloudKitContainer?) throws {+ guard !object.isDeleted else { throw GraphError.invalidReference }+ if let cloud {+ guard cloud.canUpdateRecord(forManagedObjectWith: object.objectID) else { throw GraphError.readOnly } } }
diff --git a/Halo Family/Halo Family/Persistence/ConnectionStateRepository.swift b/Halo Family/Halo Family/Persistence/ConnectionStateRepository.swiftnew file mode 100644index 0000000..98c16cf--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ConnectionStateRepository.swift @@ -0,0 +1,205 @@+import CoreData+import Foundation++nonisolated enum ClosenessChoice: Int16, CaseIterable, Identifiable, Sendable {+ case metOnce = 1+ case knowThem = 3+ case friend = 5+ case goodFriend = 7+ case bff = 10++ var id: Int16 { rawValue }+ var label: String {+ switch self {+ case .metOnce: "Met once"+ case .knowThem: "Know them"+ case .friend: "Friend"+ case .goodFriend: "Good friend"+ case .bff: "BFF"+ }+ }+}++nonisolated enum ConnectionState: String, CaseIterable, Sendable {+ case active+ case lostContact++ var label: String { self == .active ? "Active" : "Lost contact" }+}++struct ConnectionStateSnapshot {+ let closenessValue: Int16?+ let closeness: ClosenessChoice?+ let closenessID: NSManagedObjectID?+ let closenessNeedsReview: Bool+ let state: ConnectionState+ let statusID: NSManagedObjectID?+ let statusNeedsReview: Bool+ let note: String+}++struct StatePeriodRow: Identifiable {+ let id: NSManagedObjectID+ let value: Int16?+ let state: ConnectionState?+ let note: String+ let startedAt: Date?+}++@MainActor+extension FamilyRepository {+ func currentStatePeriods(_ connectionID: NSManagedObjectID, closeness: Bool) throws -> [StatePeriodRow] {+ let connection = try readable(connectionID, entity: "Connection")+ return try currentPeriods(closeness ? "ConnectionClosenessPeriod" : "ConnectionStatusPeriod",+ connection: connection, in: stack.container.viewContext).map {+ StatePeriodRow(id: $0.objectID, value: closeness ? try closenessValue($0) : nil,+ state: closeness ? nil : try statusValue($0),+ note: closeness ? "" : $0.value(forKey: "note") as? String ?? "",+ startedAt: $0.value(forKey: "startedAt") as? Date)+ }+ }++ func resolveCloseness(_ value: Int16, connectionID: NSManagedObjectID, reviewed: Set<NSManagedObjectID>) throws {+ guard (1...10).contains(value) else { throw GraphError.invalidState }+ try resolvePeriods("ConnectionClosenessPeriod", connectionID: connectionID, reviewed: reviewed) {+ $0.setValue(value, forKey: "value")+ }+ }++ func resolveStatus(_ state: ConnectionState, note: String, connectionID: NSManagedObjectID,+ reviewed: Set<NSManagedObjectID>) throws {+ try resolvePeriods("ConnectionStatusPeriod", connectionID: connectionID, reviewed: reviewed) {+ $0.setValue(state.rawValue, forKey: "state")+ $0.setValue(note.trimmingCharacters(in: .whitespacesAndNewlines), forKey: "note")+ }+ }++ private func resolvePeriods(_ entity: String, connectionID: NSManagedObjectID, reviewed: Set<NSManagedObjectID>,+ configure: (NSManagedObject) -> Void) throws {+ _ = try write { context in+ let connection = try record(connectionID, entity: "Connection", in: context)+ let periods = try currentPeriods(entity, connection: connection, in: context)+ guard periods.count > 1, Set(periods.map(\.objectID)) == reviewed else { throw GraphError.stateChanged }+ let fresh = try newPeriod(entity, connection: connection, previous: nil, in: context)+ let now = max(Date(), periods.compactMap { $0.value(forKey: "startedAt") as? Date }.max() ?? Date())+ for period in periods { period.setValue(now, forKey: "endedAt") }+ fresh.setValue(now, forKey: "startedAt")+ configure(fresh)+ return fresh+ }+ }+ func connectionState(_ connectionID: NSManagedObjectID) throws -> ConnectionStateSnapshot {+ guard let snapshot = try connectionStates([connectionID])[connectionID] else { throw GraphError.invalidReference }+ return snapshot+ }++ func connectionStates(_ connectionIDs: [NSManagedObjectID]) throws -> [NSManagedObjectID: ConnectionStateSnapshot] {+ guard !connectionIDs.isEmpty else { return [:] }+ let connections = try Set(connectionIDs).map { try readable($0, entity: "Connection") }+ let context = stack.container.viewContext+ let closeness = try groupedPeriods("ConnectionClosenessPeriod", connections: connections, in: context)+ let statuses = try groupedPeriods("ConnectionStatusPeriod", connections: connections, in: context)+ return try Dictionary(uniqueKeysWithValues: connections.map { connection in+ (connection.objectID, try stateSnapshot(connection: connection, closeness: closeness[connection.objectID] ?? [],+ statuses: statuses[connection.objectID] ?? []))+ })+ }++ private func stateSnapshot(connection: NSManagedObject, closeness: [NSManagedObject],+ statuses: [NSManagedObject]) throws -> ConnectionStateSnapshot {+ let family = try family(of: connection)+ for period in closeness + statuses { try requireSameFamily(period, family: family) }+ let value = try closeness.count == 1 ? closeness.first.map(closenessValue) : nil+ let state = try statuses.count == 1 ? statuses.first.map(statusValue) ?? .active : .active+ return ConnectionStateSnapshot(closenessValue: value, closeness: value.flatMap(ClosenessChoice.init(rawValue:)),+ closenessID: closeness.count == 1 ? closeness.first?.objectID : nil,+ closenessNeedsReview: closeness.count > 1,+ state: state,+ statusID: statuses.count == 1 ? statuses.first?.objectID : nil,+ statusNeedsReview: statuses.count > 1,+ note: statuses.count == 1 ? statuses.first?.value(forKey: "note") as? String ?? "" : "")+ }++ func setCloseness(_ choice: ClosenessChoice, connectionID: NSManagedObjectID, expectedID: NSManagedObjectID?) throws {+ try setClosenessValue(choice.rawValue, connectionID: connectionID, expectedID: expectedID)+ }++ func setClosenessValue(_ value: Int16, connectionID: NSManagedObjectID, expectedID: NSManagedObjectID?) throws {+ guard (1...10).contains(value) else { throw GraphError.invalidState }+ _ = try write { context in+ let connection = try record(connectionID, entity: "Connection", in: context)+ let periods = try checkedPeriods("ConnectionClosenessPeriod", connection: connection, expectedID: expectedID, in: context)+ if (periods.first?.value(forKey: "value") as? NSNumber)?.int16Value == value { return connection }+ let period = try newPeriod("ConnectionClosenessPeriod", connection: connection, previous: periods.first, in: context)+ period.setValue(value, forKey: "value")+ return period+ }+ }++ func setConnectionState(_ state: ConnectionState, note: String, connectionID: NSManagedObjectID,+ expectedID: NSManagedObjectID?) throws {+ let note = note.trimmingCharacters(in: .whitespacesAndNewlines)+ _ = try write { context in+ let connection = try record(connectionID, entity: "Connection", in: context)+ let periods = try checkedPeriods("ConnectionStatusPeriod", connection: connection, expectedID: expectedID, in: context)+ if periods.first?.value(forKey: "state") as? String == state.rawValue,+ (periods.first?.value(forKey: "note") as? String ?? "") == note { return connection }+ let period = try newPeriod("ConnectionStatusPeriod", connection: connection, previous: periods.first, in: context)+ period.setValue(state.rawValue, forKey: "state")+ period.setValue(note.isEmpty ? nil : note, forKey: "note")+ return period+ }+ }++ private func currentPeriods(_ entity: String, connection: NSManagedObject,+ in context: NSManagedObjectContext) throws -> [NSManagedObject] {+ let request = NSFetchRequest<NSManagedObject>(entityName: entity)+ request.predicate = NSPredicate(format: "connection == %@ AND endedAt == nil", connection)+ let periods = try context.fetch(request)+ let family = try family(of: connection)+ for period in periods { try requireSameFamily(period, family: family) }+ return periods+ }++ private func groupedPeriods(_ entity: String, connections: [NSManagedObject],+ in context: NSManagedObjectContext) throws -> [NSManagedObjectID: [NSManagedObject]] {+ let request = NSFetchRequest<NSManagedObject>(entityName: entity)+ request.predicate = NSPredicate(format: "connection IN %@ AND endedAt == nil", connections as NSArray)+ request.relationshipKeyPathsForPrefetching = ["connection", "familySpace"]+ return Dictionary(grouping: try context.fetch(request)) {+ ($0.value(forKey: "connection") as? NSManagedObject)?.objectID ?? $0.objectID+ }+ }++ private func closenessValue(_ period: NSManagedObject) throws -> Int16 {+ guard let number = period.value(forKey: "value") as? NSNumber,+ (1...10).contains(number.int16Value) else { throw GraphError.invalidState }+ return number.int16Value+ }++ private func statusValue(_ period: NSManagedObject) throws -> ConnectionState {+ guard let raw = period.value(forKey: "state") as? String,+ let state = ConnectionState(rawValue: raw) else { throw GraphError.invalidState }+ return state+ }++ private func checkedPeriods(_ entity: String, connection: NSManagedObject, expectedID: NSManagedObjectID?,+ in context: NSManagedObjectContext) throws -> [NSManagedObject] {+ let periods = try currentPeriods(entity, connection: connection, in: context)+ guard periods.count <= 1 else { throw GraphError.stateConflict }+ guard periods.first?.objectID == expectedID else { throw GraphError.stateChanged }+ return periods+ }++ private func newPeriod(_ entity: String, connection: NSManagedObject, previous: NSManagedObject?,+ in context: NSManagedObjectContext) throws -> NSManagedObject {+ let family = try family(of: connection)+ let now = max(Date(), previous?.value(forKey: "startedAt") as? Date ?? Date())+ previous?.setValue(now, forKey: "endedAt")+ let period = insert(entity, in: context, store: try owningStore(of: family))+ period.setValue(family, forKey: "familySpace")+ period.setValue(connection, forKey: "connection")+ period.setValue(now, forKey: "startedAt")+ return period+ }+}
diff --git a/Halo Family/Halo Family/Persistence/EventMemoryRepository.swift b/Halo Family/Halo Family/Persistence/EventMemoryRepository.swiftnew file mode 100644index 0000000..74a5e93--- /dev/null+++ b/Halo Family/Halo Family/Persistence/EventMemoryRepository.swift @@ -0,0 +1,249 @@+import CoreData+import Foundation++nonisolated enum InvitationState: String, CaseIterable, Sendable {+ case unknown, considering, intendToInvite, invited, accepted, declined+ var label: String {+ switch self {+ case .unknown: "Not recorded"+ case .considering: "Considering"+ case .intendToInvite: "Intend to invite"+ case .invited: "Invited"+ case .accepted: "Accepted"+ case .declined: "Declined"+ }+ }+}++nonisolated enum AttendanceState: String, CaseIterable, Sendable {+ case unknown, attended, didNotAttend+ var label: String {+ switch self {+ case .unknown: "Not recorded"+ case .attended: "Attended"+ case .didNotAttend: "Did not attend"+ }+ }+}++struct ParticipantRow: Identifiable, Equatable {+ let id: NSManagedObjectID+ let personID: NSManagedObjectID+ let name: String+ let roles: Set<String>+ let invitation: InvitationState+ let attendance: AttendanceState+ let note: String+}++struct AttachmentRow: Identifiable {+ let id: NSManagedObjectID+ let assetID: NSManagedObjectID+ let title: String+ let contentType: String+}++struct GiftRow: Identifiable {+ let id: NSManagedObjectID+ let description: String+ let givers: [String]+ let recipients: [String]+ let note: String+ let attachmentIDs: Set<NSManagedObjectID>+ let giverIDs: Set<NSManagedObjectID>+ let groupIDs: Set<NSManagedObjectID>+ let recipientIDs: Set<NSManagedObjectID>+}++struct GiftInput {+ var description: String+ var givers: Set<NSManagedObjectID> = []+ var groups: Set<NSManagedObjectID> = []+ var recipients: Set<NSManagedObjectID> = []+ var attachments: Set<NSManagedObjectID> = []+ var note = ""+}++@MainActor+extension FamilyRepository {+ func updateEvent(_ eventID: NSManagedObjectID, title: String, date: Date?, type: String = "", notes: String,+ links: (NSManagedObjectID?, NSManagedObjectID?), expected: EventRow) throws {+ let title = try validated(title)+ _ = try write { context in+ let event = try record(eventID, entity: "Event", in: context)+ guard eventRow(event) == expected else { throw MemoryError.changed }+ guard date != nil || expected.date == nil else { throw MemoryError.invalidDate }+ let family = try family(of: event)+ let person = try links.0.map { try record($0, entity: "Person", in: context) }+ let source = try links.1.map { try record($0, entity: "Context", in: context) }+ for link in [person, source].compactMap({ $0 }) { try requireSameFamily(link, family: family) }+ event.setValue(title, forKey: "title")+ event.setValue(date, forKey: "date")+ event.setValue(type.trimmingCharacters(in: .whitespacesAndNewlines), forKey: "type")+ event.setValue(notes, forKey: "notes")+ event.setValue(person, forKey: "subjectPerson")+ event.setValue(source, forKey: "context")+ event.setValue(Date(), forKey: "modifiedAt")+ return event+ }+ }++ func event(_ id: NSManagedObjectID) throws -> EventRow { try eventRow(readable(id, entity: "Event")) }++ func eventRow(_ event: NSManagedObject) -> EventRow {+ EventRow(id: event.objectID, title: event.value(forKey: "title") as? String ?? "Untitled",+ date: event.value(forKey: "date") as? Date, notes: event.value(forKey: "notes") as? String ?? "",+ type: event.value(forKey: "type") as? String ?? "",+ subjectID: (event.value(forKey: "subjectPerson") as? NSManagedObject)?.objectID,+ contextID: (event.value(forKey: "context") as? NSManagedObject)?.objectID,+ isArchived: event.value(forKey: "archivedAt") != nil)+ }++ func archiveEvent(_ id: NSManagedObjectID, archived: Bool) throws {+ _ = try write { context in+ let event = try record(id, entity: "Event", in: context)+ event.setValue(archived ? Date() : nil, forKey: "archivedAt")+ event.setValue(Date(), forKey: "modifiedAt")+ return event+ }+ }++ func saveParticipant(eventID: NSManagedObjectID, personID: NSManagedObjectID, roles: Set<String>,+ invitation: InvitationState, attendance: AttendanceState, note: String = "",+ expected: ParticipantRow? = nil) throws {+ _ = try write { context in+ let event = try record(eventID, entity: "Event", in: context)+ let person = try record(personID, entity: "Person", in: context)+ let family = try family(of: event)+ try requireSameFamily(person, family: family)+ let participant: NSManagedObject+ if let expected {+ participant = try record(expected.id, entity: "EventPerson", in: context)+ guard (participant.value(forKey: "event") as? NSManagedObject)?.objectID == eventID,+ sameParticipation(participantRow(participant), expected),+ expected.personID == personID else { throw MemoryError.changed }+ } else {+ let request = NSFetchRequest<NSManagedObject>(entityName: "EventPerson")+ request.predicate = NSPredicate(format: "event == %@ AND person == %@", event, person)+ guard try context.count(for: request) == 0 else { throw MemoryError.changed }+ participant = insert("EventPerson", in: context, store: try owningStore(of: family))+ participant.setValue(family, forKey: "familySpace")+ participant.setValue(event, forKey: "event")+ participant.setValue(person, forKey: "person")+ }+ let cleaned = Set(roles.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty })+ participant.setValue(String(data: try JSONEncoder().encode(cleaned.sorted()), encoding: .utf8), forKey: "roles")+ participant.setValue(invitation.rawValue, forKey: "invitationState")+ participant.setValue(attendance.rawValue, forKey: "attendanceState")+ participant.setValue(note, forKey: "note")+ return participant+ }+ }++ func participants(_ eventID: NSManagedObjectID) throws -> [ParticipantRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "EventPerson")+ request.predicate = NSPredicate(format: "event == %@", eventID)+ request.sortDescriptors = [NSSortDescriptor(key: "person.displayName", ascending: true)]+ return try stack.container.viewContext.fetch(request).compactMap(participantRow)+ }++ private func participantRow(_ object: NSManagedObject) -> ParticipantRow? {+ guard let person = object.value(forKey: "person") as? NSManagedObject,+ let invitation = InvitationState(rawValue: object.value(forKey: "invitationState") as? String ?? "unknown"),+ let attendance = AttendanceState(rawValue: object.value(forKey: "attendanceState") as? String ?? "unknown") else {+ return nil+ }+ let data = Data((object.value(forKey: "roles") as? String ?? "[]").utf8)+ guard let roles = try? JSONDecoder().decode([String].self, from: data) else { return nil }+ return ParticipantRow(id: object.objectID, personID: person.objectID,+ name: person.value(forKey: "displayName") as? String ?? "Unnamed", roles: Set(roles),+ invitation: invitation, attendance: attendance, note: object.value(forKey: "note") as? String ?? "")+ }++ private func sameParticipation(_ current: ParticipantRow?, _ expected: ParticipantRow) -> Bool {+ guard let current else { return false }+ return current.id == expected.id && current.personID == expected.personID && current.roles == expected.roles &&+ current.invitation == expected.invitation && current.attendance == expected.attendance && current.note == expected.note+ }++ func addGift(eventID: NSManagedObjectID, input: GiftInput) throws {+ try saveGift(eventID: eventID, input: input, expected: nil)+ }++ func saveGift(eventID: NSManagedObjectID, input: GiftInput, expected: GiftRow?) throws {+ let description = try validated(input.description)+ _ = try write { context in+ let event = try record(eventID, entity: "Event", in: context)+ let family = try family(of: event)+ let givers = try input.givers.map { try record($0, entity: "Person", in: context) }+ let groups = try input.groups.map { try record($0, entity: "PersonGroup", in: context) }+ let recipients = try input.recipients.map { try record($0, entity: "Person", in: context) }+ let attachments = try input.attachments.map { try record($0, entity: "EventAttachment", in: context) }+ for object in givers + groups + recipients + attachments { try requireSameFamily(object, family: family) }+ guard attachments.allSatisfy({ ($0.value(forKey: "event") as? NSManagedObject)?.objectID == eventID }) else {+ throw MemoryError.invalidParticipation+ }+ let gift: NSManagedObject+ if let expected {+ gift = try record(expected.id, entity: "GiftRecord", in: context)+ let current = giftRow(gift)+ guard (gift.value(forKey: "event") as? NSManagedObject)?.objectID == eventID,+ current.description == expected.description, current.note == expected.note,+ current.giverIDs == expected.giverIDs, current.groupIDs == expected.groupIDs,+ current.recipientIDs == expected.recipientIDs, current.attachmentIDs == expected.attachmentIDs else {+ throw MemoryError.changed+ }+ } else {+ gift = insert("GiftRecord", in: context, store: try owningStore(of: family))+ gift.setValue(family, forKey: "familySpace")+ gift.setValue(event, forKey: "event")+ }+ gift.setValue(description, forKey: "descriptionText")+ gift.setValue(input.note, forKey: "note")+ gift.setValue(NSSet(array: givers), forKey: "givers")+ gift.setValue(NSSet(array: groups), forKey: "giverGroups")+ gift.setValue(NSSet(array: recipients), forKey: "recipients")+ gift.setValue(NSSet(array: attachments), forKey: "attachments")+ return gift+ }+ }++ func gifts(_ eventID: NSManagedObjectID) throws -> [GiftRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "GiftRecord")+ request.predicate = NSPredicate(format: "event == %@", eventID)+ return try stack.container.viewContext.fetch(request).map(giftRow)+ }++ private func giftRow(_ gift: NSManagedObject) -> GiftRow {+ func objects(_ key: String) -> Set<NSManagedObject> { (gift.value(forKey: key) as? Set<NSManagedObject>) ?? [] }+ func names(_ key: String, _ name: String) -> [String] { objects(key).compactMap { $0.value(forKey: name) as? String }.sorted() }+ return GiftRow(id: gift.objectID, description: gift.value(forKey: "descriptionText") as? String ?? "Gift",+ givers: names("givers", "displayName") + names("giverGroups", "name"),+ recipients: names("recipients", "displayName"), note: gift.value(forKey: "note") as? String ?? "",+ attachmentIDs: Set(objects("attachments").map(\.objectID)), giverIDs: Set(objects("givers").map(\.objectID)),+ groupIDs: Set(objects("giverGroups").map(\.objectID)), recipientIDs: Set(objects("recipients").map(\.objectID)))+ }++ func attachments(_ eventID: NSManagedObjectID) throws -> [AttachmentRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "EventAttachment")+ request.predicate = NSPredicate(format: "event == %@", eventID)+ return try stack.container.viewContext.fetch(request).compactMap {+ guard let asset = $0.value(forKey: "asset") as? NSManagedObject else { return nil }+ return AttachmentRow(id: $0.objectID, assetID: asset.objectID,+ title: $0.value(forKey: "title") as? String ?? "Attachment",+ contentType: asset.value(forKey: "contentType") as? String ?? "")+ }+ }++ func socialEvents(for personID: NSManagedObjectID) throws -> [EventRow] {+ let person = try readable(personID, entity: "Person")+ let family = try family(of: person)+ let participation = NSFetchRequest<NSManagedObject>(entityName: "EventPerson")+ participation.predicate = NSPredicate(format: "person == %@", personID)+ let gifts = NSFetchRequest<NSManagedObject>(entityName: "GiftRecord")+ gifts.predicate = NSPredicate(format: "ANY givers == %@ OR ANY recipients == %@", personID, personID)+ let related = try stack.container.viewContext.fetch(participation) + stack.container.viewContext.fetch(gifts)+ let eventIDs = Set(related.compactMap { ($0.value(forKey: "event") as? NSManagedObject)?.objectID })+ return try events(in: family.objectID).filter { $0.subjectID == personID || eventIDs.contains($0.id) }+ }+}
diff --git a/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift b/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swiftnew file mode 100644index 0000000..4f5d1fe--- /dev/null+++ b/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift @@ -0,0 +1,298 @@+import CoreData+import Foundation++nonisolated struct PartialDate: Equatable, Sendable {+ let year: Int?+ let month: Int?+ let day: Int?++ init(year: Int? = nil, month: Int? = nil, day: Int? = nil) throws {+ guard year != nil || (month == nil && day == nil), month != nil || day == nil,+ year.map({ (1...9999).contains($0) }) ?? true,+ month.map({ (1...12).contains($0) }) ?? true else { throw MemoryError.invalidDate }+ if let year, let month, let day {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(secondsFromGMT: 0)!+ let parts = DateComponents(year: year, month: month, day: day)+ guard let date = calendar.date(from: parts), calendar.dateComponents([.year, .month, .day], from: date) == parts else {+ throw MemoryError.invalidDate+ }+ }+ self.year = year+ self.month = month+ self.day = day+ }++ var label: String {+ [year.map(String.init), month.map { String(format: "%02d", $0) }, day.map { String(format: "%02d", $0) }]+ .compactMap { $0 }.joined(separator: "-")+ }+}++struct SensitiveSnapshot: Equatable {+ let isDeceased: Bool+ let date: PartialDate+}++nonisolated enum StructuralKind: String, CaseIterable, Sendable {+ case parentOf, guardianOf, siblingOf, partnerOf+ var label: String {+ switch self {+ case .parentOf: "Parent of"+ case .guardianOf: "Guardian of"+ case .siblingOf: "Sibling of"+ case .partnerOf: "Partner of"+ }+ }+}++struct FamilyFactRow: Identifiable {+ let id: NSManagedObjectID+ let sourceID: NSManagedObjectID+ let targetID: NSManagedObjectID+ let source: String+ let target: String+ let label: String+ let nature: String+ let startedAt: Date?+ let endedAt: Date?+ let note: String+ let asserted: Bool+ var isArchived = false+}++struct AddressLabelRow: Identifiable, Equatable {+ let id: NSManagedObjectID+ let label: String+ let usedBy: String+ let language: String+ let script: String+ let usedByPersonID: NSManagedObjectID?+ let usedByGroupID: NSManagedObjectID?+}++struct GroupMemberRow: Identifiable {+ let id: NSManagedObjectID+ let personID: NSManagedObjectID+ let name: String+ let role: String+ let startedAt: Date?+ let endedAt: Date?+}++@MainActor+extension FamilyRepository {+ func primaryPhoto(_ personID: NSManagedObjectID) throws -> NSManagedObjectID? {+ (try readable(personID, entity: "Person").value(forKey: "primaryPhoto") as? NSManagedObject)?.objectID+ }++ func removePhoto(_ personID: NSManagedObjectID) throws {+ _ = try write { context in+ let person = try record(personID, entity: "Person", in: context)+ person.setValue(nil, forKey: "primaryPhoto")+ person.setValue(Date(), forKey: "modifiedAt")+ return person+ }+ }+ func sensitiveDetails(_ personID: NSManagedObjectID) throws -> SensitiveSnapshot {+ try sensitiveSnapshot(readable(personID, entity: "Person"))+ }++ func setSensitiveDetails(_ personID: NSManagedObjectID, deceased: Bool, date: PartialDate,+ expected: SensitiveSnapshot) throws {+ guard deceased || date.year == nil else { throw MemoryError.invalidDate }+ _ = try write { context in+ let person = try record(personID, entity: "Person", in: context)+ guard try sensitiveSnapshot(person) == expected else { throw MemoryError.changed }+ person.setValue(deceased, forKey: "isDeceased")+ person.setValue(date.year, forKey: "deathYear")+ person.setValue(date.month, forKey: "deathMonth")+ person.setValue(date.day, forKey: "deathDay")+ person.setValue(Date(), forKey: "modifiedAt")+ return person+ }+ }++ private func sensitiveSnapshot(_ person: NSManagedObject) throws -> SensitiveSnapshot {+ SensitiveSnapshot(isDeceased: person.value(forKey: "isDeceased") as? Bool ?? false,+ date: try PartialDate(year: (person.value(forKey: "deathYear") as? NSNumber)?.intValue,+ month: (person.value(forKey: "deathMonth") as? NSNumber)?.intValue,+ day: (person.value(forKey: "deathDay") as? NSNumber)?.intValue))+ }++ func addFamilyFact(sourceID: NSManagedObjectID, targetID: NSManagedObjectID, kind: StructuralKind?,+ label: String = "", nature: String = "", dates: (Date?, Date?) = (nil, nil), note: String = "") throws {+ let label = label.trimmingCharacters(in: .whitespacesAndNewlines)+ guard sourceID != targetID, kind != nil || !label.isEmpty,+ ["", "biological", "adoptive", "step", "foster", "unknown"].contains(nature) else {+ throw MemoryError.invalidRelationship+ }+ try validateDates(dates.0, dates.1)+ _ = try write { context in+ let source = try record(sourceID, entity: "Person", in: context)+ let target = try record(targetID, entity: "Person", in: context)+ let family = try family(of: source)+ try requireSameFamily(target, family: family)+ let fact = insert(kind == nil ? "RelationshipAssertion" : "PersonRelationship", in: context, store: try owningStore(of: family))+ fact.setValue(family, forKey: "familySpace")+ fact.setValue(source, forKey: "source")+ fact.setValue(target, forKey: "target")+ fact.setValue(kind?.rawValue, forKey: "kind")+ if kind == nil { fact.setValue(label, forKey: "customLabel") }+ if kind != nil { fact.setValue(nature.isEmpty ? nil : nature, forKey: "nature") }+ fact.setValue(note, forKey: "note")+ fact.setValue(dates.0, forKey: "startedAt")+ fact.setValue(dates.1, forKey: "endedAt")+ return fact+ }+ }++ func familyFacts(for personID: NSManagedObjectID, includeArchived: Bool = false) throws -> [FamilyFactRow] {+ try ["PersonRelationship", "RelationshipAssertion"].flatMap { entity in+ let request = NSFetchRequest<NSManagedObject>(entityName: entity)+ let modern = stack.container.managedObjectModel.entitiesByName[entity]?.attributesByName["archivedAt"] != nil+ let pair = NSPredicate(format: "source == %@ OR target == %@", personID, personID)+ request.predicate = modern && !includeArchived ?+ NSCompoundPredicate(andPredicateWithSubpredicates: [pair, NSPredicate(format: "archivedAt == nil")]) : pair+ return try stack.container.viewContext.fetch(request).compactMap { fact -> FamilyFactRow? in+ guard let source = fact.value(forKey: "source") as? NSManagedObject,+ let target = fact.value(forKey: "target") as? NSManagedObject else { return nil }+ let asserted = entity == "RelationshipAssertion"+ return FamilyFactRow(id: fact.objectID, sourceID: source.objectID, targetID: target.objectID,+ source: source.value(forKey: "displayName") as? String ?? "Unnamed",+ target: target.value(forKey: "displayName") as? String ?? "Unnamed",+ label: asserted ? fact.value(forKey: "customLabel") as? String ?? "Relationship" :+ StructuralKind(rawValue: fact.value(forKey: "kind") as? String ?? "")?.label ?? "Relationship",+ nature: asserted ? "" : fact.value(forKey: "nature") as? String ?? "",+ startedAt: fact.value(forKey: "startedAt") as? Date,+ endedAt: fact.value(forKey: "endedAt") as? Date,+ note: fact.value(forKey: "note") as? String ?? "", asserted: asserted,+ isArchived: modern && fact.value(forKey: "archivedAt") != nil)+ }+ }+ }++ func endFamilyFact(_ id: NSManagedObjectID, at date: Date) throws {+ guard let entity = id.entity.name, ["PersonRelationship", "RelationshipAssertion"].contains(entity) else {+ throw GraphError.invalidReference+ }+ _ = try write { context in+ let fact = try record(id, entity: entity, in: context)+ guard fact.value(forKey: "endedAt") == nil else { throw MemoryError.changed }+ try validateDates(fact.value(forKey: "startedAt") as? Date, date)+ fact.setValue(date, forKey: "endedAt")+ return fact+ }+ }++ func groups(in familyID: NSManagedObjectID) throws -> [GraphRow] {+ try rows(entity: "PersonGroup", nameKey: "name", predicate: NSPredicate(format: "familySpace == %@ AND archivedAt == nil",+ familyID))+ }++ func createGroup(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 group = insert("PersonGroup", in: context, store: try owningStore(of: family))+ group.setValue(family, forKey: "familySpace")+ group.setValue(name, forKey: "name")+ group.setValue(Date(), forKey: "createdAt")+ return group+ }+ }++ func addGroupMember(_ personID: NSManagedObjectID, groupID: NSManagedObjectID, role: String = "",+ startedAt: Date? = nil, endedAt: Date? = nil) throws {+ try validateDates(startedAt, endedAt)+ _ = try write { context in+ let person = try record(personID, entity: "Person", in: context)+ let group = try record(groupID, entity: "PersonGroup", in: context)+ let family = try family(of: group)+ try requireSameFamily(person, family: family)+ let membership = insert("GroupMembership", in: context, store: try owningStore(of: family))+ membership.setValue(family, forKey: "familySpace")+ membership.setValue(person, forKey: "person")+ membership.setValue(group, forKey: "group")+ membership.setValue(role, forKey: "role")+ membership.setValue(startedAt, forKey: "startedAt")+ membership.setValue(endedAt, forKey: "endedAt")+ return membership+ }+ }++ func groupMembers(_ groupID: NSManagedObjectID) throws -> [GroupMemberRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "GroupMembership")+ request.predicate = NSPredicate(format: "group == %@", groupID)+ return try stack.container.viewContext.fetch(request).compactMap { link in+ guard let person = link.value(forKey: "person") as? NSManagedObject else { return nil }+ return GroupMemberRow(id: link.objectID, personID: person.objectID,+ name: person.value(forKey: "displayName") as? String ?? "Unnamed",+ role: link.value(forKey: "role") as? String ?? "", startedAt: link.value(forKey: "startedAt") as? Date,+ endedAt: link.value(forKey: "endedAt") as? Date)+ }+ }++ func endGroupMembership(_ id: NSManagedObjectID, at date: Date) throws {+ _ = try write { context in+ let membership = try record(id, entity: "GroupMembership", in: context)+ guard membership.value(forKey: "endedAt") == nil else { throw MemoryError.changed }+ try validateDates(membership.value(forKey: "startedAt") as? Date, date)+ membership.setValue(date, forKey: "endedAt")+ return membership+ }+ }++ func addAddressLabel(targetID: NSManagedObjectID, label: String, usedByPerson: NSManagedObjectID? = nil,+ usedByGroup: NSManagedObjectID? = nil, language: String = "", script: String = "") throws {+ let label = try validated(label)+ guard usedByPerson == nil || usedByGroup == nil else { throw MemoryError.invalidRelationship }+ _ = try write { context in+ let target = try record(targetID, entity: "Person", in: context)+ let family = try family(of: target)+ let person = try usedByPerson.map { try record($0, entity: "Person", in: context) }+ let group = try usedByGroup.map { try record($0, entity: "PersonGroup", in: context) }+ for object in [person, group].compactMap({ $0 }) { try requireSameFamily(object, family: family) }+ let record = insert("AddressLabel", in: context, store: try owningStore(of: family))+ record.setValue(family, forKey: "familySpace")+ record.setValue(target, forKey: "target")+ record.setValue(person, forKey: "usedByPerson")+ record.setValue(group, forKey: "usedByGroup")+ record.setValue(label, forKey: "label")+ record.setValue(language, forKey: "language")+ record.setValue(script, forKey: "script")+ return record+ }+ }++ func addressLabels(for personID: NSManagedObjectID) throws -> [AddressLabelRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "AddressLabel")+ request.predicate = NSPredicate(format: "target == %@", personID)+ return try stack.container.viewContext.fetch(request).map(addressLabelRow)+ }++ private func addressLabelRow(_ object: NSManagedObject) -> AddressLabelRow {+ AddressLabelRow(id: object.objectID, label: object.value(forKey: "label") as? String ?? "",+ usedBy: object.value(forKeyPath: "usedByPerson.displayName") as? String ??+ object.value(forKeyPath: "usedByGroup.name") as? String ?? "General",+ language: object.value(forKey: "language") as? String ?? "",+ script: object.value(forKey: "script") as? String ?? "",+ usedByPersonID: (object.value(forKey: "usedByPerson") as? NSManagedObject)?.objectID,+ usedByGroupID: (object.value(forKey: "usedByGroup") as? NSManagedObject)?.objectID)+ }++ func updateAddressLabel(_ id: NSManagedObjectID, label: String, language: String, script: String, expected: AddressLabelRow) throws {+ let label = try validated(label)+ _ = try write { context in+ let object = try record(id, entity: "AddressLabel", in: context)+ let current = addressLabelRow(object)+ guard current.id == expected.id, current.label == expected.label, current.language == expected.language,+ current.script == expected.script, current.usedByPersonID == expected.usedByPersonID,+ current.usedByGroupID == expected.usedByGroupID else { throw MemoryError.changed }+ object.setValue(label, forKey: "label")+ object.setValue(language, forKey: "language")+ object.setValue(script, forKey: "script")+ return object+ }+ }+}
diff --git a/Halo Family/Halo Family/Persistence/FamilyRepository.swift b/Halo Family/Halo Family/Persistence/FamilyRepository.swiftindex 930c20b..4df9e05 100644--- a/Halo Family/Halo Family/Persistence/FamilyRepository.swift +++ b/Halo Family/Halo Family/Persistence/FamilyRepository.swift @@ -12,6 +12,18 @@ enum GraphError: LocalizedError { case invalidReference case differentFamily case duplicateConnection+ case duplicateMembership+ case invalidDates+ case contextCycle+ case invalidOrigin+ case readOnly+ case originChanged+ case personChanged+ case originConflict+ case stateChanged+ case stateConflict+ case invalidState+ case roleChanged var errorDescription: String? { switch self {@@ -20,6 +32,18 @@ enum GraphError: LocalizedError { case .invalidReference: "This record is no longer available. Select it again." case .differentFamily: "These records must belong to the same family." case .duplicateConnection: "This child already knows this person."+ case .duplicateMembership: "This connection already has a current membership in this context."+ case .invalidDates: "The end date must not be earlier than the start date."+ case .contextCycle: "A context cannot be inside itself or one of its descendants."+ case .invalidOrigin: "Choose one context or event, or enter a description of the first meeting."+ case .readOnly: "You don’t have permission to edit this family."+ case .originChanged: "The first-meeting record changed. Reopen it before saving."+ case .personChanged: "This person’s details changed. Reopen them before saving."+ case .originConflict: "There are different first-meeting accounts. Review them before editing."+ case .stateChanged: "The relationship changed. Reopen it before saving."+ case .stateConflict: "There are overlapping relationship changes. Their history has been retained for review."+ case .invalidState: "A relationship history record could not be read. Its stored value has been preserved."+ case .roleChanged: "This role association changed. Reopen it before saving." } } }@@ -38,12 +62,26 @@ final class FamilyRepository { } func children(in family: NSManagedObjectID) throws -> [GraphRow] {- try rows(entity: "ChildProfile", nameKey: "person.displayName", predicate: NSPredicate(format: "familySpace == %@", family))+ let modern = stack.container.managedObjectModel.entitiesByName["ChildProfile"]?.attributesByName["archivedAt"] != nil+ return try rows(entity: "ChildProfile", nameKey: "person.displayName", predicate: modern ?+ NSPredicate(format: "familySpace == %@ AND archivedAt == nil AND mergedInto == nil", family) :+ NSPredicate(format: "familySpace == %@", family)) } /// Fetch Connections directly rather than depending on inverse relationship invalidation.- func connections(for child: NSManagedObjectID) throws -> [GraphRow] {- try rows(entity: "Connection", nameKey: "person.displayName", predicate: NSPredicate(format: "child == %@", child))+ func connections(for child: NSManagedObjectID, includeDeceased: Bool = true) throws -> [GraphRow] {+ var predicates = [NSPredicate(format: "child == %@", child)]+ if !includeDeceased {+ predicates.append(NSPredicate(format: "person.isDeceased == NO OR person.isDeceased == nil"))+ }+ if stack.container.managedObjectModel.entitiesByName["Person"]?.relationshipsByName["mergedInto"] != nil {+ predicates.append(NSPredicate(format: "person.mergedInto == nil AND person.archivedAt == nil"))+ }+ if stack.container.managedObjectModel.entitiesByName["Connection"]?.attributesByName["archivedAt"] != nil {+ predicates.append(NSPredicate(format: "archivedAt == nil AND mergedInto == nil"))+ }+ return try rows(entity: "Connection", nameKey: "person.displayName",+ predicate: NSCompoundPredicate(andPredicateWithSubpredicates: predicates)) } func createFamily(name: String) throws -> NSManagedObjectID {@@ -96,16 +134,26 @@ final class FamilyRepository { } } - private func write(_ operation: (NSManagedObjectContext) throws -> NSManagedObject) throws -> NSManagedObjectID {+ func write(_ operation: (NSManagedObjectContext) throws -> NSManagedObject) throws -> NSManagedObjectID {+ guard stack.role != .widget else { throw GraphError.readOnly } let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.persistentStoreCoordinator = stack.container.persistentStoreCoordinator context.transactionAuthor = stack.role.rawValue let result = try operation(context)+ let inserted = Array(context.insertedObjects)+ let updated = Array(context.updatedObjects)+ let deleted = Array(context.deletedObjects) try context.save()+ // Repository callers can immediately refetch already registered objects after a local save.+ NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [+ NSInsertedObjectsKey: inserted.map(\.objectID), NSUpdatedObjectsKey: updated.map(\.objectID),+ NSDeletedObjectsKey: deleted.map(\.objectID),+ ], into: [stack.container.viewContext])+ NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: stack.container) return result.objectID } - private func rows(entity: String, nameKey: String, predicate: NSPredicate? = nil) throws -> [GraphRow] {+ func rows(entity: String, nameKey: String, predicate: NSPredicate? = nil) throws -> [GraphRow] { let request = NSFetchRequest<NSManagedObject>(entityName: entity) request.predicate = predicate request.sortDescriptors = [NSSortDescriptor(key: nameKey, ascending: true)]@@ -114,28 +162,37 @@ final class FamilyRepository { } } - private func record(_ id: NSManagedObjectID, entity: String, in context: NSManagedObjectContext) throws -> NSManagedObject {- guard !id.isTemporaryID, id.entity.name == entity else { throw GraphError.invalidReference }+ func record(_ id: NSManagedObjectID, entity: String, in context: NSManagedObjectContext) throws -> NSManagedObject {+ guard !id.isTemporaryID, id.entity.name == entity,+ let store = id.persistentStore,+ stack.container.persistentStoreCoordinator.persistentStores.contains(store) else { throw GraphError.invalidReference } let object = try context.existingObject(with: id) guard !object.isDeleted else { throw GraphError.invalidReference }+ if ["Person", "Connection", "ChildProfile"].contains(entity),+ object.entity.relationshipsByName["mergedInto"] != nil,+ object.value(forKey: "mergedInto") != nil { throw MergeError.changed }+ if ["Connection", "ChildProfile"].contains(entity), object.entity.attributesByName["archivedAt"] != nil,+ object.value(forKey: "archivedAt") != nil { throw MergeError.changed }+ if let cloud = stack.container as? NSPersistentCloudKitContainer,+ !cloud.canUpdateRecord(forManagedObjectWith: id) { throw GraphError.readOnly } return object } - private func owningStore(of family: NSManagedObject) throws -> NSPersistentStore {+ func owningStore(of family: NSManagedObject) throws -> NSPersistentStore { guard let store = family.objectID.persistentStore, stack.container.persistentStoreCoordinator.persistentStores.contains(store) else { throw GraphError.invalidReference } return store } - private func insert(_ entity: String, in context: NSManagedObjectContext, store: NSPersistentStore) -> NSManagedObject {+ func insert(_ entity: String, in context: NSManagedObjectContext, store: NSPersistentStore) -> NSManagedObject { let object = NSEntityDescription.insertNewObject(forEntityName: entity, into: context) context.assign(object, to: store) object.setValue(UUID(), forKey: "id") return object } - private func makePerson(name: String, family: NSManagedObject, store: NSPersistentStore,- context: NSManagedObjectContext, needsReview: Bool) -> NSManagedObject {+ func makePerson(name: String, family: NSManagedObject, store: NSPersistentStore,+ context: NSManagedObjectContext, needsReview: Bool) -> NSManagedObject { let person = insert("Person", in: context, store: store) person.setValue(name, forKey: "displayName") person.setValue(family, forKey: "familySpace")@@ -155,7 +212,7 @@ final class FamilyRepository { return connection } - private func validated(_ name: String) throws -> String {+ func validated(_ name: String) throws -> String { let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines) guard !trimmed.isEmpty else { throw GraphError.blankName } return trimmed
diff --git a/Halo Family/Halo Family/Persistence/FamilySharing.swift b/Halo Family/Halo Family/Persistence/FamilySharing.swiftnew file mode 100644index 0000000..5d0199b--- /dev/null+++ b/Halo Family/Halo Family/Persistence/FamilySharing.swift @@ -0,0 +1,101 @@+import CloudKit+import CoreData+import Foundation++nonisolated struct FamilyShare: Identifiable, Sendable {+ let id = UUID()+ let familyID: NSManagedObjectID+ let title: String+ let share: CKShare+ let container: CKContainer+}++enum SharingError: LocalizedError {+ case hostRequired+ case ownerRequired+ case wrongContainer+ case missingResult++ var errorDescription: String? {+ switch self {+ case .hostRequired: "Open the main app with iCloud available to share a family."+ case .ownerRequired: "Only the family owner can create an invitation."+ case .wrongContainer: "This invitation belongs to a different app."+ case .missingResult: "iCloud did not finish preparing the invitation. Please try again."+ }+ }+}++/// Only the host can invoke sharing APIs; the FamilySpace root includes its related graph.+@MainActor+final class FamilySharing {+ let stack: PersistenceStack+ private var preparations: [NSManagedObjectID: Task<FamilyShare, Error>] = [:]++ init(stack: PersistenceStack) { self.stack = stack }++ func prepare(familyID: NSManagedObjectID) async throws -> FamilyShare {+ if let task = preparations[familyID] { return try await task.value }+ let task = Task { @MainActor in try await createOrFetch(familyID: familyID) }+ preparations[familyID] = task+ defer { preparations[familyID] = nil }+ return try await task.value+ }++ private func createOrFetch(familyID: NSManagedObjectID) async throws -> FamilyShare {+ let cloud = try cloudContainer()+ guard familyID.entity.name == "FamilySpace", !familyID.isTemporaryID,+ familyID.persistentStore == stack.privateStore else { throw SharingError.ownerRequired }+ let family = try stack.container.viewContext.existingObject(with: familyID)+ guard !family.isDeleted else { throw GraphError.invalidReference }+ let title = family.value(forKey: "name") as? String ?? "Halo Family"+ if let existing = try cloud.fetchShares(matching: [familyID])[familyID] {+ return FamilyShare(familyID: familyID, title: title, share: existing,+ container: CKContainer(identifier: StoreConfiguration.cloudContainer))+ }+ let result: FamilyShare = try await withCheckedThrowingContinuation { continuation in+ cloud.share([family], to: nil) { _, share, container, error in+ if let error { continuation.resume(throwing: error) } else if let share, let container {+ continuation.resume(returning: FamilyShare(familyID: familyID, title: title, share: share, container: container))+ } else { continuation.resume(throwing: SharingError.missingResult) }+ }+ }+ result.share[CKShare.SystemFieldKey.title] = title as CKRecordValue+ result.share.publicPermission = .none+ try await persist(result.share, familyID: familyID)+ return result+ }++ func persist(_ share: CKShare, familyID: NSManagedObjectID) async throws {+ let cloud = try cloudContainer()+ guard let store = familyID.persistentStore,+ [stack.privateStore, stack.sharedStore].contains(store) else { throw GraphError.invalidReference }+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in+ cloud.persistUpdatedShare(share, in: store) { _, error in+ if let error { continuation.resume(throwing: error) } else { continuation.resume() }+ }+ }+ }++ func accept(_ metadata: CKShare.Metadata) async throws {+ guard metadata.containerIdentifier == StoreConfiguration.cloudContainer else { throw SharingError.wrongContainer }+ let cloud = try cloudContainer()+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in+ cloud.acceptShareInvitations(from: [metadata], into: stack.sharedStore) { accepted, error in+ if let error { continuation.resume(throwing: error) } else if accepted?.isEmpty == false {+ continuation.resume()+ } else { continuation.resume(throwing: SharingError.missingResult) }+ }+ }+ // Acceptance finishes before the graph necessarily downloads. Remote history handles later imports.+ await stack.refreshHistory()+ NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: stack.container)+ }++ private func cloudContainer() throws -> NSPersistentCloudKitContainer {+ guard stack.role == .host, let cloud = stack.container as? NSPersistentCloudKitContainer else {+ throw SharingError.hostRequired+ }+ return cloud+ }+}
diff --git a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversion b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversionindex 7a57798..0f17c83 100644--- a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversion +++ b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversion @@ -3,6 +3,6 @@ <plist version="1.0"> <dict> <key>_XCCurrentVersionName</key>- <string>HaloModelV2.xcdatamodel</string>+ <string>HaloModelV6.xcdatamodel</string> </dict> </plist>
diff --git a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contents b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contentsnew file mode 100644index 0000000..bc68ab8--- /dev/null+++ b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contents @@ -0,0 +1,100 @@+<?xml version='1.0' encoding='utf-8'?>+<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" sourceLanguage="Swift" userDefinedModelVersionIdentifier="3" usedWithCloudKit="YES">+ <entity name="FamilySpace" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="name" optional="YES" attributeType="String" />+ <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="familySpace" inverseEntity="Person" toMany="YES" />+ <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="familySpace" inverseEntity="ChildProfile" toMany="YES" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="familySpace" inverseEntity="Connection" toMany="YES" />+ <relationship name="assets" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="familySpace" inverseEntity="Asset" toMany="YES" />+ <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="familySpace" inverseEntity="Context" toMany="YES" />+ <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="familySpace" inverseEntity="Event" toMany="YES" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="familySpace" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="familySpace" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="contextPeople" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="familySpace" inverseEntity="ContextPerson" toMany="YES" />+ </entity>+ <entity name="Person" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="displayName" optional="YES" attributeType="String" />+ <attribute name="needsReview" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="people" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="childProfile" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="person" inverseEntity="ChildProfile" maxCount="1" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="person" inverseEntity="Connection" toMany="YES" />+ <attribute name="givenName" optional="YES" attributeType="String" />+ <attribute name="familyName" optional="YES" attributeType="String" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="contextLinks" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="person" inverseEntity="ContextPerson" toMany="YES" />+ </entity>+ <entity name="ChildProfile" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="isActive" optional="YES" attributeType="Boolean" defaultValueString="YES" usesScalarValueType="YES" />+ <attribute name="displayOrder" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="children" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="childProfile" inverseEntity="Person" maxCount="1" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="child" inverseEntity="Connection" toMany="YES" />+ </entity>+ <entity name="Connection" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="connections" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="child" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="connections" inverseEntity="ChildProfile" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="connections" inverseEntity="Person" maxCount="1" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="connection" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origin" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="connection" inverseEntity="ConnectionOrigin" maxCount="1" />+ </entity>+ <entity name="Asset" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="data" optional="YES" attributeType="Binary" allowsExternalBinaryDataStorage="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="assets" inverseEntity="FamilySpace" maxCount="1" />+ </entity>+ <entity name="Context" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="name" optional="YES" attributeType="String" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contexts" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="parent" inverseEntity="Context" toMany="YES" />+ <relationship name="parent" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="children" inverseEntity="Context" maxCount="1" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="context" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="context" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="context" inverseEntity="ContextPerson" toMany="YES" />+ </entity>+ <entity name="ConnectionContext" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="memberships" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="memberships" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="memberships" inverseEntity="Context" maxCount="1" />+ </entity>+ <entity name="ConnectionOrigin" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="originDescription" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="origins" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="origin" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="origins" inverseEntity="Context" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="origins" inverseEntity="Event" maxCount="1" />+ </entity>+ <entity name="Event" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="title" optional="YES" attributeType="String" />+ <attribute name="date" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="events" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="event" inverseEntity="ConnectionOrigin" toMany="YES" />+ </entity>+ <entity name="ContextPerson" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextPeople" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="people" inverseEntity="Context" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="contextLinks" inverseEntity="Person" maxCount="1" />+ </entity>+</model>
diff --git a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contents b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contentsnew file mode 100644index 0000000..5a844e1--- /dev/null+++ b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contents @@ -0,0 +1,140 @@+<?xml version='1.0' encoding='utf-8'?>+<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" sourceLanguage="Swift" userDefinedModelVersionIdentifier="4" usedWithCloudKit="YES">+ <entity name="FamilySpace" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="name" optional="YES" attributeType="String" />+ <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="familySpace" inverseEntity="Person" toMany="YES" />+ <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="familySpace" inverseEntity="ChildProfile" toMany="YES" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="familySpace" inverseEntity="Connection" toMany="YES" />+ <relationship name="assets" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="familySpace" inverseEntity="Asset" toMany="YES" />+ <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="familySpace" inverseEntity="Context" toMany="YES" />+ <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="familySpace" inverseEntity="Event" toMany="YES" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="familySpace" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="familySpace" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="contextPeople" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="familySpace" inverseEntity="ContextPerson" toMany="YES" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="familySpace" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="familySpace" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+ <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="familySpace" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+ </entity>+ <entity name="Person" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="displayName" optional="YES" attributeType="String" />+ <attribute name="needsReview" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="people" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="childProfile" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="person" inverseEntity="ChildProfile" maxCount="1" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="person" inverseEntity="Connection" toMany="YES" />+ <attribute name="givenName" optional="YES" attributeType="String" />+ <attribute name="familyName" optional="YES" attributeType="String" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="contextLinks" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="person" inverseEntity="ContextPerson" toMany="YES" />+ </entity>+ <entity name="ChildProfile" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="isActive" optional="YES" attributeType="Boolean" defaultValueString="YES" usesScalarValueType="YES" />+ <attribute name="displayOrder" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="children" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="childProfile" inverseEntity="Person" maxCount="1" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="child" inverseEntity="Connection" toMany="YES" />+ </entity>+ <entity name="Connection" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="connections" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="child" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="connections" inverseEntity="ChildProfile" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="connections" inverseEntity="Person" maxCount="1" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="connection" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origin" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="connection" inverseEntity="ConnectionOrigin" maxCount="1" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="connection" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="connection" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+ <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="connection" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+ </entity>+ <entity name="Asset" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="data" optional="YES" attributeType="Binary" allowsExternalBinaryDataStorage="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="assets" inverseEntity="FamilySpace" maxCount="1" />+ </entity>+ <entity name="Context" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="name" optional="YES" attributeType="String" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contexts" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="parent" inverseEntity="Context" toMany="YES" />+ <relationship name="parent" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="children" inverseEntity="Context" maxCount="1" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="context" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="context" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="context" inverseEntity="ContextPerson" toMany="YES" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="context" inverseEntity="OriginProposal" toMany="YES" />+ </entity>+ <entity name="ConnectionContext" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="memberships" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="memberships" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="memberships" inverseEntity="Context" maxCount="1" />+ </entity>+ <entity name="ConnectionOrigin" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="originDescription" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="origins" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="origin" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="origins" inverseEntity="Context" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="origins" inverseEntity="Event" maxCount="1" />+ </entity>+ <entity name="Event" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="title" optional="YES" attributeType="String" />+ <attribute name="date" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="events" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="event" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="event" inverseEntity="OriginProposal" toMany="YES" />+ </entity>+ <entity name="ContextPerson" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextPeople" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="people" inverseEntity="Context" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="contextLinks" inverseEntity="Person" maxCount="1" />+ <attribute name="role" optional="YES" attributeType="String" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ </entity>+ <entity name="OriginProposal" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="narrative" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="isCleared" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="originProposals" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="originProposals" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="originProposals" inverseEntity="Context" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="originProposals" inverseEntity="Event" maxCount="1" />+ <relationship name="predecessors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="successors" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="successors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="predecessors" inverseEntity="OriginProposal" toMany="YES" />+ </entity>+ <entity name="ConnectionClosenessPeriod" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="value" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="closenessPeriods" inverseEntity="Connection" maxCount="1" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="closenessPeriods" inverseEntity="FamilySpace" maxCount="1" />+ </entity>+ <entity name="ConnectionStatusPeriod" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="state" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="statusPeriods" inverseEntity="Connection" maxCount="1" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="statusPeriods" inverseEntity="FamilySpace" maxCount="1" />+ </entity>+</model>
diff --git a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contents b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contentsnew file mode 100644index 0000000..11690a0--- /dev/null+++ b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contents @@ -0,0 +1,282 @@+<?xml version='1.0' encoding='utf-8'?>+<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" sourceLanguage="Swift" userDefinedModelVersionIdentifier="5" usedWithCloudKit="YES">+ <entity name="FamilySpace" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="name" optional="YES" attributeType="String" />+ <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="familySpace" inverseEntity="Person" toMany="YES" />+ <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="familySpace" inverseEntity="ChildProfile" toMany="YES" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="familySpace" inverseEntity="Connection" toMany="YES" />+ <relationship name="assets" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="familySpace" inverseEntity="Asset" toMany="YES" />+ <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="familySpace" inverseEntity="Context" toMany="YES" />+ <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="familySpace" inverseEntity="Event" toMany="YES" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="familySpace" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="familySpace" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="contextPeople" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="familySpace" inverseEntity="ContextPerson" toMany="YES" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="familySpace" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="familySpace" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+ <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="familySpace" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+ <relationship name="personRelationshipRecords" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="familySpace" inverseEntity="PersonRelationship" toMany="YES" />+ <relationship name="relationshipAssertionRecords" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="familySpace" inverseEntity="RelationshipAssertion" toMany="YES" />+ <relationship name="addressLabelRecords" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="familySpace" inverseEntity="AddressLabel" toMany="YES" />+ <relationship name="personGroupRecords" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="familySpace" inverseEntity="PersonGroup" toMany="YES" />+ <relationship name="groupMembershipRecords" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="familySpace" inverseEntity="GroupMembership" toMany="YES" />+ <relationship name="contextCategoryRecords" optional="YES" deletionRule="Nullify" destinationEntity="ContextCategory" inverseName="familySpace" inverseEntity="ContextCategory" toMany="YES" />+ <relationship name="eventPersonRecords" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="familySpace" inverseEntity="EventPerson" toMany="YES" />+ <relationship name="giftRecordRecords" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="familySpace" inverseEntity="GiftRecord" toMany="YES" />+ <relationship name="eventAttachmentRecords" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="familySpace" inverseEntity="EventAttachment" toMany="YES" />+ </entity>+ <entity name="Person" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="displayName" optional="YES" attributeType="String" />+ <attribute name="needsReview" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="people" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="childProfile" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="person" inverseEntity="ChildProfile" maxCount="1" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="person" inverseEntity="Connection" toMany="YES" />+ <attribute name="givenName" optional="YES" attributeType="String" />+ <attribute name="familyName" optional="YES" attributeType="String" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="contextLinks" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="person" inverseEntity="ContextPerson" toMany="YES" />+ <attribute name="isDeceased" optional="YES" attributeType="Boolean" usesScalarValueType="YES" defaultValueString="NO" />+ <attribute name="deathYear" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+ <attribute name="deathMonth" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+ <attribute name="deathDay" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="mergedInto" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="mergedPeople" inverseEntity="Person" maxCount="1" />+ <relationship name="mergedPeople" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="mergedInto" inverseEntity="Person" toMany="YES" />+ <relationship name="primaryPhoto" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="photoPerson" inverseEntity="Asset" maxCount="1" />+ <relationship name="personRelationshipFrom" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="source" inverseEntity="PersonRelationship" toMany="YES" />+ <relationship name="personRelationshipTo" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="target" inverseEntity="PersonRelationship" toMany="YES" />+ <relationship name="relationshipAssertionFrom" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="source" inverseEntity="RelationshipAssertion" toMany="YES" />+ <relationship name="relationshipAssertionTo" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="target" inverseEntity="RelationshipAssertion" toMany="YES" />+ <relationship name="addressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="target" inverseEntity="AddressLabel" toMany="YES" />+ <relationship name="usedAddressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="usedByPerson" inverseEntity="AddressLabel" toMany="YES" />+ <relationship name="groupMemberships" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="person" inverseEntity="GroupMembership" toMany="YES" />+ <relationship name="subjectEvents" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="subjectPerson" inverseEntity="Event" toMany="YES" />+ <relationship name="eventParticipations" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="person" inverseEntity="EventPerson" toMany="YES" />+ <relationship name="givenGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="givers" inverseEntity="GiftRecord" toMany="YES" />+ <relationship name="receivedGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="recipients" inverseEntity="GiftRecord" toMany="YES" />+ </entity>+ <entity name="ChildProfile" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="isActive" optional="YES" attributeType="Boolean" defaultValueString="YES" usesScalarValueType="YES" />+ <attribute name="displayOrder" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="children" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="childProfile" inverseEntity="Person" maxCount="1" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="child" inverseEntity="Connection" toMany="YES" />+ </entity>+ <entity name="Connection" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="connections" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="child" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="connections" inverseEntity="ChildProfile" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="connections" inverseEntity="Person" maxCount="1" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="connection" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origin" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="connection" inverseEntity="ConnectionOrigin" maxCount="1" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="connection" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="connection" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+ <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="connection" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+ </entity>+ <entity name="Asset" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="data" optional="YES" attributeType="Binary" allowsExternalBinaryDataStorage="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="assets" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="photoPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="primaryPhoto" inverseEntity="Person" maxCount="1" />+ <attribute name="filename" optional="YES" attributeType="String" />+ <attribute name="contentType" optional="YES" attributeType="String" />+ <attribute name="kind" optional="YES" attributeType="String" />+ <attribute name="byteCount" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+ <attribute name="pixelWidth" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+ <attribute name="pixelHeight" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+ <relationship name="eventAttachment" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="asset" inverseEntity="EventAttachment" maxCount="1" />+ <attribute name="contentRevision" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ </entity>+ <entity name="Context" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="name" optional="YES" attributeType="String" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contexts" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="parent" inverseEntity="Context" toMany="YES" />+ <relationship name="parent" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="children" inverseEntity="Context" maxCount="1" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="context" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="context" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="context" inverseEntity="ContextPerson" toMany="YES" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="context" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="category" optional="YES" deletionRule="Nullify" destinationEntity="ContextCategory" inverseName="contexts" inverseEntity="ContextCategory" maxCount="1" />+ <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="context" inverseEntity="Event" toMany="YES" />+ </entity>+ <entity name="ConnectionContext" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="memberships" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="memberships" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="memberships" inverseEntity="Context" maxCount="1" />+ </entity>+ <entity name="ConnectionOrigin" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="originDescription" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="origins" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="origin" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="origins" inverseEntity="Context" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="origins" inverseEntity="Event" maxCount="1" />+ </entity>+ <entity name="Event" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="title" optional="YES" attributeType="String" />+ <attribute name="date" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="events" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="event" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="event" inverseEntity="OriginProposal" toMany="YES" />+ <attribute name="type" optional="YES" attributeType="String" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endDate" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="subjectPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="subjectEvents" inverseEntity="Person" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="events" inverseEntity="Context" maxCount="1" />+ <relationship name="participants" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="event" inverseEntity="EventPerson" toMany="YES" />+ <relationship name="gifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="event" inverseEntity="GiftRecord" toMany="YES" />+ <relationship name="attachments" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="event" inverseEntity="EventAttachment" toMany="YES" />+ </entity>+ <entity name="ContextPerson" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextPeople" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="people" inverseEntity="Context" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="contextLinks" inverseEntity="Person" maxCount="1" />+ <attribute name="role" optional="YES" attributeType="String" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ </entity>+ <entity name="OriginProposal" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="narrative" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="isCleared" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="originProposals" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="originProposals" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="originProposals" inverseEntity="Context" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="originProposals" inverseEntity="Event" maxCount="1" />+ <relationship name="predecessors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="successors" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="successors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="predecessors" inverseEntity="OriginProposal" toMany="YES" />+ </entity>+ <entity name="ConnectionClosenessPeriod" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="value" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="closenessPeriods" inverseEntity="Connection" maxCount="1" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="closenessPeriods" inverseEntity="FamilySpace" maxCount="1" />+ </entity>+ <entity name="ConnectionStatusPeriod" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="state" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="statusPeriods" inverseEntity="Connection" maxCount="1" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="statusPeriods" inverseEntity="FamilySpace" maxCount="1" />+ </entity>+ <entity name="PersonRelationship" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personRelationshipRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="source" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="personRelationshipFrom" inverseEntity="Person" maxCount="1" />+ <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="personRelationshipTo" inverseEntity="Person" maxCount="1" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="kind" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="nature" optional="YES" attributeType="String" />+ </entity>+ <entity name="RelationshipAssertion" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="relationshipAssertionRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="source" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="relationshipAssertionFrom" inverseEntity="Person" maxCount="1" />+ <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="relationshipAssertionTo" inverseEntity="Person" maxCount="1" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="kind" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="customLabel" optional="YES" attributeType="String" />+ <attribute name="side" optional="YES" attributeType="String" />+ <attribute name="relatedBy" optional="YES" attributeType="String" />+ </entity>+ <entity name="AddressLabel" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="addressLabelRecords" inverseEntity="FamilySpace" maxCount="1" />+ <attribute name="label" optional="YES" attributeType="String" />+ <attribute name="language" optional="YES" attributeType="String" />+ <attribute name="script" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="isPreferred" optional="YES" attributeType="Boolean" usesScalarValueType="YES" defaultValueString="NO" />+ <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="addressLabels" inverseEntity="Person" maxCount="1" />+ <relationship name="usedByPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="usedAddressLabels" inverseEntity="Person" maxCount="1" />+ <relationship name="usedByGroup" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="usedAddressLabels" inverseEntity="PersonGroup" maxCount="1" />+ </entity>+ <entity name="PersonGroup" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personGroupRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="usedAddressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="usedByGroup" inverseEntity="AddressLabel" toMany="YES" />+ <attribute name="name" optional="YES" attributeType="String" />+ <attribute name="type" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="group" inverseEntity="GroupMembership" toMany="YES" />+ <relationship name="givenGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="giverGroups" inverseEntity="GiftRecord" toMany="YES" />+ </entity>+ <entity name="GroupMembership" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="groupMembershipRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="group" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="memberships" inverseEntity="PersonGroup" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="groupMemberships" inverseEntity="Person" maxCount="1" />+ <attribute name="role" optional="YES" attributeType="String" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ </entity>+ <entity name="ContextCategory" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextCategoryRecords" inverseEntity="FamilySpace" maxCount="1" />+ <attribute name="name" optional="YES" attributeType="String" />+ <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="category" inverseEntity="Context" toMany="YES" />+ </entity>+ <entity name="EventPerson" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="eventPersonRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="participants" inverseEntity="Event" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="eventParticipations" inverseEntity="Person" maxCount="1" />+ <attribute name="roles" optional="YES" attributeType="String" />+ <attribute name="invitationState" optional="YES" attributeType="String" />+ <attribute name="attendanceState" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ </entity>+ <entity name="GiftRecord" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="giftRecordRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="gifts" inverseEntity="Event" maxCount="1" />+ <attribute name="descriptionText" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <relationship name="givers" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="givenGifts" inverseEntity="Person" toMany="YES" />+ <relationship name="giverGroups" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="givenGifts" inverseEntity="PersonGroup" toMany="YES" />+ <relationship name="recipients" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="receivedGifts" inverseEntity="Person" toMany="YES" />+ <relationship name="attachments" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="gifts" inverseEntity="EventAttachment" toMany="YES" />+ </entity>+ <entity name="EventAttachment" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="eventAttachmentRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="attachments" inverseEntity="Event" maxCount="1" />+ <relationship name="asset" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="eventAttachment" inverseEntity="Asset" maxCount="1" />+ <relationship name="gifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="attachments" inverseEntity="GiftRecord" toMany="YES" />+ <attribute name="kind" optional="YES" attributeType="String" />+ <attribute name="title" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ </entity>+</model>
diff --git a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV6.xcdatamodel/contents b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV6.xcdatamodel/contentsnew file mode 100644index 0000000..42db605--- /dev/null+++ b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV6.xcdatamodel/contents @@ -0,0 +1,324 @@+<?xml version='1.0' encoding='utf-8'?>+<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" sourceLanguage="Swift" userDefinedModelVersionIdentifier="6" usedWithCloudKit="YES">+ <entity name="FamilySpace" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="name" optional="YES" attributeType="String" />+ <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="familySpace" inverseEntity="Person" toMany="YES" />+ <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="familySpace" inverseEntity="ChildProfile" toMany="YES" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="familySpace" inverseEntity="Connection" toMany="YES" />+ <relationship name="assets" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="familySpace" inverseEntity="Asset" toMany="YES" />+ <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="familySpace" inverseEntity="Context" toMany="YES" />+ <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="familySpace" inverseEntity="Event" toMany="YES" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="familySpace" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="familySpace" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="contextPeople" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="familySpace" inverseEntity="ContextPerson" toMany="YES" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="familySpace" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="familySpace" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+ <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="familySpace" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+ <relationship name="personRelationshipRecords" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="familySpace" inverseEntity="PersonRelationship" toMany="YES" />+ <relationship name="relationshipAssertionRecords" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="familySpace" inverseEntity="RelationshipAssertion" toMany="YES" />+ <relationship name="addressLabelRecords" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="familySpace" inverseEntity="AddressLabel" toMany="YES" />+ <relationship name="personGroupRecords" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="familySpace" inverseEntity="PersonGroup" toMany="YES" />+ <relationship name="groupMembershipRecords" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="familySpace" inverseEntity="GroupMembership" toMany="YES" />+ <relationship name="contextCategoryRecords" optional="YES" deletionRule="Nullify" destinationEntity="ContextCategory" inverseName="familySpace" inverseEntity="ContextCategory" toMany="YES" />+ <relationship name="eventPersonRecords" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="familySpace" inverseEntity="EventPerson" toMany="YES" />+ <relationship name="giftRecordRecords" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="familySpace" inverseEntity="GiftRecord" toMany="YES" />+ <relationship name="eventAttachmentRecords" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="familySpace" inverseEntity="EventAttachment" toMany="YES" />+ <relationship name="personMerges" optional="YES" deletionRule="Nullify" destinationEntity="PersonMerge" inverseName="familySpace" inverseEntity="PersonMerge" toMany="YES" />+ <relationship name="mergeConnectionReviews" optional="YES" deletionRule="Nullify" destinationEntity="MergeConnectionReview" inverseName="familySpace" inverseEntity="MergeConnectionReview" toMany="YES" />+ <relationship name="personMergeRecoveries" optional="YES" deletionRule="Nullify" destinationEntity="PersonMergeRecovery" inverseName="familySpace" inverseEntity="PersonMergeRecovery" toMany="YES" />+ </entity>+ <entity name="Person" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="displayName" optional="YES" attributeType="String" />+ <attribute name="needsReview" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="people" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="childProfile" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="person" inverseEntity="ChildProfile" maxCount="1" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="person" inverseEntity="Connection" toMany="YES" />+ <attribute name="givenName" optional="YES" attributeType="String" />+ <attribute name="familyName" optional="YES" attributeType="String" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="contextLinks" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="person" inverseEntity="ContextPerson" toMany="YES" />+ <attribute name="isDeceased" optional="YES" attributeType="Boolean" usesScalarValueType="YES" defaultValueString="NO" />+ <attribute name="deathYear" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+ <attribute name="deathMonth" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+ <attribute name="deathDay" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="mergedInto" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="mergedPeople" inverseEntity="Person" maxCount="1" />+ <relationship name="mergedPeople" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="mergedInto" inverseEntity="Person" toMany="YES" />+ <relationship name="primaryPhoto" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="photoPerson" inverseEntity="Asset" maxCount="1" />+ <relationship name="personRelationshipFrom" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="source" inverseEntity="PersonRelationship" toMany="YES" />+ <relationship name="personRelationshipTo" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="target" inverseEntity="PersonRelationship" toMany="YES" />+ <relationship name="relationshipAssertionFrom" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="source" inverseEntity="RelationshipAssertion" toMany="YES" />+ <relationship name="relationshipAssertionTo" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="target" inverseEntity="RelationshipAssertion" toMany="YES" />+ <relationship name="addressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="target" inverseEntity="AddressLabel" toMany="YES" />+ <relationship name="usedAddressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="usedByPerson" inverseEntity="AddressLabel" toMany="YES" />+ <relationship name="groupMemberships" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="person" inverseEntity="GroupMembership" toMany="YES" />+ <relationship name="subjectEvents" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="subjectPerson" inverseEntity="Event" toMany="YES" />+ <relationship name="eventParticipations" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="person" inverseEntity="EventPerson" toMany="YES" />+ <relationship name="givenGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="givers" inverseEntity="GiftRecord" toMany="YES" />+ <relationship name="receivedGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="recipients" inverseEntity="GiftRecord" toMany="YES" />+ </entity>+ <entity name="ChildProfile" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="isActive" optional="YES" attributeType="Boolean" defaultValueString="YES" usesScalarValueType="YES" />+ <attribute name="displayOrder" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="children" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="childProfile" inverseEntity="Person" maxCount="1" />+ <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="child" inverseEntity="Connection" toMany="YES" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="mergedInto" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="mergedRecords" inverseEntity="ChildProfile" maxCount="1" />+ <relationship name="mergedRecords" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="mergedInto" inverseEntity="ChildProfile" toMany="YES" />+ </entity>+ <entity name="Connection" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="connections" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="child" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="connections" inverseEntity="ChildProfile" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="connections" inverseEntity="Person" maxCount="1" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="connection" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origin" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="connection" inverseEntity="ConnectionOrigin" maxCount="1" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="connection" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="connection" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+ <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="connection" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="mergedInto" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="mergedRecords" inverseEntity="Connection" maxCount="1" />+ <relationship name="mergedRecords" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="mergedInto" inverseEntity="Connection" toMany="YES" />+ </entity>+ <entity name="Asset" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="data" optional="YES" attributeType="Binary" allowsExternalBinaryDataStorage="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="assets" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="photoPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="primaryPhoto" inverseEntity="Person" maxCount="1" />+ <attribute name="filename" optional="YES" attributeType="String" />+ <attribute name="contentType" optional="YES" attributeType="String" />+ <attribute name="kind" optional="YES" attributeType="String" />+ <attribute name="byteCount" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+ <attribute name="pixelWidth" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+ <attribute name="pixelHeight" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+ <relationship name="eventAttachment" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="asset" inverseEntity="EventAttachment" maxCount="1" />+ <attribute name="contentRevision" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ </entity>+ <entity name="Context" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="name" optional="YES" attributeType="String" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contexts" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="parent" inverseEntity="Context" toMany="YES" />+ <relationship name="parent" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="children" inverseEntity="Context" maxCount="1" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="context" inverseEntity="ConnectionContext" toMany="YES" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="context" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="context" inverseEntity="ContextPerson" toMany="YES" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="context" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="category" optional="YES" deletionRule="Nullify" destinationEntity="ContextCategory" inverseName="contexts" inverseEntity="ContextCategory" maxCount="1" />+ <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="context" inverseEntity="Event" toMany="YES" />+ </entity>+ <entity name="ConnectionContext" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="memberships" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="memberships" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="memberships" inverseEntity="Context" maxCount="1" />+ </entity>+ <entity name="ConnectionOrigin" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="originDescription" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="origins" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="origin" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="origins" inverseEntity="Context" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="origins" inverseEntity="Event" maxCount="1" />+ </entity>+ <entity name="Event" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="title" optional="YES" attributeType="String" />+ <attribute name="date" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="events" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="event" inverseEntity="ConnectionOrigin" toMany="YES" />+ <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="event" inverseEntity="OriginProposal" toMany="YES" />+ <attribute name="type" optional="YES" attributeType="String" />+ <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endDate" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="subjectPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="subjectEvents" inverseEntity="Person" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="events" inverseEntity="Context" maxCount="1" />+ <relationship name="participants" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="event" inverseEntity="EventPerson" toMany="YES" />+ <relationship name="gifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="event" inverseEntity="GiftRecord" toMany="YES" />+ <relationship name="attachments" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="event" inverseEntity="EventAttachment" toMany="YES" />+ </entity>+ <entity name="ContextPerson" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="notes" optional="YES" attributeType="String" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextPeople" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="people" inverseEntity="Context" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="contextLinks" inverseEntity="Person" maxCount="1" />+ <attribute name="role" optional="YES" attributeType="String" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ </entity>+ <entity name="OriginProposal" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="narrative" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="isCleared" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="originProposals" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="originProposals" inverseEntity="Connection" maxCount="1" />+ <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="originProposals" inverseEntity="Context" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="originProposals" inverseEntity="Event" maxCount="1" />+ <relationship name="predecessors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="successors" inverseEntity="OriginProposal" toMany="YES" />+ <relationship name="successors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="predecessors" inverseEntity="OriginProposal" toMany="YES" />+ </entity>+ <entity name="ConnectionClosenessPeriod" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="value" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="closenessPeriods" inverseEntity="Connection" maxCount="1" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="closenessPeriods" inverseEntity="FamilySpace" maxCount="1" />+ </entity>+ <entity name="ConnectionStatusPeriod" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="state" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="statusPeriods" inverseEntity="Connection" maxCount="1" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="statusPeriods" inverseEntity="FamilySpace" maxCount="1" />+ </entity>+ <entity name="PersonRelationship" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personRelationshipRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="source" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="personRelationshipFrom" inverseEntity="Person" maxCount="1" />+ <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="personRelationshipTo" inverseEntity="Person" maxCount="1" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="kind" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="nature" optional="YES" attributeType="String" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ </entity>+ <entity name="RelationshipAssertion" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="relationshipAssertionRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="source" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="relationshipAssertionFrom" inverseEntity="Person" maxCount="1" />+ <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="relationshipAssertionTo" inverseEntity="Person" maxCount="1" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="kind" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="customLabel" optional="YES" attributeType="String" />+ <attribute name="side" optional="YES" attributeType="String" />+ <attribute name="relatedBy" optional="YES" attributeType="String" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ </entity>+ <entity name="AddressLabel" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="addressLabelRecords" inverseEntity="FamilySpace" maxCount="1" />+ <attribute name="label" optional="YES" attributeType="String" />+ <attribute name="language" optional="YES" attributeType="String" />+ <attribute name="script" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="isPreferred" optional="YES" attributeType="Boolean" usesScalarValueType="YES" defaultValueString="NO" />+ <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="addressLabels" inverseEntity="Person" maxCount="1" />+ <relationship name="usedByPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="usedAddressLabels" inverseEntity="Person" maxCount="1" />+ <relationship name="usedByGroup" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="usedAddressLabels" inverseEntity="PersonGroup" maxCount="1" />+ </entity>+ <entity name="PersonGroup" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personGroupRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="usedAddressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="usedByGroup" inverseEntity="AddressLabel" toMany="YES" />+ <attribute name="name" optional="YES" attributeType="String" />+ <attribute name="type" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="group" inverseEntity="GroupMembership" toMany="YES" />+ <relationship name="givenGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="giverGroups" inverseEntity="GiftRecord" toMany="YES" />+ </entity>+ <entity name="GroupMembership" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="groupMembershipRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="group" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="memberships" inverseEntity="PersonGroup" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="groupMemberships" inverseEntity="Person" maxCount="1" />+ <attribute name="role" optional="YES" attributeType="String" />+ <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ </entity>+ <entity name="ContextCategory" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextCategoryRecords" inverseEntity="FamilySpace" maxCount="1" />+ <attribute name="name" optional="YES" attributeType="String" />+ <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="category" inverseEntity="Context" toMany="YES" />+ <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ </entity>+ <entity name="EventPerson" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="eventPersonRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="participants" inverseEntity="Event" maxCount="1" />+ <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="eventParticipations" inverseEntity="Person" maxCount="1" />+ <attribute name="roles" optional="YES" attributeType="String" />+ <attribute name="invitationState" optional="YES" attributeType="String" />+ <attribute name="attendanceState" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ </entity>+ <entity name="GiftRecord" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="giftRecordRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="gifts" inverseEntity="Event" maxCount="1" />+ <attribute name="descriptionText" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <relationship name="givers" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="givenGifts" inverseEntity="Person" toMany="YES" />+ <relationship name="giverGroups" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="givenGifts" inverseEntity="PersonGroup" toMany="YES" />+ <relationship name="recipients" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="receivedGifts" inverseEntity="Person" toMany="YES" />+ <relationship name="attachments" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="gifts" inverseEntity="EventAttachment" toMany="YES" />+ </entity>+ <entity name="EventAttachment" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="eventAttachmentRecords" inverseEntity="FamilySpace" maxCount="1" />+ <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="attachments" inverseEntity="Event" maxCount="1" />+ <relationship name="asset" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="eventAttachment" inverseEntity="Asset" maxCount="1" />+ <relationship name="gifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="attachments" inverseEntity="GiftRecord" toMany="YES" />+ <attribute name="kind" optional="YES" attributeType="String" />+ <attribute name="title" optional="YES" attributeType="String" />+ <attribute name="note" optional="YES" attributeType="String" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ </entity>+ <entity name="PersonMerge" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="sourceID" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="survivorID" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="undoneAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="undoUnavailableAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="sourceName" optional="YES" attributeType="String" />+ <attribute name="survivorName" optional="YES" attributeType="String" />+ <attribute name="beforeData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+ <attribute name="afterData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personMerges" inverseEntity="FamilySpace" maxCount="1" />+ <attribute name="archivedData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+ <attribute name="recoveryIDs" optional="YES" attributeType="String" />+ </entity>+ <entity name="MergeConnectionReview" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="connectionID" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="reviewedData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="mergeConnectionReviews" inverseEntity="FamilySpace" maxCount="1" />+ </entity>+ <entity name="PersonMergeRecovery" representedClassName="NSManagedObject" syncable="YES">+ <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+ <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+ <attribute name="mergeIDs" optional="YES" attributeType="String" />+ <attribute name="beforeData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+ <attribute name="afterData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+ <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personMergeRecoveries" inverseEntity="FamilySpace" maxCount="1" />+ </entity>+</model>
diff --git a/Halo Family/Halo Family/Persistence/ImageImport.swift b/Halo Family/Halo Family/Persistence/ImageImport.swiftnew file mode 100644index 0000000..c75d01f--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ImageImport.swift @@ -0,0 +1,84 @@+import Foundation+import ImageIO+import CoreGraphics+import UniformTypeIdentifiers++nonisolated enum MemoryError: LocalizedError {+ case unsupportedFile+ case fileTooLarge+ case invalidImage+ case invalidDate+ case changed+ case invalidRelationship+ case invalidParticipation++ var errorDescription: String? {+ switch self {+ case .unsupportedFile: "Choose a JPEG, PNG or PDF file. Person photos must be JPEG or PNG."+ case .fileTooLarge: "The file exceeds the allowed size. Photos must be at most 4 MB after processing; attachments at most 20 MB."+ case .invalidImage: "This image or document could not be read."+ case .invalidDate: "Enter a valid partial date, starting with the year."+ case .changed: "These details changed. Reopen them before saving."+ case .invalidRelationship: "Choose different people from this family and valid relationship details."+ case .invalidParticipation: "Choose people, groups and attachments from this event's family."+ }+ }+}++nonisolated struct PreparedAsset: Sendable {+ let data: Data+ let filename: String+ let contentType: String+ let width: Int?+ let height: Int?+}++/// Decode only a bounded thumbnail, then encode a fresh image without source EXIF/GPS metadata.+nonisolated enum ImageImport {+ static let photoLimit = 4_000_000+ static let attachmentLimit = 20_000_000++ static func prepare(_ data: Data, filename: String, photo: Bool) throws -> PreparedAsset {+ guard !data.isEmpty, data.count <= attachmentLimit else { throw MemoryError.fileTooLarge }+ if !photo, data.starts(with: Data("%PDF-".utf8)) {+ guard let provider = CGDataProvider(data: data as CFData), CGPDFDocument(provider) != nil else {+ throw MemoryError.invalidImage+ }+ return PreparedAsset(data: data, filename: safeName(filename, extension: "pdf"),+ contentType: UTType.pdf.identifier, width: nil, height: nil)+ }+ guard let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),+ let type = CGImageSourceGetType(source) as String?,+ type == UTType.jpeg.identifier || type == UTType.png.identifier else { throw MemoryError.unsupportedFile }+ let options: [CFString: Any] = [+ kCGImageSourceCreateThumbnailFromImageAlways: true,+ kCGImageSourceThumbnailMaxPixelSize: photo ? 2048 : 4096,+ kCGImageSourceCreateThumbnailWithTransform: true,+ kCGImageSourceShouldCacheImmediately: true,+ ]+ guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else {+ throw MemoryError.invalidImage+ }+ let outputType = photo ? UTType.jpeg : (type == UTType.png.identifier ? .png : .jpeg)+ let limit = photo ? photoLimit : attachmentLimit+ for quality in [0.88, 0.72, 0.55] {+ let output = NSMutableData()+ guard let destination = CGImageDestinationCreateWithData(output, outputType.identifier as CFString, 1, nil) else {+ throw MemoryError.invalidImage+ }+ // Never copy the source properties dictionary: it can contain GPS and identifying metadata.+ CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)+ guard CGImageDestinationFinalize(destination) else { throw MemoryError.invalidImage }+ if output.length <= limit {+ return PreparedAsset(data: output as Data, filename: safeName(filename, extension: outputType == .png ? "png" : "jpg"),+ contentType: outputType.identifier, width: image.width, height: image.height)+ }+ }+ throw MemoryError.fileTooLarge+ }++ private static func safeName(_ name: String, extension suffix: String) -> String {+ let base = URL(fileURLWithPath: name).deletingPathExtension().lastPathComponent+ return "\(base.isEmpty ? "Attachment" : String(base.prefix(120))).\(suffix)"+ }+}
diff --git a/Halo Family/Halo Family/Persistence/KinshipQueries.swift b/Halo Family/Halo Family/Persistence/KinshipQueries.swiftnew file mode 100644index 0000000..ebe396e--- /dev/null+++ b/Halo Family/Halo Family/Persistence/KinshipQueries.swift @@ -0,0 +1,82 @@+import CoreData+import Foundation++struct DerivedKinshipRow: Identifiable {+ let id: NSManagedObjectID+ let name: String+ let label: String+}++@MainActor+extension FamilyRepository {+ /// Conservative labels describe the known path; no gender, side or address label is inferred.+ func derivedKinship(for personID: NSManagedObjectID, asOf date: Date = Date()) throws -> [DerivedKinshipRow] {+ let person = try readable(personID, entity: "Person")+ let family = try family(of: person)+ let request = NSFetchRequest<NSManagedObject>(entityName: "PersonRelationship")+ let modern = stack.container.managedObjectModel.entitiesByName["PersonRelationship"]?.attributesByName["archivedAt"] != nil+ let active = NSPredicate(format: "familySpace == %@ AND (startedAt == nil OR startedAt <= %@) " ++ "AND (endedAt == nil OR endedAt > %@)",+ family, date as NSDate, date as NSDate)+ request.predicate = modern ?+ NSCompoundPredicate(andPredicateWithSubpredicates: [active, NSPredicate(format: "archivedAt == nil")]) : active+ let facts = try stack.container.viewContext.fetch(request)+ var parents: [NSManagedObjectID: Set<NSManagedObjectID>] = [:]+ var siblings: [NSManagedObjectID: Set<NSManagedObjectID>] = [:]+ for fact in facts {+ guard let source = fact.value(forKey: "source") as? NSManagedObject,+ let target = fact.value(forKey: "target") as? NSManagedObject else { continue }+ try requireSameFamily(source, family: family)+ try requireSameFamily(target, family: family)+ if fact.value(forKey: "kind") as? String == StructuralKind.parentOf.rawValue {+ parents[target.objectID, default: []].insert(source.objectID)+ } else if fact.value(forKey: "kind") as? String == StructuralKind.siblingOf.rawValue {+ siblings[source.objectID, default: []].insert(target.objectID)+ siblings[target.objectID, default: []].insert(source.objectID)+ }+ }+ // Malformed imported parent cycles are preserved as facts, but never used for derivation.+ guard !hasParentCycle(parents) else { return [] }+ func siblingSet(_ id: NSManagedObjectID) -> Set<NSManagedObjectID> {+ let directParents = parents[id] ?? []+ let throughParents = parents.keys.filter { $0 != id && !(parents[$0] ?? []).isDisjoint(with: directParents) }+ return (siblings[id] ?? []).union(throughParents)+ }+ let direct = Set(try familyFacts(for: personID).filter {+ ($0.startedAt.map { $0 <= date } ?? true) && ($0.endedAt.map { $0 > date } ?? true)+ }.map {+ $0.sourceID == personID ? $0.targetID : $0.sourceID+ })+ var candidates: [NSManagedObjectID: Set<String>] = [:]+ for sibling in siblingSet(personID) { candidates[sibling, default: []].insert("Sibling through known family facts") }+ for parent in parents[personID] ?? [] {+ for grandparent in parents[parent] ?? [] {+ candidates[grandparent, default: []].insert("Grandparent through known family facts")+ for relative in siblingSet(grandparent) { candidates[relative, default: []].insert("Grandparent’s sibling") }+ }+ for relative in siblingSet(parent) { candidates[relative, default: []].insert("Parent’s sibling") }+ }+ return try candidates.compactMap { id, labels in+ guard id != personID, !direct.contains(id), labels.count == 1, let label = labels.first else { return nil }+ let relative = try readable(id, entity: "Person")+ guard relative.value(forKey: "mergedInto") == nil else { return nil }+ return DerivedKinshipRow(id: id, name: relative.value(forKey: "displayName") as? String ?? "Unnamed", label: label)+ }.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }+ }+ private func hasParentCycle(_ parents: [NSManagedObjectID: Set<NSManagedObjectID>]) -> Bool {+ let nodes = Set(parents.keys).union(parents.values.flatMap { $0 })+ var incoming = Dictionary(uniqueKeysWithValues: nodes.map { ($0, 0) })+ for ancestors in parents.values { for ancestor in ancestors { incoming[ancestor, default: 0] += 1 } }+ var ready = nodes.filter { incoming[$0] == 0 }+ var processed = 0+ while let node = ready.popFirst() {+ processed += 1+ for ancestor in parents[node] ?? [] {+ incoming[ancestor, default: 0] -= 1+ if incoming[ancestor] == 0 { ready.insert(ancestor) }+ }+ }+ return processed != nodes.count+ }++}
diff --git a/Halo Family/Halo Family/Persistence/MergeAccountReview.swift b/Halo Family/Halo Family/Persistence/MergeAccountReview.swiftnew file mode 100644index 0000000..6920526--- /dev/null+++ b/Halo Family/Halo Family/Persistence/MergeAccountReview.swift @@ -0,0 +1,126 @@+import CoreData+import Foundation++struct LateMergeAccounts: Identifiable {+ let id: NSManagedObjectID+ let stableID: UUID+ let name: String+ let targetID: NSManagedObjectID?+ let records: [MergeRecord]+ let unreviewedIDs: Set<UUID>+}++@MainActor+extension FamilyRepository {+ func lateMergeAccounts(in familyID: NSManagedObjectID) throws -> [LateMergeAccounts] {+ let family = try readable(familyID, entity: "FamilySpace")+ return try lateMergeAccounts(family: family, in: stack.container.viewContext)+ }++ private func lateMergeAccounts(family: NSManagedObject, in context: NSManagedObjectContext) throws -> [LateMergeAccounts] {+ let audits = NSFetchRequest<NSManagedObject>(entityName: "PersonMerge")+ audits.predicate = NSPredicate(format: "familySpace == %@ AND undoneAt == nil", family)+ let history = try context.fetch(audits)+ guard !history.isEmpty else { return [] }+ var baselines: [UUID: [[MergeRecord]]] = [:]+ for audit in history {+ let rows = try MergeSnapshot.decode(audit.value(forKey: "archivedData") as? Data)+ for (id, accounts) in mergeAccountIndex(rows) { baselines[id, default: []].append(accounts) }+ }+ guard !baselines.isEmpty else { return [] }+ let reviewed = NSFetchRequest<NSManagedObject>(entityName: "MergeConnectionReview")+ reviewed.predicate = NSPredicate(format: "familySpace == %@", family)+ for review in try context.fetch(reviewed) {+ guard let id = review.value(forKey: "connectionID") as? UUID else { throw MergeError.invalidSnapshot }+ baselines[id, default: []].append(try MergeSnapshot.decode(review.value(forKey: "reviewedData") as? Data))+ }+ let current = try MergeSnapshot.records(family: family, in: context)+ let indexed = mergeAccountIndex(current)+ let objects = try MergeSnapshot.objects(family: family, in: context)+ return try baselines.keys.sorted(by: { $0.uuidString < $1.uuidString }).compactMap { id in+ guard let connection = objects[id], connection.value(forKey: "archivedAt") != nil else { return nil }+ let rows = indexed[id] ?? []+ guard !(baselines[id] ?? []).contains(rows) else { return nil }+ var seen: [UUID: [MergeRecord]] = [:]+ for baseline in baselines[id] ?? [] {+ for row in baseline { seen[row.id, default: []].append(row) }+ }+ let unreviewed = Set(rows.filter { !(seen[$0.id] ?? []).contains($0) }.map(\.id))+ return LateMergeAccounts(id: connection.objectID, stableID: id,+ name: connection.value(forKeyPath: "person.displayName") as? String ?? "Earlier relationship",+ targetID: try activeMergeConnection(connection)?.objectID, records: rows, unreviewedIDs: unreviewed)+ }+ }++ /// Copies late accounts as alternatives, without choosing a new current truth. Original IDs stay in history.+ func reviewLateMergeAccounts(_ preview: LateMergeAccounts) throws {+ _ = try write { context in+ let connection = try context.existingObject(with: preview.id)+ guard connection.entity.name == "Connection", connection.value(forKey: "archivedAt") != nil,+ try stable(connection) == preview.stableID else { throw MergeError.changed }+ let family = try family(of: connection)+ _ = try record(family.objectID, entity: "FamilySpace", in: context)+ guard let fresh = try lateMergeAccounts(family: family, in: context).first(where: { $0.id == preview.id }),+ fresh.records == preview.records, fresh.unreviewedIDs == preview.unreviewedIDs else { throw MergeError.changed }+ let target = try activeMergeConnection(connection)+ guard target?.objectID == preview.targetID else { throw MergeError.changed }+ if let target {+ _ = try record(target.objectID, entity: "Connection", in: context)+ // Seed a causal account for any pre-proposal first meeting on the current relationship.+ _ = try preparedHeads(connection: target, heads: originHeads(connection: target, in: context), in: context)+ for head in try mergeOrigins(connection) where head.recordID != nil && preview.unreviewedIDs.contains(head.id) {+ _ = try makeProposal(input: OriginInput(contextID: head.contextID, eventID: head.eventID, narrative: head.narrative),+ cleared: head.cleared, connection: target, predecessors: [], in: context)+ }+ try copyLatePeriodsAndMemberships(connection, to: target, unreviewed: preview.unreviewedIDs, in: context)+ }+ let review = insert("MergeConnectionReview", in: context, store: try owningStore(of: family))+ review.setValue(family, forKey: "familySpace"); review.setValue(preview.stableID, forKey: "connectionID")+ review.setValue(Date(), forKey: "createdAt")+ review.setValue(try MergeSnapshot.encode(preview.records), forKey: "reviewedData")+ try requireMergeWritePermissions(context)+ return review+ }+ }++ private func copyLatePeriodsAndMemberships(_ source: NSManagedObject, to target: NSManagedObject,+ unreviewed: Set<UUID>, in context: NSManagedObjectContext) throws {+ let family = try family(of: source)+ let entities = ["ConnectionClosenessPeriod", "ConnectionStatusPeriod", "ConnectionContext"]+ for entity in entities {+ let request = NSFetchRequest<NSManagedObject>(entityName: entity)+ request.predicate = NSPredicate(format: "connection == %@ AND endedAt == nil", source)+ for original in try context.fetch(request) {+ guard try unreviewed.contains(stable(original)) else { continue }+ let copy = insert(entity, in: context, store: try owningStore(of: family))+ for key in original.entity.attributesByName.keys where key != "id" {+ copy.setValue(original.value(forKey: key), forKey: key)+ }+ copy.setValue(family, forKey: "familySpace"); copy.setValue(target, forKey: "connection")+ if entity == "ConnectionContext" { copy.setValue(original.value(forKey: "context"), forKey: "context") }+ }+ }+ }++ private func activeMergeConnection(_ original: NSManagedObject) throws -> NSManagedObject? {+ let family = try family(of: original)+ var visited: Set<NSManagedObjectID> = [original.objectID]+ var current = original+ while let next = current.value(forKey: "mergedInto") as? NSManagedObject {+ guard visited.insert(next.objectID).inserted else { throw MergeError.invalidSnapshot }+ try requireSameFamily(next, family: family)+ current = next+ }+ return current.value(forKey: "archivedAt") == nil ? current : nil+ }++ private func mergeAccountIndex(_ records: [MergeRecord]) -> [UUID: [MergeRecord]] {+ var result: [UUID: [MergeRecord]] = [:]+ for row in records {+ if row.entity == "Connection" { result[row.id, default: []].append(row) } else {+ for id in row.links["connection"] ?? [] { result[id, default: []].append(row) }+ }+ }+ return result+ }+}
diff --git a/Halo Family/Halo Family/Persistence/MergeConflictRecovery.swift b/Halo Family/Halo Family/Persistence/MergeConflictRecovery.swiftnew file mode 100644index 0000000..2ab6150--- /dev/null+++ b/Halo Family/Halo Family/Persistence/MergeConflictRecovery.swift @@ -0,0 +1,184 @@+import CoreData+import Foundation++struct PersonMergeConflict: Identifiable {+ let id: String+ let familyID: NSManagedObjectID+ let people: [GraphRow]+ let mergeIDs: [UUID]+ let records: [MergeRecord]+}++private struct MergeRecoveryState {+ let acknowledged: Set<UUID>+ let byPerson: [UUID: Set<UUID>]+}++@MainActor+extension FamilyRepository {+ func mergeConflicts(in familyID: NSManagedObjectID) throws -> [PersonMergeConflict] {+ let family = try readable(familyID, entity: "FamilySpace")+ return try mergeConflicts(family: family, in: stack.container.viewContext)+ }++ /// Recovery exposes the separate identities and retains the currently saved references and competing audits.+ /// It deliberately does not replay an old full snapshot over intervening edits.+ func recoverCompetingMerges(_ preview: PersonMergeConflict) throws {+ _ = try write { context in+ let family = try record(preview.familyID, entity: "FamilySpace", in: context)+ let conflicts = try mergeConflicts(family: family, in: context)+ guard let current = conflicts.first(where: { $0.id == preview.id }), current.records == preview.records,+ current.mergeIDs == preview.mergeIDs else { throw MergeError.changed }+ let objects = try MergeSnapshot.objects(family: family, in: context)+ for person in current.people {+ let object = try context.existingObject(with: person.id)+ guard object.entity.name == "Person", try self.family(of: object) == family else { throw GraphError.differentFamily }+ object.setValue(nil, forKey: "mergedInto"); object.setValue(nil, forKey: "archivedAt")+ object.setValue(true, forKey: "needsReview"); object.setValue(Date(), forKey: "modifiedAt")+ }+ let recovery = insert("PersonMergeRecovery", in: context, store: try owningStore(of: family))+ recovery.setValue(family, forKey: "familySpace"); recovery.setValue(Date(), forKey: "createdAt")+ recovery.setValue(String(data: try JSONEncoder().encode(preview.mergeIDs), encoding: .utf8), forKey: "mergeIDs")+ let ids = Set(try current.people.map { try stable(context.existingObject(with: $0.id)) })+ recovery.setValue(try MergeSnapshot.encode(preview.records.filter { ids.contains($0.id) }), forKey: "beforeData")+ recovery.setValue(try MergeSnapshot.encode(try ids.map {+ guard let object = objects[$0] else { throw MergeError.invalidSnapshot }+ return try MergeSnapshot.record(object)+ }.sorted { $0.id.uuidString < $1.id.uuidString }), forKey: "afterData")+ try requireMergeWritePermissions(context)+ return recovery+ }+ }++ func mergeConflicts(family: NSManagedObject, in context: NSManagedObjectContext) throws -> [PersonMergeConflict] {+ guard context.persistentStoreCoordinator?.managedObjectModel.entitiesByName["PersonMerge"] != nil else { return [] }+ let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMerge")+ request.predicate = NSPredicate(format: "familySpace == %@ AND undoneAt == nil", family)+ let audits = try context.fetch(request)+ if audits.isEmpty {+ let aliases = NSFetchRequest<NSManagedObject>(entityName: "Person")+ aliases.predicate = NSPredicate(format: "familySpace == %@ AND mergedInto != nil", family)+ aliases.fetchLimit = 1+ guard try !context.fetch(aliases).isEmpty else { return [] }+ }+ let recovery = try mergeRecoveryState(family: family, in: context)+ let peopleRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")+ peopleRequest.predicate = NSPredicate(format: "familySpace == %@", family)+ let people = try context.fetch(peopleRequest)+ var objects: [UUID: NSManagedObject] = [:]+ for person in people {+ guard objects.updateValue(person, forKey: try stable(person)) == nil else { throw MergeError.invalidSnapshot }+ }+ var edges: [UUID: Set<UUID>] = [:]+ var accounts: [(id: UUID, source: UUID, target: UUID)] = []+ var stale: Set<UUID> = []+ for audit in audits {+ let id = try stable(audit)+ guard !recovery.acknowledged.contains(id) else { continue }+ guard let source = audit.value(forKey: "sourceID") as? UUID,+ let target = audit.value(forKey: "survivorID") as? UUID,+ objects[source] != nil, objects[target] != nil else { throw MergeError.invalidSnapshot }+ edges[source, default: []].insert(target)+ accounts.append((id, source, target))+ let known = try decodedMergeIDs(audit.value(forKey: "recoveryIDs") as? String)+ let required = (recovery.byPerson[source] ?? []).union(recovery.byPerson[target] ?? [])+ if !required.isSubset(of: Set(known)) { stale.formUnion([source, target]) }+ }+ var problematic = Set(edges.filter { $0.value.count > 1 }.keys).union(stale)+ problematic.formUnion(cycleMembers(edges))+ let supported = mergeAuditComponents(edges)+ var currentEdges: [UUID: Set<UUID>] = [:]+ for (id, person) in objects {+ if let target = person.value(forKey: "mergedInto") as? NSManagedObject {+ try requireSameFamily(target, family: family)+ let targetID = try stable(target)+ currentEdges[id, default: []].insert(targetID)+ if supported[id] == nil || supported[id] != supported[targetID] { problematic.formUnion([id, targetID]) }+ }+ }+ problematic.formUnion(cycleMembers(currentEdges))+ for (id, targets) in currentEdges { edges[id, default: []].formUnion(targets) }+ guard !problematic.isEmpty else { return [] }+ let components = mergeConflictComponents(problematic, edges: edges)+ let records = try MergeSnapshot.records(family: family, in: context)+ return try components.map { ids in+ let sorted = ids.sorted { $0.uuidString < $1.uuidString }+ let rows = try sorted.map { id -> GraphRow in+ guard let person = objects[id] else { throw MergeError.invalidSnapshot }+ return GraphRow(id: person.objectID, name: person.value(forKey: "displayName") as? String ?? "Person")+ }+ return PersonMergeConflict(id: sorted.map(\.uuidString).joined(separator: "|"), familyID: family.objectID,+ people: rows, mergeIDs: accounts.filter { ids.contains($0.source) || ids.contains($0.target) }.map(\.id)+ .sorted { $0.uuidString < $1.uuidString }, records: records)+ }.sorted { $0.id < $1.id }+ }++ private func decodedMergeIDs(_ text: String?) throws -> [UUID] {+ guard let text else { return [] }+ guard let ids = try? JSONDecoder().decode([UUID].self, from: Data(text.utf8)) else { throw MergeError.invalidSnapshot }+ return ids+ }++ private func mergeRecoveryState(family: NSManagedObject, in context: NSManagedObjectContext) throws -> MergeRecoveryState {+ let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMergeRecovery")+ request.predicate = NSPredicate(format: "familySpace == %@", family)+ var acknowledged: Set<UUID> = [], byPerson: [UUID: Set<UUID>] = [:]+ for recovery in try context.fetch(request) {+ let id = try stable(recovery)+ acknowledged.formUnion(try decodedMergeIDs(recovery.value(forKey: "mergeIDs") as? String))+ for row in try MergeSnapshot.decode(recovery.value(forKey: "afterData") as? Data) where row.entity == "Person" {+ byPerson[row.id, default: []].insert(id)+ }+ }+ return MergeRecoveryState(acknowledged: acknowledged, byPerson: byPerson)+ }++ private func mergeAuditComponents(_ edges: [UUID: Set<UUID>]) -> [UUID: UUID] {+ let ids = Set(edges.keys).union(edges.values.flatMap { $0 })+ let components = mergeConflictComponents(ids, edges: edges)+ var result: [UUID: UUID] = [:]+ for component in components {+ guard let first = component.first else { continue }+ for id in component { result[id] = first }+ }+ return result+ }++ private func cycleMembers(_ edges: [UUID: Set<UUID>]) -> Set<UUID> {+ var incoming: [UUID: Int] = [:]+ for (source, targets) in edges {+ incoming[source, default: 0] += 0+ for target in targets { incoming[target, default: 0] += 1 }+ }+ var pending = incoming.filter { $0.value == 0 }.map(\.key)+ var index = 0+ while index < pending.count {+ let source = pending[index]; index += 1+ for target in edges[source] ?? [] {+ incoming[target, default: 0] -= 1+ if incoming[target] == 0 { pending.append(target) }+ }+ }+ return Set(incoming.filter { $0.value > 0 }.keys)+ }++ private func mergeConflictComponents(_ problematic: Set<UUID>, edges: [UUID: Set<UUID>]) -> [Set<UUID>] {+ var neighbours: [UUID: Set<UUID>] = [:]+ for (source, targets) in edges {+ for target in targets {+ neighbours[source, default: []].insert(target); neighbours[target, default: []].insert(source)+ }+ }+ var remaining = problematic, components: [Set<UUID>] = []+ while let first = remaining.first {+ var component: Set<UUID> = [], pending = [first]+ while let id = pending.popLast() {+ guard component.insert(id).inserted else { continue }+ pending.append(contentsOf: neighbours[id] ?? [])+ }+ remaining.subtract(component); components.append(component)+ }+ return components+ }++}
diff --git a/Halo Family/Halo Family/Persistence/MergeSnapshot.swift b/Halo Family/Halo Family/Persistence/MergeSnapshot.swiftnew file mode 100644index 0000000..f0027e5--- /dev/null+++ b/Halo Family/Halo Family/Persistence/MergeSnapshot.swift @@ -0,0 +1,186 @@+import CoreData+import Foundation++nonisolated enum MergeError: LocalizedError {+ case changed+ case invalidSnapshot+ case choiceRequired+ case unavailable++ var errorDescription: String? {+ switch self {+ case .changed: "These records changed. Review a fresh merge preview before continuing."+ case .invalidSnapshot: "The merge history could not be read. No records were changed."+ case .choiceRequired: "Choose the connection, first meeting and relationship values to retain for each overlap."+ case .unavailable: "Undo is unavailable because an affected record changed or this merge was already undone."+ }+ }+}++/// Metadata only: photos and attachments retain their existing Asset UUIDs and bytes.+nonisolated enum SnapshotValue: Codable, Equatable, Sendable {+ case text(String), integer(Int64), decimal(Double), flag(Bool), date(Date), uuid(UUID)+}++nonisolated struct MergeRecord: Codable, Equatable, Sendable {+ let id: UUID+ let entity: String+ let attributes: [String: SnapshotValue]+ let links: [String: [UUID]]+}++@MainActor+enum MergeSnapshot {+ static func records(family: NSManagedObject, in context: NSManagedObjectContext) throws -> [MergeRecord] {+ guard let model = context.persistentStoreCoordinator?.managedObjectModel else { throw MergeError.invalidSnapshot }+ var records: [MergeRecord] = []+ var identities: Set<UUID> = []+ let historyEntities = ["FamilySpace", "PersonMerge", "MergeConnectionReview", "PersonMergeRecovery"]+ for entity in model.entities where !historyEntities.contains(entity.name ?? "") {+ guard let name = entity.name, entity.relationshipsByName["familySpace"] != nil else { continue }+ let request = NSFetchRequest<NSManagedObject>(entityName: name)+ request.predicate = NSPredicate(format: "familySpace == %@", family)+ for object in try context.fetch(request) {+ let row = try record(object)+ guard identities.insert(row.id).inserted else { throw MergeError.invalidSnapshot }+ records.append(row)+ }+ }+ guard let familyID = family.value(forKey: "id") as? UUID else { throw MergeError.invalidSnapshot }+ identities.insert(familyID)+ guard records.allSatisfy({ $0.links.values.allSatisfy { Set($0).isSubset(of: identities) } }) else {+ throw GraphError.differentFamily+ }+ return records.sorted { $0.id.uuidString < $1.id.uuidString }+ }++ static func record(_ object: NSManagedObject) throws -> MergeRecord {+ guard let id = object.value(forKey: "id") as? UUID, let entity = object.entity.name else { throw MergeError.invalidSnapshot }+ var values: [String: SnapshotValue] = [:]+ for (key, attribute) in object.entity.attributesByName {+ // Skip before reading: external payloads must not be materialized by merge preview.+ if attribute.attributeType == .binaryDataAttributeType { continue }+ guard let value = object.value(forKey: key) else { continue }+ switch value {+ case let uuid as UUID: values[key] = .uuid(uuid)+ case let date as Date: values[key] = .date(date)+ case let text as String: values[key] = .text(text)+ case let number as NSNumber:+ if attribute.attributeType == .booleanAttributeType { values[key] = .flag(number.boolValue) } else if+ [.doubleAttributeType, .floatAttributeType, .decimalAttributeType].contains(attribute.attributeType) {+ values[key] = .decimal(number.doubleValue)+ } else { values[key] = .integer(number.int64Value) }+ default: throw MergeError.invalidSnapshot+ }+ }+ var links: [String: [UUID]] = [:]+ for (key, relationship) in object.entity.relationshipsByName {+ let objects: [NSManagedObject]+ if relationship.isToMany { objects = Array(object.value(forKey: key) as? Set<NSManagedObject> ?? []) } else {+ objects = (object.value(forKey: key) as? NSManagedObject).map { [$0] } ?? []+ }+ links[key] = try objects.map {+ guard let id = $0.value(forKey: "id") as? UUID else { throw MergeError.invalidSnapshot }+ return id+ }.sorted { $0.uuidString < $1.uuidString }+ }+ return MergeRecord(id: id, entity: entity, attributes: values, links: links)+ }++ static func objects(family: NSManagedObject, in context: NSManagedObjectContext) throws -> [UUID: NSManagedObject] {+ var result: [UUID: NSManagedObject] = [:]+ guard let familyID = family.value(forKey: "id") as? UUID else { throw MergeError.invalidSnapshot }+ result[familyID] = family+ for entity in context.persistentStoreCoordinator?.managedObjectModel.entities ?? [] {+ guard let name = entity.name, name != "FamilySpace", entity.relationshipsByName["familySpace"] != nil else { continue }+ let request = NSFetchRequest<NSManagedObject>(entityName: name)+ request.predicate = NSPredicate(format: "familySpace == %@", family)+ for object in try context.fetch(request) {+ guard let id = object.value(forKey: "id") as? UUID, result.updateValue(object, forKey: id) == nil else {+ throw MergeError.invalidSnapshot+ }+ }+ }+ return result+ }++ static func restore(_ records: [MergeRecord], objects: [UUID: NSManagedObject]) throws {+ for row in records { try validate(row, objects: objects) }+ for row in records {+ guard let object = objects[row.id], object.entity.name == row.entity else { throw MergeError.invalidSnapshot }+ for (key, attribute) in object.entity.attributesByName where attribute.attributeType != .binaryDataAttributeType {+ object.setValue(row.attributes[key].map(value), forKey: key)+ }+ }+ for row in records {+ guard let object = objects[row.id] else { throw MergeError.invalidSnapshot }+ for (key, ids) in row.links {+ guard let relationship = object.entity.relationshipsByName[key] else { throw MergeError.invalidSnapshot }+ let targets = try ids.map {+ guard let target = objects[$0], !target.isDeleted else { throw MergeError.invalidSnapshot }+ return target+ }+ if relationship.isToMany { object.setValue(NSSet(array: targets), forKey: key) } else {+ object.setValue(targets.first, forKey: key)+ }+ }+ }+ }++ private static func validate(_ row: MergeRecord, objects: [UUID: NSManagedObject]) throws {+ guard let object = objects[row.id], object.entity.name == row.entity, row.attributes["id"] == .uuid(row.id),+ Set(row.links.keys) == Set(object.entity.relationshipsByName.keys) else { throw MergeError.invalidSnapshot }+ for (key, value) in row.attributes {+ guard let attribute = object.entity.attributesByName[key], accepts(value, type: attribute.attributeType) else {+ throw MergeError.invalidSnapshot+ }+ }+ for (key, ids) in row.links {+ guard let relationship = object.entity.relationshipsByName[key], relationship.isToMany || ids.count <= 1,+ Set(ids).count == ids.count else { throw MergeError.invalidSnapshot }+ for id in ids {+ guard let target = objects[id], !target.isDeleted,+ target.entity.name == relationship.destinationEntity?.name else { throw MergeError.invalidSnapshot }+ }+ }+ }++ private static func accepts(_ value: SnapshotValue, type: NSAttributeType) -> Bool {+ switch (value, type) {+ case (.text, .stringAttributeType), (.flag, .booleanAttributeType), (.uuid, .UUIDAttributeType): true+ case (.date(let date), .dateAttributeType): date.timeIntervalSinceReferenceDate.isFinite+ case (.integer(let number), .integer16AttributeType): Int16(exactly: number) != nil+ case (.integer(let number), .integer32AttributeType): Int32(exactly: number) != nil+ case (.integer, .integer64AttributeType): true+ case (.decimal(let value), .doubleAttributeType), (.decimal(let value), .floatAttributeType),+ (.decimal(let value), .decimalAttributeType): value.isFinite+ default: false+ }+ }++ private static func value(_ value: SnapshotValue) -> Any {+ switch value {+ case .text(let value): value+ case .integer(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+ }+ }++ nonisolated static func encode(_ records: [MergeRecord]) throws -> Data {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.sortedKeys]+ let data = try encoder.encode(records)+ guard data.count <= 16_000_000 else { throw MergeError.invalidSnapshot }+ return data+ }++ nonisolated static func decode(_ data: Data?) throws -> [MergeRecord] {+ guard let data, data.count <= 16_000_000,+ let records = try? JSONDecoder().decode([MergeRecord].self, from: data),+ Set(records.map(\.id)).count == records.count else { throw MergeError.invalidSnapshot }+ return records+ }+}
diff --git a/Halo Family/Halo Family/Persistence/OriginRepository.swift b/Halo Family/Halo Family/Persistence/OriginRepository.swiftnew file mode 100644index 0000000..8a63319--- /dev/null+++ b/Halo Family/Halo Family/Persistence/OriginRepository.swift @@ -0,0 +1,267 @@+import CoreData+import Foundation++struct OriginProposalRow: Identifiable, Equatable {+ let id: NSManagedObjectID+ let stableID: UUID+ let contextID: NSManagedObjectID?+ let eventID: NSManagedObjectID?+ let sourceName: String?+ let narrative: String+ let isCleared: Bool+}++struct OriginOverview {+ let origin: OriginRow?+ let conflicts: [OriginProposalRow]+ let headIDs: Set<UUID>+}++/// Proposals are immutable. Each new proposal acknowledges only the heads it actually saw.+/// Concurrent offline edits therefore remain separate heads until a parent resolves them.+@MainActor+extension FamilyRepository {+ func origin(for connectionID: NSManagedObjectID) throws -> OriginRow? {+ let overview = try originOverview(for: connectionID)+ guard overview.conflicts.isEmpty else { throw GraphError.originConflict }+ return overview.origin+ }++ func originOverview(for connectionID: NSManagedObjectID) throws -> OriginOverview {+ let context = stack.container.viewContext+ let connection = try readable(connectionID, entity: "Connection")+ return try originOverview(connection: connection, heads: originHeads(connection: connection, in: context), in: context)+ }++ func originHistory(for connectionID: NSManagedObjectID) throws -> [OriginProposalRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "OriginProposal")+ request.predicate = NSPredicate(format: "connection == %@", connectionID)+ request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]+ return try stack.container.viewContext.fetch(request).map { try proposalRow($0) }+ }++ func conflictingOriginConnections(in familyID: NSManagedObjectID) throws -> Set<NSManagedObjectID> {+ _ = try readable(familyID, entity: "FamilySpace")+ let request = NSFetchRequest<NSManagedObject>(entityName: "OriginProposal")+ request.predicate = NSPredicate(format: "familySpace == %@", familyID)+ request.relationshipKeyPathsForPrefetching = ["connection", "predecessors", "familySpace"]+ let proposals = try stack.container.viewContext.fetch(request)+ let grouped = Dictionary(grouping: proposals) {+ ($0.value(forKey: "connection") as? NSManagedObject)?.objectID ?? $0.objectID+ }+ var conflicts: Set<NSManagedObjectID> = []+ for (connectionID, records) in grouped {+ guard connectionID.entity.name == "Connection" else { throw GraphError.invalidReference }+ if try proposalHeads(records).count > 1 { conflicts.insert(connectionID) }+ }+ return conflicts+ }++ func saveOrigin(connectionID: NSManagedObjectID, input: OriginInput, expectedOrigin: OriginRow?,+ expectedHeads: Set<UUID> = []) throws {+ _ = try write { context in+ let connection = try record(connectionID, entity: "Connection", in: context)+ let heads = try originHeads(connection: connection, in: context)+ let overview = try originOverview(connection: connection, heads: heads, in: context)+ guard overview.conflicts.isEmpty else { throw GraphError.originConflict }+ guard sameOriginValue(overview.origin, expectedOrigin),+ overview.headIDs == (expectedOrigin?.revisionIDs ?? expectedHeads) else { throw GraphError.originChanged }+ let predecessors = try preparedHeads(connection: connection, heads: heads, in: context)+ _ = try makeProposal(input: input, cleared: false, connection: connection, predecessors: predecessors, in: context)+ return try updateProjection(input: input, cleared: false, connection: connection, in: context)+ }+ }++ func clearOrigin(connectionID: NSManagedObjectID, expectedOrigin: OriginRow) throws {+ _ = try write { context in+ let connection = try record(connectionID, entity: "Connection", in: context)+ let heads = try originHeads(connection: connection, in: context)+ let overview = try originOverview(connection: connection, heads: heads, in: context)+ guard overview.conflicts.isEmpty else { throw GraphError.originConflict }+ guard sameOriginValue(overview.origin, expectedOrigin) else { throw GraphError.originChanged }+ let predecessors = try preparedHeads(connection: connection, heads: heads, in: context)+ _ = try makeProposal(input: OriginInput(), cleared: true, connection: connection, predecessors: predecessors, in: context)+ return try updateProjection(input: OriginInput(), cleared: true, connection: connection, in: context)+ }+ }++ func resolveOrigin(connectionID: NSManagedObjectID, choosing proposalID: NSManagedObjectID, expectedHeads: Set<UUID>) throws {+ _ = try write { context in+ let connection = try record(connectionID, entity: "Connection", in: context)+ let heads = try originHeads(connection: connection, in: context)+ let ids = Set(try heads.map { try proposalRow($0).stableID })+ guard ids == expectedHeads, heads.count > 1,+ let chosen = heads.first(where: { $0.objectID == proposalID }) else { throw GraphError.originChanged }+ let row = try proposalRow(chosen)+ let input = row.isCleared ? OriginInput() :+ OriginInput(contextID: row.contextID, eventID: row.eventID, narrative: row.narrative)+ _ = try makeProposal(input: input, cleared: row.isCleared, connection: connection, predecessors: heads, in: context)+ return try updateProjection(input: input, cleared: row.isCleared, connection: connection, in: context)+ }+ }++ private func originOverview(connection: NSManagedObject, heads: [NSManagedObject],+ in context: NSManagedObjectContext) throws -> OriginOverview {+ let rows = try heads.map { try proposalRow($0) }+ let ids = Set(rows.map(\.stableID))+ if rows.count > 1 { return OriginOverview(origin: nil, conflicts: rows, headIDs: ids) }+ let canonical = try projectionOrigins(connection: connection, in: context)+ if let row = rows.first {+ let origin = row.isCleared ? nil : OriginRow(id: canonical.first?.objectID ?? row.id,+ contextID: row.contextID, eventID: row.eventID,+ sourceName: row.sourceName, narrative: row.narrative, revisionIDs: ids)+ return OriginOverview(origin: origin, conflicts: [], headIDs: ids)+ }+ guard canonical.count <= 1 else { throw GraphError.originChanged }+ let legacy = canonical.first.map { originRow($0) }+ return OriginOverview(origin: legacy, conflicts: [], headIDs: [])+ }++ func originHeads(connection: NSManagedObject, in context: NSManagedObjectContext) throws -> [NSManagedObject] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "OriginProposal")+ request.predicate = NSPredicate(format: "connection == %@", connection)+ return try proposalHeads(context.fetch(request))+ }++ private func proposalHeads(_ all: [NSManagedObject]) throws -> [NSManagedObject] {+ let allIDs = Set(all.map(\.objectID))+ var stableIDs: Set<UUID> = []+ var remainingParents: [NSManagedObjectID: Int] = [:]+ var children: [NSManagedObjectID: [NSManagedObjectID]] = [:]+ for proposal in all {+ guard stableIDs.insert(try validateProposal(proposal)).inserted else { throw GraphError.invalidReference }+ let parents = proposal.value(forKey: "predecessors") as? Set<NSManagedObject> ?? []+ guard parents.allSatisfy({ allIDs.contains($0.objectID) && $0.objectID != proposal.objectID }) else {+ throw GraphError.invalidReference+ }+ remainingParents[proposal.objectID] = parents.count+ for parent in parents { children[parent.objectID, default: []].append(proposal.objectID) }+ }+ // Validate every component, including cycles concealed alongside a valid head.+ var queue = remainingParents.filter { $0.value == 0 }.map(\.key)+ var index = 0+ while index < queue.count {+ for child in children[queue[index], default: []] {+ remainingParents[child, default: 0] -= 1+ if remainingParents[child] == 0 { queue.append(child) }+ }+ index += 1+ }+ guard queue.count == all.count else { throw GraphError.invalidReference }+ return all.filter { children[$0.objectID, default: []].isEmpty }.sorted {+ (($0.value(forKey: "id") as? UUID)?.uuidString ?? "") < (($1.value(forKey: "id") as? UUID)?.uuidString ?? "")+ }+ }++ func preparedHeads(connection: NSManagedObject, heads: [NSManagedObject],+ in context: NSManagedObjectContext) throws -> [NSManagedObject] {+ guard heads.isEmpty, let legacy = try projectionOrigins(connection: connection, in: context).first else { return heads }+ let row = originRow(legacy)+ let input = OriginInput(contextID: row.contextID, eventID: row.eventID, narrative: row.narrative)+ return [try makeProposal(input: input, cleared: false, connection: connection, predecessors: [], in: context)]+ }++ func makeProposal(input: OriginInput, cleared: Bool, connection: NSManagedObject,+ predecessors: [NSManagedObject], in context: NSManagedObjectContext) throws -> NSManagedObject {+ let family = try family(of: connection)+ let narrative = input.narrative.trimmingCharacters(in: .whitespacesAndNewlines)+ guard cleared || (!(input.contextID != nil && input.eventID != nil) &&+ (input.contextID != nil || input.eventID != nil || !narrative.isEmpty)) else { throw GraphError.invalidOrigin }+ let source = try input.contextID.map { try record($0, entity: "Context", in: context) }+ let event = try input.eventID.map { try record($0, entity: "Event", in: context) }+ if let source { try requireSameFamily(source, family: family) }+ if let event { try requireSameFamily(event, family: family) }+ let proposal = insert("OriginProposal", in: context, store: try owningStore(of: family))+ proposal.setValue(family, forKey: "familySpace")+ proposal.setValue(connection, forKey: "connection")+ proposal.setValue(source, forKey: "context")+ proposal.setValue(event, forKey: "event")+ proposal.setValue(narrative.isEmpty ? nil : narrative, forKey: "narrative")+ proposal.setValue(cleared, forKey: "isCleared")+ proposal.setValue(Date(), forKey: "createdAt")+ proposal.setValue(Set(predecessors), forKey: "predecessors")+ return proposal+ }++ private func updateProjection(input: OriginInput, cleared: Bool, connection: NSManagedObject,+ in context: NSManagedObjectContext) throws -> NSManagedObject {+ let existing = try projectionOrigins(connection: connection, in: context)+ if cleared {+ existing.forEach(context.delete)+ return connection+ }+ let family = try family(of: connection)+ let store = try owningStore(of: family)+ let origin = existing.first ?? insert("ConnectionOrigin", in: context, store: store)+ // Concurrent first writes can import two materialized rows. Proposals preserve both+ // accounts; resolution compacts only this replaceable projection.+ existing.dropFirst().forEach(context.delete)+ origin.setValue(family, forKey: "familySpace")+ origin.setValue(connection, forKey: "connection")+ origin.setValue(try input.contextID.map { try record($0, entity: "Context", in: context) }, forKey: "context")+ origin.setValue(try input.eventID.map { try record($0, entity: "Event", in: context) }, forKey: "event")+ origin.setValue(input.narrative.trimmingCharacters(in: .whitespacesAndNewlines), forKey: "originDescription")+ return origin+ }++ private func projectionOrigins(connection: NSManagedObject, in context: NSManagedObjectContext) throws -> [NSManagedObject] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionOrigin")+ request.predicate = NSPredicate(format: "connection == %@", connection)+ let records = try context.fetch(request)+ return records.sorted {+ (($0.value(forKey: "id") as? UUID)?.uuidString ?? "") < (($1.value(forKey: "id") as? UUID)?.uuidString ?? "")+ }+ }++ private func originRow(_ object: NSManagedObject) -> OriginRow {+ let source = object.value(forKey: "context") as? NSManagedObject+ let event = object.value(forKey: "event") as? NSManagedObject+ return OriginRow(id: object.objectID, contextID: source?.objectID, eventID: event?.objectID,+ sourceName: sourceName(context: source, event: event),+ narrative: object.value(forKey: "originDescription") as? String ?? "")+ }++ private func proposalRow(_ object: NSManagedObject) throws -> OriginProposalRow {+ let id = try validateProposal(object)+ let source = object.value(forKey: "context") as? NSManagedObject+ let event = object.value(forKey: "event") as? NSManagedObject+ return OriginProposalRow(id: object.objectID, stableID: id, contextID: source?.objectID, eventID: event?.objectID,+ sourceName: sourceName(context: source, event: event),+ narrative: object.value(forKey: "narrative") as? String ?? "",+ isCleared: object.value(forKey: "isCleared") as? Bool ?? false)+ }++ private func validateProposal(_ object: NSManagedObject) throws -> UUID {+ guard let id = object.value(forKey: "id") as? UUID,+ let connection = object.value(forKey: "connection") as? NSManagedObject else { throw GraphError.invalidReference }+ let family = try family(of: connection)+ try requireSameFamily(object, family: family)+ let source = object.value(forKey: "context") as? NSManagedObject+ let event = object.value(forKey: "event") as? NSManagedObject+ let narrative = object.value(forKey: "narrative") as? String ?? ""+ let cleared = object.value(forKey: "isCleared") as? Bool ?? false+ guard source == nil || event == nil,+ cleared ? (source == nil && event == nil && narrative.isEmpty) :+ (source != nil || event != nil || !narrative.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) else {+ throw GraphError.invalidOrigin+ }+ if let source { try requireSameFamily(source, family: family) }+ if let event { try requireSameFamily(event, family: family) }+ return id+ }++ private func sourceName(context: NSManagedObject?, event: NSManagedObject?) -> String? {+ if let context { return "Context: \(contextPath(context))" }+ if let event {+ let row = EventRow(id: event.objectID, title: event.value(forKey: "title") as? String ?? "Untitled",+ date: event.value(forKey: "date") as? Date, notes: "")+ return "Event: \(row.label)"+ }+ return nil+ }++ private func sameOriginValue(_ current: OriginRow?, _ expected: OriginRow?) -> Bool {+ current?.id == expected?.id && current?.contextID == expected?.contextID && current?.eventID == expected?.eventID &&+ current?.narrative == expected?.narrative && current?.revisionIDs == expected?.revisionIDs+ }+}
diff --git a/Halo Family/Halo Family/Persistence/PersistenceStack.swift b/Halo Family/Halo Family/Persistence/PersistenceStack.swiftindex 5fc89c3..5641a60 100644--- a/Halo Family/Halo Family/Persistence/PersistenceStack.swift +++ b/Halo Family/Halo Family/Persistence/PersistenceStack.swift @@ -148,7 +148,7 @@ final class PersistenceStack { container.viewContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType) } - static func loadModel(version: String = "HaloModelV2") throws -> NSManagedObjectModel {+ static func loadModel(version: String = "HaloModelV6") throws -> NSManagedObjectModel { #if SWIFT_PACKAGE let bundle = Bundle.module #else
diff --git a/Halo Family/Halo Family/Persistence/PersonMergeHistory.swift b/Halo Family/Halo Family/Persistence/PersonMergeHistory.swiftnew file mode 100644index 0000000..e755105--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PersonMergeHistory.swift @@ -0,0 +1,104 @@+import CoreData+import Foundation++@MainActor+extension FamilyRepository {+ func mergeRecoveryHistory(in familyID: NSManagedObjectID) throws -> [PersonMergeRecoveryRow] {+ _ = try readable(familyID, entity: "FamilySpace")+ let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMergeRecovery")+ request.predicate = NSPredicate(format: "familySpace == %@", familyID)+ request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]+ return try stack.container.viewContext.fetch(request).map {+ try PersonMergeRecoveryRow(id: $0.objectID, createdAt: $0.value(forKey: "createdAt") as? Date,+ people: MergeSnapshot.decode($0.value(forKey: "beforeData") as? Data))+ }+ }++ func mergeHistory(in familyID: NSManagedObjectID) throws -> [PersonMergeHistoryRow] {+ let context = stack.container.viewContext+ let family = try readable(familyID, entity: "FamilySpace")+ let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMerge")+ request.predicate = NSPredicate(format: "familySpace == %@", family)+ request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]+ let audits = try context.fetch(request)+ guard !audits.isEmpty else { return [] }+ let needsComparison = audits.contains { $0.value(forKey: "undoneAt") == nil && $0.value(forKey: "undoUnavailableAt") == nil }+ let current = needsComparison ?+ Dictionary(uniqueKeysWithValues: try MergeSnapshot.records(family: family, in: context).map { ($0.id, $0) }) : [:]+ let people = NSFetchRequest<NSManagedObject>(entityName: "Person")+ people.predicate = NSPredicate(format: "familySpace == %@", family)+ var objects: [UUID: NSManagedObject] = [:]+ for person in try context.fetch(people) {+ guard objects.updateValue(person, forKey: try stable(person)) == nil else { throw MergeError.invalidSnapshot }+ }+ return audits.map { audit in+ let source = audit.value(forKey: "sourceID") as? UUID+ let survivor = audit.value(forKey: "survivorID") as? UUID+ let undone = audit.value(forKey: "undoneAt") != nil+ let after = undone || audit.value(forKey: "undoUnavailableAt") != nil ? nil : try? checkedMergeHistory(audit).after+ let unchanged = after?.allSatisfy { current[$0.id] == $0 } ?? false+ return PersonMergeHistoryRow(id: audit.objectID, sourceName: audit.value(forKey: "sourceName") as? String ?? "Person",+ survivorName: audit.value(forKey: "survivorName") as? String ?? "Person",+ sourceID: source.flatMap { objects[$0]?.objectID }, survivorID: survivor.flatMap { objects[$0]?.objectID },+ createdAt: audit.value(forKey: "createdAt") as? Date, undone: undone,+ undoAvailable: !undone && audit.value(forKey: "undoUnavailableAt") == nil && unchanged)+ }+ }++ func undoPersonMerge(_ auditID: NSManagedObjectID) throws {+ _ = try write { context in+ let audit = try record(auditID, entity: "PersonMerge", in: context)+ guard audit.value(forKey: "undoneAt") == nil, audit.value(forKey: "undoUnavailableAt") == nil else {+ throw MergeError.unavailable+ }+ let family = try family(of: audit)+ let history = try checkedMergeHistory(audit)+ let current = Dictionary(uniqueKeysWithValues: try MergeSnapshot.records(family: family, in: context).map { ($0.id, $0) })+ guard history.after.allSatisfy({ current[$0.id] == $0 }) else { throw MergeError.unavailable }+ let objects = try MergeSnapshot.objects(family: family, in: context)+ let beforeIDs = Set(history.before.map(\.id))+ for row in history.after where !beforeIDs.contains(row.id) {+ guard ["OriginProposal", "ConnectionClosenessPeriod", "ConnectionStatusPeriod"].contains(row.entity),+ let object = objects[row.id], object.entity.name == row.entity else { throw MergeError.invalidSnapshot }+ // Only untouched merge-generated projections are removed. Original accounts/UUIDs remain;+ // their generated alternatives and selection stay documented in this retained audit.+ context.delete(object)+ }+ try MergeSnapshot.restore(history.before, objects: objects)+ let restored = Dictionary(uniqueKeysWithValues: try MergeSnapshot.records(family: family, in: context).map { ($0.id, $0) })+ guard history.before.allSatisfy({ restored[$0.id] == $0 }) else { throw MergeError.invalidSnapshot }+ audit.setValue(Date(), forKey: "undoneAt")+ try requireMergeWritePermissions(context)+ return audit+ }+ }++ func mergePreviousDetails(_ auditID: NSManagedObjectID) throws -> [MergeRecord] {+ try checkedMergeHistory(readable(auditID, entity: "PersonMerge")).before+ }++ func archivedMergeConnections(_ auditID: NSManagedObjectID) throws -> [GraphRow] {+ let audit = try readable(auditID, entity: "PersonMerge")+ let family = try family(of: audit)+ let objects = try MergeSnapshot.objects(family: family, in: stack.container.viewContext)+ return try checkedMergeHistory(audit).after.compactMap { row in+ guard row.entity == "Connection", row.attributes["archivedAt"] != nil,+ let object = objects[row.id] else { return nil }+ let child = object.value(forKeyPath: "child.person.displayName") as? String ?? "Child"+ return GraphRow(id: object.objectID, name: "Earlier relationship for \(child)")+ }+ }++ private func checkedMergeHistory(_ audit: NSManagedObject) throws -> (before: [MergeRecord], after: [MergeRecord]) {+ let before = try MergeSnapshot.decode(audit.value(forKey: "beforeData") as? Data)+ let after = try MergeSnapshot.decode(audit.value(forKey: "afterData") as? Data)+ guard let sourceID = audit.value(forKey: "sourceID") as? UUID,+ let survivorID = audit.value(forKey: "survivorID") as? UUID, sourceID != survivorID,+ before.contains(where: { $0.id == sourceID && $0.entity == "Person" && ($0.links["mergedInto"] ?? []).isEmpty }),+ before.contains(where: { $0.id == survivorID && $0.entity == "Person" }),+ after.contains(where: { $0.id == sourceID && $0.entity == "Person" && $0.links["mergedInto"] == [survivorID] }),+ after.contains(where: { $0.id == survivorID && $0.entity == "Person" }),+ Set(before.map(\.id)).isSubset(of: Set(after.map(\.id))) else { throw MergeError.invalidSnapshot }+ return (before, after)+ }+}
diff --git a/Halo Family/Halo Family/Persistence/PersonMergePreview.swift b/Halo Family/Halo Family/Persistence/PersonMergePreview.swiftnew file mode 100644index 0000000..9755814--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PersonMergePreview.swift @@ -0,0 +1,154 @@+import CoreData+import Foundation++@MainActor+extension FamilyRepository {+ func mergedPersonTarget(_ personID: NSManagedObjectID) throws -> NSManagedObjectID? {+ var current = try readable(personID, entity: "Person")+ guard current.entity.relationshipsByName["mergedInto"] != nil else { return nil }+ let family = try family(of: current)+ var visited: Set<NSManagedObjectID> = [personID]+ var result: NSManagedObjectID?+ while let next = current.value(forKey: "mergedInto") as? NSManagedObject {+ guard visited.insert(next.objectID).inserted else { throw MergeError.invalidSnapshot }+ try requireSameFamily(next, family: family)+ current = next; result = next.objectID+ }+ return result+ }++ func likelyDuplicates(in familyID: NSManagedObjectID) throws -> [DuplicatePersonPair] {+ // Suggestions only. Same-name people are valid; deceased people are excluded from routine suggestions.+ let people = try people(in: familyID, includeDeceased: false)+ func words(_ name: String) -> [String] {+ name.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: Locale(identifier: "en_US_POSIX"))+ .split(whereSeparator: { $0.isWhitespace }).map(String.init)+ }+ let indexed = Dictionary(grouping: people) { words($0.name).first ?? "" }+ var result: [DuplicatePersonPair] = []+ for key in indexed.keys.sorted() where !key.isEmpty {+ let group = indexed[key] ?? []+ for (index, person) in group.enumerated() {+ for other in group.dropFirst(index + 1).prefix(20) {+ let first = words(person.name), second = words(other.name)+ if first.count == 1 || second.count == 1 || first == second ||+ first.dropFirst().first?.first == second.dropFirst().first?.first {+ let ids = try [person, other].map { try stable(readable($0.id, entity: "Person")).uuidString }.sorted()+ result.append(DuplicatePersonPair(source: person, survivor: other, id: ids.joined(separator: "|")))+ if result.count >= 100 { return result }+ }+ }+ }+ }+ return result+ }++ func mergePreview(sourceID: NSManagedObjectID, survivorID: NSManagedObjectID) throws -> PersonMergePreview {+ let context = stack.container.viewContext+ let source = try readable(sourceID, entity: "Person"), survivor = try readable(survivorID, entity: "Person")+ let family = try family(of: source)+ try requireSameFamily(survivor, family: family)+ guard try mergeConflicts(in: family.objectID).isEmpty else { throw MergeError.changed }+ guard source != survivor, source.value(forKey: "mergedInto") == nil,+ survivor.value(forKey: "mergedInto") == nil else { throw MergeError.changed }+ let records = try MergeSnapshot.records(family: family, in: context)+ let sourceProfile = source.value(forKey: "childProfile") as? NSManagedObject+ let survivorProfile = survivor.value(forKey: "childProfile") as? NSManagedObject+ let combines = sourceProfile != nil && survivorProfile != nil+ var childMap: [NSManagedObjectID: NSManagedObjectID] = [:]+ if let sourceProfile, let survivorProfile { childMap[sourceProfile.objectID] = survivorProfile.objectID }+ let request = NSFetchRequest<NSManagedObject>(entityName: "Connection")+ request.predicate = NSPredicate(format: "familySpace == %@ AND mergedInto == nil AND archivedAt == nil", family)+ let all = try context.fetch(request)+ let relevant = all.filter {+ let person = $0.value(forKey: "person") as? NSManagedObject+ let child = $0.value(forKey: "child") as? NSManagedObject+ return person == source || person == survivor || (combines && (child == sourceProfile || child == survivorProfile))+ }+ var groups: [String: [NSManagedObject]] = [:]+ var selfConnections: [NSManagedObjectID] = []+ for connection in relevant {+ guard let child = connection.value(forKey: "child") as? NSManagedObject,+ let person = connection.value(forKey: "person") as? NSManagedObject else { throw GraphError.invalidReference }+ let childID = childMap[child.objectID] ?? child.objectID+ let personID = person == source ? survivorID : person.objectID+ let childPerson = child.value(forKey: "person") as? NSManagedObject+ let childPersonID = childPerson == source ? survivorID : childPerson?.objectID+ if personID == childPersonID { selfConnections.append(connection.objectID); continue }+ let key = childID.uriRepresentation().absoluteString + "|" + personID.uriRepresentation().absoluteString+ groups[key, default: []].append(connection)+ }+ let overlaps = try groups.keys.sorted().compactMap { key -> MergeConnectionOverlap? in+ let connections = try (groups[key] ?? []).sorted { try stable($0).uuidString < stable($1).uuidString }+ guard connections.count > 1 else { return nil }+ let kept = connections.first {+ ($0.value(forKey: "person") as? NSManagedObject) != source &&+ (!combines || ($0.value(forKey: "child") as? NSManagedObject) != sourceProfile)+ } ?? connections[0]+ let child = kept.value(forKey: "child") as? NSManagedObject+ let person = kept.value(forKey: "person") as? NSManagedObject+ return try MergeConnectionOverlap(id: stable(kept), keptID: kept.objectID,+ connections: connections.map(\.objectID), childName: child?.value(forKeyPath: "person.displayName") as? String ?? "Child",+ personName: person?.value(forKey: "displayName") as? String ?? "Person",+ origins: try connections.flatMap { try mergeOrigins($0) },+ closeness: try connections.flatMap { try mergePeriods($0, closeness: true) },+ statuses: try connections.flatMap { try mergePeriods($0, closeness: false) })+ }+ let sourceUUID = try stable(source), survivorUUID = try stable(survivor)+ let references = records.filter { row in+ row.id != sourceUUID && row.id != survivorUUID && row.links.values.contains { $0.contains(sourceUUID) }+ }+ let selfLinks = records.filter {+ ["PersonRelationship", "RelationshipAssertion"].contains($0.entity) &&+ Set(($0.links["source"] ?? []) + ($0.links["target"] ?? [])) == [sourceUUID, survivorUUID]+ }.count+ let participations = records.filter { $0.entity == "EventPerson" }+ let events = Set(participations.filter { $0.links["person"] == [sourceUUID] }.flatMap { $0.links["event"] ?? [] })+ let duplicateAccounts = participations.filter {+ $0.links["person"] == [survivorUUID] && !events.isDisjoint(with: $0.links["event"] ?? [])+ }.count+ return PersonMergePreview(familyID: family.objectID, source: try mergePerson(source), survivor: try mergePerson(survivor),+ records: records, overlaps: overlaps,+ referenceCounts: Dictionary(grouping: references, by: \.entity).mapValues(\.count), combinesChildProfiles: combines,+ selfRelationships: selfLinks, selfConnections: selfConnections, duplicateEventAccounts: duplicateAccounts)+ }++ func stable(_ object: NSManagedObject) throws -> UUID {+ guard let id = object.value(forKey: "id") as? UUID else { throw MergeError.invalidSnapshot }+ return id+ }++ private func mergePerson(_ object: NSManagedObject) throws -> MergePersonValues {+ try MergePersonValues(id: object.objectID, stableID: stable(object),+ name: object.value(forKey: "displayName") as? String ?? "Unnamed",+ notes: object.value(forKey: "notes") as? String ?? "", sensitive: try sensitiveDetails(object.objectID),+ photoID: (object.value(forKey: "primaryPhoto") as? NSManagedObject)?.objectID)+ }++ func mergeOrigins(_ connection: NSManagedObject) throws -> [MergeOriginChoice] {+ let label = connection.value(forKeyPath: "person.displayName") as? String ?? "Person"+ let overview = try originOverview(for: connection.objectID)+ let history = try originHistory(for: connection.objectID).filter { overview.headIDs.contains($0.stableID) }+ if !history.isEmpty {+ return history.map {+ MergeOriginChoice(id: $0.stableID, recordID: $0.id, connectionID: connection.objectID,+ label: label + ": " + ($0.isCleared ? "No first meeting" : ($0.sourceName ?? $0.narrative)),+ contextID: $0.contextID, eventID: $0.eventID, narrative: $0.narrative, cleared: $0.isCleared, proposal: true)+ }+ }+ let origin = overview.origin+ let id = try origin.map { try readable($0.id, entity: "ConnectionOrigin") }.map(stable) ?? stable(connection)+ return [MergeOriginChoice(id: id, recordID: origin?.id, connectionID: connection.objectID,+ label: label + ": " + (origin?.sourceName ?? origin?.narrative ?? "No first meeting recorded"),+ contextID: origin?.contextID, eventID: origin?.eventID, narrative: origin?.narrative ?? "",+ cleared: origin == nil, proposal: false)]+ }++ private func mergePeriods(_ connection: NSManagedObject, closeness: Bool) throws -> [MergePeriodChoice] {+ let name = connection.value(forKeyPath: "person.displayName") as? String ?? "Person"+ return try currentStatePeriods(connection.objectID, closeness: closeness).map {+ let value = $0.value.map { ClosenessChoice(rawValue: $0)?.label ?? "Closeness \($0)" } ?? $0.state?.label ?? "Unknown"+ return MergePeriodChoice(id: $0.id, label: name + ": " + value, value: $0.value, state: $0.state, note: $0.note)+ }+ }+}
diff --git a/Halo Family/Halo Family/Persistence/PersonMergeRepository.swift b/Halo Family/Halo Family/Persistence/PersonMergeRepository.swiftnew file mode 100644index 0000000..89168f8--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PersonMergeRepository.swift @@ -0,0 +1,188 @@+import CoreData+import Foundation++@MainActor+extension FamilyRepository {+ func mergePeople(_ preview: PersonMergePreview, choices: PersonMergeChoices) throws -> NSManagedObjectID {+ try write { context in+ let source = try record(preview.source.id, entity: "Person", in: context)+ let survivor = try record(preview.survivor.id, entity: "Person", in: context)+ let family = try record(preview.familyID, entity: "FamilySpace", in: context)+ try requireSameFamily(source, family: family)+ try requireSameFamily(survivor, family: family)+ let before = try MergeSnapshot.records(family: family, in: context)+ guard try mergeConflicts(family: family, in: context).isEmpty else { throw MergeError.changed }+ guard before == preview.records, source != survivor, source.value(forKey: "mergedInto") == nil,+ survivor.value(forKey: "mergedInto") == nil else { throw MergeError.changed }+ // Validate every displayed choice before changing anything.+ try validateMergeChoices(preview.overlaps, choices: choices)+ let all = try MergeSnapshot.objects(family: family, in: context)+ try applyPersonFields(source: source, survivor: survivor, choices: choices)+ let sourceProfile = source.value(forKey: "childProfile") as? NSManagedObject+ let survivorProfile = survivor.value(forKey: "childProfile") as? NSManagedObject+ var retainedHistoricalProfile: NSManagedObject?+ if let sourceProfile, let survivorProfile {+ // Both marked the same child. Keep the survivor's profile identity and all peer references.+ for object in all.values where object.entity.name == "Connection" &&+ (object.value(forKey: "child") as? NSManagedObject) == sourceProfile {+ object.setValue(survivorProfile, forKey: "child")+ }+ sourceProfile.setValue(Date(), forKey: "archivedAt")+ sourceProfile.setValue(survivorProfile, forKey: "mergedInto")+ retainedHistoricalProfile = sourceProfile+ }+ for object in all.values where object != source && object != survivor && object != family &&+ object != retainedHistoricalProfile && object.entity.name != "PersonMerge" {+ try repointPersonReferences(object, from: source, to: survivor)+ }+ for overlap in preview.overlaps {+ guard let choice = choices.connections[overlap.id] else { throw MergeError.choiceRequired }+ try consolidate(overlap, choices: choice, family: family, in: context)+ }+ // A fact between the duplicate identities becomes a self-reference. Retain it as archived history.+ let selfLinks = Set(before.filter {+ ["PersonRelationship", "RelationshipAssertion"].contains($0.entity) &&+ Set(($0.links["source"] ?? []) + ($0.links["target"] ?? [])) == [preview.source.stableID, preview.survivor.stableID]+ }.map(\.id))+ for id in selfLinks { all[id]?.setValue(Date(), forKey: "archivedAt") }+ for id in preview.selfConnections {+ try record(id, entity: "Connection", in: context).setValue(Date(), forKey: "archivedAt")+ }+ source.setValue(survivor, forKey: "mergedInto")+ source.setValue(Date(), forKey: "archivedAt")+ source.setValue(Date(), forKey: "modifiedAt")+ let after = try MergeSnapshot.records(family: family, in: context)+ let old = Dictionary(uniqueKeysWithValues: before.map { ($0.id, $0) })+ let changed = after.filter { old[$0.id] != $0 }+ let changedIDs = Set(changed.map(\.id))+ let audit = insert("PersonMerge", in: context, store: try owningStore(of: family))+ audit.setValue(family, forKey: "familySpace")+ audit.setValue(preview.source.stableID, forKey: "sourceID")+ audit.setValue(preview.survivor.stableID, forKey: "survivorID")+ audit.setValue(preview.source.name, forKey: "sourceName")+ audit.setValue(preview.survivor.name, forKey: "survivorName")+ audit.setValue(Date(), forKey: "createdAt")+ let recoveries = NSFetchRequest<NSManagedObject>(entityName: "PersonMergeRecovery")+ recoveries.predicate = NSPredicate(format: "familySpace == %@", family)+ let recoveryIDs = try context.fetch(recoveries).map(stable).sorted { $0.uuidString < $1.uuidString }+ audit.setValue(String(data: try JSONEncoder().encode(recoveryIDs), encoding: .utf8), forKey: "recoveryIDs")+ audit.setValue(try MergeSnapshot.encode(before.filter { changedIDs.contains($0.id) }), forKey: "beforeData")+ audit.setValue(try MergeSnapshot.encode(changed), forKey: "afterData")+ let archivedIDs = Set(changed.filter {+ $0.entity == "Connection" && $0.attributes["archivedAt"] != nil && old[$0.id]?.attributes["archivedAt"] == nil+ }.map(\.id))+ audit.setValue(try MergeSnapshot.encode(after.filter {+ archivedIDs.contains($0.id) || !archivedIDs.isDisjoint(with: $0.links["connection"] ?? [])+ }), forKey: "archivedData")+ try requireMergeWritePermissions(context)+ return audit+ }+ }++ private func applyPersonFields(source: NSManagedObject, survivor: NSManagedObject, choices: PersonMergeChoices) throws {+ let selectedName = choices.name == .source ? source : survivor+ survivor.setValue(try validated(selectedName.value(forKey: "displayName") as? String ?? ""), forKey: "displayName")+ let sourceNotes = source.value(forKey: "notes") as? String ?? ""+ let survivorNotes = survivor.value(forKey: "notes") as? String ?? ""+ let notes: String+ switch choices.notes {+ case .source: notes = sourceNotes+ case .survivor: notes = survivorNotes+ case .both:+ notes = sourceNotes.isEmpty || sourceNotes == survivorNotes ? survivorNotes :+ (survivorNotes.isEmpty ? sourceNotes : survivorNotes + "\n\n" + sourceNotes)+ }+ survivor.setValue(notes.isEmpty ? nil : notes, forKey: "notes")+ let sensitive = choices.sensitive == .source ? source : survivor+ let sensitiveValues = ["isDeceased", "deathYear", "deathMonth", "deathDay"].map { sensitive.value(forKey: $0) }+ for (key, value) in zip(["isDeceased", "deathYear", "deathMonth", "deathDay"], sensitiveValues) {+ survivor.setValue(value, forKey: key)+ }+ if choices.photo == .source { survivor.setValue(source.value(forKey: "primaryPhoto"), forKey: "primaryPhoto") }+ // Person photos have a to-one owner. Keep both payloads, but only the selected photo is primary.+ source.setValue(nil, forKey: "primaryPhoto")+ let review = (source.value(forKey: "needsReview") as? Bool ?? false) || (survivor.value(forKey: "needsReview") as? Bool ?? false)+ survivor.setValue(review, forKey: "needsReview")+ survivor.setValue(Date(), forKey: "modifiedAt")+ }++ private func repointPersonReferences(_ object: NSManagedObject, from source: NSManagedObject, to survivor: NSManagedObject) throws {+ for (key, relationship) in object.entity.relationshipsByName where relationship.destinationEntity?.name == "Person" {+ if relationship.isToMany {+ var people = object.value(forKey: key) as? Set<NSManagedObject> ?? []+ if people.remove(source) != nil { people.insert(survivor); object.setValue(people, forKey: key) }+ } else if (object.value(forKey: key) as? NSManagedObject) == source {+ object.setValue(survivor, forKey: key)+ }+ }+ }++ private func validateMergeChoices(_ overlaps: [MergeConnectionOverlap], choices: PersonMergeChoices) throws {+ for overlap in overlaps {+ guard let choice = choices.connections[overlap.id], overlap.origins.contains(where: { $0.id == choice.originID }),+ overlap.closeness.isEmpty || overlap.closeness.contains(where: { $0.id == choice.closenessID }),+ overlap.statuses.isEmpty || overlap.statuses.contains(where: { $0.id == choice.statusID }) else {+ throw MergeError.choiceRequired+ }+ }+ }++ private func consolidate(_ overlap: MergeConnectionOverlap, choices: MergeConnectionChoices,+ family: NSManagedObject, in context: NSManagedObjectContext) throws {+ let kept = try record(overlap.keptID, entity: "Connection", in: context)+ guard let chosen = overlap.origins.first(where: { $0.id == choices.originID }) else { throw MergeError.choiceRequired }+ var predecessors = try preparedHeads(connection: kept, heads: originHeads(connection: kept, in: context), in: context)+ for origin in overlap.origins where origin.connectionID != kept.objectID && origin.recordID != nil {+ // Preserve original immutable accounts on the archived connection; copy them as merge alternatives.+ let input = OriginInput(contextID: origin.contextID, eventID: origin.eventID, narrative: origin.narrative)+ let copy = try makeProposal(input: input, cleared: origin.cleared, connection: kept, predecessors: [], in: context)+ predecessors.append(copy)+ }+ if !predecessors.isEmpty || !chosen.cleared {+ _ = try makeProposal(input: OriginInput(contextID: chosen.contextID, eventID: chosen.eventID, narrative: chosen.narrative),+ cleared: chosen.cleared, connection: kept, predecessors: predecessors, in: context)+ }+ let store = try owningStore(of: family)+ if let selected = overlap.closeness.first(where: { $0.id == choices.closenessID }) {+ try mergePeriod("ConnectionClosenessPeriod", kept: kept, family: family, store: store, in: context) {+ $0.setValue(selected.value, forKey: "value")+ }+ }+ if let selected = overlap.statuses.first(where: { $0.id == choices.statusID }) {+ try mergePeriod("ConnectionStatusPeriod", kept: kept, family: family, store: store, in: context) {+ $0.setValue(selected.state?.rawValue, forKey: "state"); $0.setValue(selected.note, forKey: "note")+ }+ }+ for id in overlap.connections where id != kept.objectID {+ let connection = try record(id, entity: "Connection", in: context)+ let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionContext")+ request.predicate = NSPredicate(format: "connection == %@", connection)+ for membership in try context.fetch(request) { membership.setValue(kept, forKey: "connection") }+ connection.setValue(kept, forKey: "mergedInto")+ connection.setValue(Date(), forKey: "archivedAt")+ }+ }++ private func mergePeriod(_ entity: String, kept: NSManagedObject, family: NSManagedObject, store: NSPersistentStore,+ in context: NSManagedObjectContext, configure: (NSManagedObject) -> Void) throws {+ let request = NSFetchRequest<NSManagedObject>(entityName: entity)+ request.predicate = NSPredicate(format: "connection == %@ AND endedAt == nil", kept)+ let previous = try context.fetch(request)+ let now = max(Date(), previous.compactMap { $0.value(forKey: "startedAt") as? Date }.max() ?? Date())+ for period in previous { period.setValue(now, forKey: "endedAt") }+ let period = insert(entity, in: context, store: store)+ period.setValue(family, forKey: "familySpace"); period.setValue(kept, forKey: "connection")+ period.setValue(now, forKey: "startedAt")+ configure(period)+ }++ func requireMergeWritePermissions(_ context: NSManagedObjectContext) throws {+ guard let cloud = stack.container as? NSPersistentCloudKitContainer else { return }+ for object in context.updatedObjects where !object.objectID.isTemporaryID {+ guard cloud.canUpdateRecord(forManagedObjectWith: object.objectID) else { throw GraphError.readOnly }+ }+ for object in context.deletedObjects {+ guard cloud.canDeleteRecord(forManagedObjectWith: object.objectID) else { throw GraphError.readOnly }+ }+ }+}
diff --git a/Halo Family/Halo Family/Persistence/PersonMergeTypes.swift b/Halo Family/Halo Family/Persistence/PersonMergeTypes.swiftnew file mode 100644index 0000000..4ffcf37--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PersonMergeTypes.swift @@ -0,0 +1,110 @@+import CoreData+import Foundation++nonisolated enum MergeSide: String, CaseIterable, Identifiable, Sendable {+ case survivor, source+ var id: Self { self }+ var label: String { self == .survivor ? "Kept person" : "Person being merged" }+}++nonisolated enum MergeNotesChoice: String, CaseIterable, Identifiable, Sendable {+ case both, survivor, source+ var id: Self { self }+ var label: String {+ switch self {+ case .both: "Keep both notes"+ case .survivor: "Kept person's notes"+ case .source: "Other person's notes"+ }+ }+}++struct MergePersonValues {+ let id: NSManagedObjectID+ let stableID: UUID+ let name: String+ let notes: String+ let sensitive: SensitiveSnapshot+ let photoID: NSManagedObjectID?+}++struct MergeOriginChoice: Identifiable {+ let id: UUID+ let recordID: NSManagedObjectID?+ let connectionID: NSManagedObjectID+ let label: String+ let contextID: NSManagedObjectID?+ let eventID: NSManagedObjectID?+ let narrative: String+ let cleared: Bool+ let proposal: Bool+}++struct MergePeriodChoice: Identifiable {+ let id: NSManagedObjectID+ let label: String+ let value: Int16?+ let state: ConnectionState?+ let note: String+}++struct MergeConnectionOverlap: Identifiable {+ let id: UUID+ let keptID: NSManagedObjectID+ let connections: [NSManagedObjectID]+ let childName: String+ let personName: String+ let origins: [MergeOriginChoice]+ let closeness: [MergePeriodChoice]+ let statuses: [MergePeriodChoice]+}++struct PersonMergePreview {+ let familyID: NSManagedObjectID+ let source: MergePersonValues+ let survivor: MergePersonValues+ let records: [MergeRecord]+ let overlaps: [MergeConnectionOverlap]+ let referenceCounts: [String: Int]+ let combinesChildProfiles: Bool+ let selfRelationships: Int+ let selfConnections: [NSManagedObjectID]+ let duplicateEventAccounts: Int+}++struct MergeConnectionChoices: Equatable {+ var originID: UUID?+ var closenessID: NSManagedObjectID?+ var statusID: NSManagedObjectID?+}++struct PersonMergeChoices: Equatable {+ var name: MergeSide = .survivor+ var notes: MergeNotesChoice = .both+ var photo: MergeSide = .survivor+ var sensitive: MergeSide = .survivor+ var connections: [UUID: MergeConnectionChoices] = [:]+}++struct PersonMergeHistoryRow: Identifiable {+ let id: NSManagedObjectID+ let sourceName: String+ let survivorName: String+ let sourceID: NSManagedObjectID?+ let survivorID: NSManagedObjectID?+ let createdAt: Date?+ let undone: Bool+ let undoAvailable: Bool+}++struct DuplicatePersonPair: Identifiable {+ let source: GraphRow+ let survivor: GraphRow+ let id: String+}++struct PersonMergeRecoveryRow: Identifiable {+ let id: NSManagedObjectID+ let createdAt: Date?+ let people: [MergeRecord]+}
diff --git a/Halo Family/Halo Family/Persistence/RelationshipMutations.swift b/Halo Family/Halo Family/Persistence/RelationshipMutations.swiftnew file mode 100644index 0000000..58dd837--- /dev/null+++ b/Halo Family/Halo Family/Persistence/RelationshipMutations.swift @@ -0,0 +1,182 @@+import CoreData+import Foundation++struct OriginInput {+ var contextID: NSManagedObjectID?+ var eventID: NSManagedObjectID?+ var narrative = ""+}++@MainActor+extension FamilyRepository {+ func addPerson(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)+ return makePerson(name: name, family: family, store: try owningStore(of: family), context: context, needsReview: true)+ }+ }++ func updatePerson(_ personID: NSManagedObjectID, name: String, notes: String,+ needsReview: Bool, expected: PersonDetail) throws {+ let name = try validated(name)+ _ = try write { context in+ let person = try record(personID, entity: "Person", in: context)+ guard expected.id == personID,+ (person.value(forKey: "displayName") as? String ?? "Unnamed") == expected.name,+ (person.value(forKey: "notes") as? String ?? "") == expected.notes,+ (person.value(forKey: "needsReview") as? Bool ?? false) == expected.needsReview else {+ throw GraphError.personChanged+ }+ person.setValue(name, forKey: "displayName")+ person.setValue(notes.trimmingCharacters(in: .whitespacesAndNewlines), forKey: "notes")+ person.setValue(needsReview, forKey: "needsReview")+ person.setValue(Date(), forKey: "modifiedAt")+ return person+ }+ }++ func createContext(name: String, familyID: NSManagedObjectID, parentID: NSManagedObjectID? = nil) throws -> NSManagedObjectID {+ let name = try validated(name)+ return try write { context in+ let family = try record(familyID, entity: "FamilySpace", in: context)+ let parent = try parentID.map { try record($0, entity: "Context", in: context) }+ if let parent { try requireSameFamily(parent, family: family) }+ let source = insert("Context", in: context, store: try owningStore(of: family))+ source.setValue(name, forKey: "name")+ source.setValue(family, forKey: "familySpace")+ source.setValue(parent, forKey: "parent")+ return source+ }+ }++ func moveContext(_ contextID: NSManagedObjectID, parentID: NSManagedObjectID?) throws {+ _ = try write { context in+ let source = try record(contextID, entity: "Context", in: context)+ let family = try family(of: source)+ let parent = try parentID.map { try record($0, entity: "Context", in: context) }+ if let parent { try requireSameFamily(parent, family: family) }+ var current = parent+ var seen: Set<NSManagedObjectID> = [source.objectID]+ while let node = current {+ guard seen.insert(node.objectID).inserted else { throw GraphError.contextCycle }+ current = node.value(forKey: "parent") as? NSManagedObject+ }+ source.setValue(parent, forKey: "parent")+ return source+ }+ }++ func archiveContext(_ contextID: NSManagedObjectID, archived: Bool) throws {+ _ = try write { context in+ let source = try record(contextID, entity: "Context", in: context)+ source.setValue(archived ? Date() : nil, forKey: "archivedAt")+ return source+ }+ }++ func addMembership(connectionID: NSManagedObjectID, contextID: NSManagedObjectID,+ startedAt: Date? = nil, endedAt: Date? = nil) throws -> NSManagedObjectID {+ try validateDates(startedAt, endedAt)+ return try write { context in+ let connection = try record(connectionID, entity: "Connection", in: context)+ let source = try record(contextID, entity: "Context", in: context)+ let family = try family(of: connection)+ try requireSameFamily(source, family: family)+ let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionContext")+ request.predicate = NSPredicate(format: "connection == %@ AND context == %@ AND endedAt == nil", connection, source)+ if endedAt == nil, try context.count(for: request) > 0 { throw GraphError.duplicateMembership }+ let membership = insert("ConnectionContext", in: context, store: try owningStore(of: family))+ membership.setValue(family, forKey: "familySpace")+ membership.setValue(connection, forKey: "connection")+ membership.setValue(source, forKey: "context")+ membership.setValue(startedAt, forKey: "startedAt")+ membership.setValue(endedAt, forKey: "endedAt")+ return membership+ }+ }++ func endMembership(_ membershipID: NSManagedObjectID, at date: Date) throws {+ _ = try write { context in+ let membership = try record(membershipID, entity: "ConnectionContext", in: context)+ guard let connection = membership.value(forKey: "connection") as? NSManagedObject else { throw GraphError.invalidReference }+ _ = try record(connection.objectID, entity: "Connection", in: context)+ try validateDates(membership.value(forKey: "startedAt") as? Date, date)+ membership.setValue(date, forKey: "endedAt")+ return membership+ }+ }++ func createEvent(title: String, date: Date, notes: String = "", familyID: NSManagedObjectID) throws -> NSManagedObjectID {+ let title = try validated(title)+ return try write { context in+ let family = try record(familyID, entity: "FamilySpace", in: context)+ let event = insert("Event", in: context, store: try owningStore(of: family))+ event.setValue(family, forKey: "familySpace")+ event.setValue(title, forKey: "title")+ event.setValue(date, forKey: "date")+ event.setValue(notes.trimmingCharacters(in: .whitespacesAndNewlines), forKey: "notes")+ event.setValue(Date(), forKey: "createdAt")+ return event+ }+ }++ func associatePerson(_ personID: NSManagedObjectID, contextID: NSManagedObjectID, role: String = "",+ startedAt: Date? = nil, endedAt: Date? = nil) throws -> NSManagedObjectID {+ try validateDates(startedAt, endedAt)+ let role = role.trimmingCharacters(in: .whitespacesAndNewlines)+ return try write { context in+ let person = try record(personID, entity: "Person", in: context)+ let source = try record(contextID, entity: "Context", in: context)+ let family = try family(of: source)+ try requireSameFamily(person, family: family)+ let request = NSFetchRequest<NSManagedObject>(entityName: "ContextPerson")+ request.predicate = NSPredicate(format: "person == %@ AND context == %@", person, source)+ if let existing = try context.fetch(request).first(where: {+ ($0.value(forKey: "role") as? String ?? "") == role &&+ $0.value(forKey: "startedAt") as? Date == startedAt && $0.value(forKey: "endedAt") as? Date == endedAt+ }) { return existing }+ let link = insert("ContextPerson", in: context, store: try owningStore(of: family))+ link.setValue(family, forKey: "familySpace")+ link.setValue(person, forKey: "person")+ link.setValue(source, forKey: "context")+ link.setValue(role.isEmpty ? nil : role, forKey: "role")+ link.setValue(startedAt, forKey: "startedAt")+ link.setValue(endedAt, forKey: "endedAt")+ return link+ }+ }++ func updateRole(_ id: NSManagedObjectID, role: String, startedAt: Date?, endedAt: Date?,+ expected: ContextPersonRow) throws {+ try validateDates(startedAt, endedAt)+ _ = try write { context in+ let link = try record(id, entity: "ContextPerson", in: context)+ guard id == expected.id,+ (link.value(forKey: "person") as? NSManagedObject)?.objectID == expected.personID,+ (link.value(forKey: "context") as? NSManagedObject)?.objectID == expected.contextID,+ (link.value(forKey: "role") as? String ?? "") == expected.role,+ link.value(forKey: "startedAt") as? Date == expected.startedAt,+ link.value(forKey: "endedAt") as? Date == expected.endedAt else { throw GraphError.roleChanged }+ let role = role.trimmingCharacters(in: .whitespacesAndNewlines)+ link.setValue(role.isEmpty ? nil : role, forKey: "role")+ link.setValue(startedAt, forKey: "startedAt")+ link.setValue(endedAt, forKey: "endedAt")+ return link+ }+ }++ func family(of object: NSManagedObject) throws -> NSManagedObject {+ guard let family = object.value(forKey: "familySpace") as? NSManagedObject else { throw GraphError.invalidReference }+ return family+ }++ func requireSameFamily(_ object: NSManagedObject, family: NSManagedObject) throws {+ guard try self.family(of: object).objectID == family.objectID,+ object.objectID.persistentStore == family.objectID.persistentStore else { throw GraphError.differentFamily }+ }++ func validateDates(_ start: Date?, _ end: Date?) throws {+ if let start, let end, end < start { throw GraphError.invalidDates }+ }+}
diff --git a/Halo Family/Halo Family/Persistence/RelationshipQueries.swift b/Halo Family/Halo Family/Persistence/RelationshipQueries.swiftnew file mode 100644index 0000000..83c047e--- /dev/null+++ b/Halo Family/Halo Family/Persistence/RelationshipQueries.swift @@ -0,0 +1,190 @@+import CoreData+import Foundation++struct ContextRow: Identifiable, Equatable {+ let id: NSManagedObjectID+ let name: String+ let path: String+ let isArchived: Bool+}++struct MembershipRow: Identifiable, Equatable {+ let id: NSManagedObjectID+ let contextID: NSManagedObjectID+ let name: String+ let startedAt: Date?+ let endedAt: Date?+ let isArchived: Bool+}++struct OriginRow: Equatable {+ let id: NSManagedObjectID+ let contextID: NSManagedObjectID?+ let eventID: NSManagedObjectID?+ let sourceName: String?+ let narrative: String+ var revisionIDs: Set<UUID> = []+}++struct PersonDetail: Equatable {+ let id: NSManagedObjectID+ let name: String+ let notes: String+ let needsReview: Bool+}++struct EventRow: Identifiable, Equatable {+ let id: NSManagedObjectID+ let title: String+ let date: Date?+ let notes: String+ var type = ""+ var subjectID: NSManagedObjectID?+ var contextID: NSManagedObjectID?+ var isArchived = false++ var label: String {+ "\(title) — \(date?.formatted(date: .abbreviated, time: .omitted) ?? "Date not recorded")"+ }+}++struct ContextPersonRow: Identifiable, Equatable {+ let id: NSManagedObjectID+ let contextID: NSManagedObjectID+ let personID: NSManagedObjectID+ let name: String+ let role: String+ let startedAt: Date?+ let endedAt: Date?+}++struct ContextConnectionRow: Identifiable, Equatable {+ let id: NSManagedObjectID+ let connectionID: NSManagedObjectID+ let personName: String+ let childName: String+ let startedAt: Date?+ let endedAt: Date?+}++@MainActor+extension FamilyRepository {+ func people(in familyID: NSManagedObjectID, search: String = "", needsReview: Bool = false,+ includeDeceased: Bool = true) throws -> [GraphRow] {+ var predicates = [NSPredicate(format: "familySpace == %@", familyID)]+ if stack.container.managedObjectModel.entitiesByName["Person"]?.attributesByName["archivedAt"] != nil {+ let conflicted = try mergeConflicts(in: familyID).flatMap { $0.people.map(\.id) }+ predicates.append(NSPredicate(format: "(archivedAt == nil AND mergedInto == nil) OR SELF IN %@", conflicted))+ 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 needsReview { predicates.append(NSPredicate(format: "needsReview == YES")) }+ return try rows(entity: "Person", nameKey: "displayName", predicate: NSCompoundPredicate(andPredicateWithSubpredicates: predicates))+ }++ func person(_ id: NSManagedObjectID) throws -> PersonDetail {+ let person = try readable(id, entity: "Person")+ return PersonDetail(id: id, name: person.value(forKey: "displayName") as? String ?? "Unnamed",+ notes: person.value(forKey: "notes") as? String ?? "",+ needsReview: person.value(forKey: "needsReview") as? Bool ?? false)+ }++ func personID(for connectionID: NSManagedObjectID) throws -> NSManagedObjectID {+ let connection = try readable(connectionID, entity: "Connection")+ guard let person = connection.value(forKey: "person") as? NSManagedObject else { throw GraphError.invalidReference }+ return person.objectID+ }++ func connections(to personID: NSManagedObjectID) throws -> [GraphRow] {+ let modern = stack.container.managedObjectModel.entitiesByName["Connection"]?.attributesByName["archivedAt"] != nil+ return try rows(entity: "Connection", nameKey: "child.person.displayName", predicate: modern ?+ NSPredicate(format: "person == %@ AND archivedAt == nil AND mergedInto == nil", personID) :+ NSPredicate(format: "person == %@", personID))+ }++ func contextIsArchived(_ contextID: NSManagedObjectID) throws -> Bool {+ try readable(contextID, entity: "Context").value(forKey: "archivedAt") != nil+ }++ func contexts(in familyID: NSManagedObjectID, includeArchived: Bool = true) throws -> [ContextRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "Context")+ request.predicate = NSPredicate(format: "familySpace == %@", familyID)+ return try stack.container.viewContext.fetch(request).compactMap { object in+ let archived = object.value(forKey: "archivedAt") != nil+ guard includeArchived || !archived else { return nil }+ return ContextRow(id: object.objectID, name: object.value(forKey: "name") as? String ?? "Unnamed",+ path: contextPath(object), isArchived: archived)+ }.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }+ }++ func memberships(for connectionID: NSManagedObjectID) throws -> [MembershipRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionContext")+ request.predicate = NSPredicate(format: "connection == %@", connectionID)+ return try stack.container.viewContext.fetch(request).compactMap { object in+ guard let source = object.value(forKey: "context") as? NSManagedObject else { return nil }+ return MembershipRow(id: object.objectID, contextID: source.objectID, name: contextPath(source),+ startedAt: object.value(forKey: "startedAt") as? Date,+ endedAt: object.value(forKey: "endedAt") as? Date,+ isArchived: source.value(forKey: "archivedAt") != nil)+ }.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }+ }++ func events(in familyID: NSManagedObjectID, includeArchived: Bool = true) throws -> [EventRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "Event")+ request.predicate = NSPredicate(format: "familySpace == %@", familyID)+ request.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false), NSSortDescriptor(key: "title", ascending: true)]+ return try stack.container.viewContext.fetch(request).map(eventRow).filter { includeArchived || !$0.isArchived }+ }++ func contextConnections(_ contextID: NSManagedObjectID) throws -> [ContextConnectionRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionContext")+ request.predicate = NSPredicate(format: "context == %@", contextID)+ request.sortDescriptors = [NSSortDescriptor(key: "connection.person.displayName", ascending: true),+ NSSortDescriptor(key: "connection.child.person.displayName", ascending: true)]+ return try stack.container.viewContext.fetch(request).compactMap { membership in+ guard let connection = membership.value(forKey: "connection") as? NSManagedObject else { return nil }+ return ContextConnectionRow(id: membership.objectID, connectionID: connection.objectID,+ personName: connection.value(forKeyPath: "person.displayName") as? String ?? "Unnamed",+ childName: connection.value(forKeyPath: "child.person.displayName") as? String ?? "Unnamed",+ startedAt: membership.value(forKey: "startedAt") as? Date,+ endedAt: membership.value(forKey: "endedAt") as? Date)+ }+ }++ func contextPeople(_ contextID: NSManagedObjectID) throws -> [ContextPersonRow] {+ let request = NSFetchRequest<NSManagedObject>(entityName: "ContextPerson")+ request.predicate = NSPredicate(format: "context == %@", contextID)+ request.sortDescriptors = [NSSortDescriptor(key: "person.displayName", ascending: true),+ NSSortDescriptor(key: "role", ascending: true)]+ return try stack.container.viewContext.fetch(request).compactMap { object in+ guard let person = object.value(forKey: "person") as? NSManagedObject,+ let source = object.value(forKey: "context") as? NSManagedObject else { return nil }+ return ContextPersonRow(id: object.objectID, contextID: source.objectID, personID: person.objectID,+ name: person.value(forKey: "displayName") as? String ?? "Unnamed",+ role: object.value(forKey: "role") as? String ?? "",+ startedAt: object.value(forKey: "startedAt") as? Date,+ endedAt: object.value(forKey: "endedAt") as? Date)+ }+ }++ func readable(_ id: NSManagedObjectID, entity: String) throws -> NSManagedObject {+ guard !id.isTemporaryID, id.entity.name == entity,+ let store = id.persistentStore,+ stack.container.persistentStoreCoordinator.persistentStores.contains(store) else { throw GraphError.invalidReference }+ let object = try stack.container.viewContext.existingObject(with: id)+ guard !object.isDeleted else { throw GraphError.invalidReference }+ return object+ }++ func contextPath(_ object: NSManagedObject) -> String {+ var names: [String] = []+ var current: NSManagedObject? = object+ var seen: Set<NSManagedObjectID> = []+ while let context = current, seen.insert(context.objectID).inserted {+ names.append(context.value(forKey: "name") as? String ?? "Unnamed")+ current = context.value(forKey: "parent") as? NSManagedObject+ }+ return names.reversed().joined(separator: " › ")+ }+}
diff --git a/Halo Family/Halo Family/Persistence/ReviewRepository.swift b/Halo Family/Halo Family/Persistence/ReviewRepository.swiftnew file mode 100644index 0000000..afdb95b--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ReviewRepository.swift @@ -0,0 +1,37 @@+import CoreData+import Foundation++struct ConnectionReviewRow: Identifiable {+ let id: NSManagedObjectID+ let name: String+ let childName: String+ let originNeedsReview: Bool+ let relationshipNeedsReview: Bool+}++@MainActor+extension FamilyRepository {+ func reviewConnections(in familyID: NSManagedObjectID) throws -> [ConnectionReviewRow] {+ _ = try readable(familyID, entity: "FamilySpace")+ let request = NSFetchRequest<NSManagedObject>(entityName: "Connection")+ let modern = stack.container.managedObjectModel.entitiesByName["Connection"]?.attributesByName["archivedAt"] != nil+ request.predicate = modern ? NSPredicate(format: "familySpace == %@ AND archivedAt == nil AND mergedInto == nil", familyID) :+ NSPredicate(format: "familySpace == %@", familyID)+ request.sortDescriptors = [NSSortDescriptor(key: "person.displayName", ascending: true),+ NSSortDescriptor(key: "child.person.displayName", ascending: true)]+ request.relationshipKeyPathsForPrefetching = ["person", "child.person"]+ let connections = try stack.container.viewContext.fetch(request)+ let states = try connectionStates(connections.map(\.objectID))+ let origins = try conflictingOriginConnections(in: familyID)+ return connections.compactMap { connection in+ let originConflict = origins.contains(connection.objectID)+ let state = states[connection.objectID]+ let stateConflict = state?.statusNeedsReview == true || state?.closenessNeedsReview == true+ guard originConflict || stateConflict else { return nil }+ return ConnectionReviewRow(id: connection.objectID,+ name: connection.value(forKeyPath: "person.displayName") as? String ?? "Unnamed",+ childName: connection.value(forKeyPath: "child.person.displayName") as? String ?? "Unnamed",+ originNeedsReview: originConflict, relationshipNeedsReview: stateConflict)+ }+ }+}
diff --git a/Halo Family/Halo Family/Persistence/SyntheticLaunch.swift b/Halo Family/Halo Family/Persistence/SyntheticLaunch.swiftnew file mode 100644index 0000000..8fa757e--- /dev/null+++ b/Halo Family/Halo Family/Persistence/SyntheticLaunch.swift @@ -0,0 +1,15 @@+import Foundation++/// Debug UI checks use a fresh local directory and never open the App Group or CloudKit.+nonisolated enum SyntheticLaunch {+ static func directory(arguments: [String] = ProcessInfo.processInfo.arguments) throws -> URL? {+ guard let position = arguments.firstIndex(of: "--synthetic-store") else { return nil }+ guard arguments.indices.contains(position + 1) else { throw GraphError.invalidReference }+ let directory = URL(fileURLWithPath: arguments[position + 1], isDirectory: true).resolvingSymlinksInPath()+ let roots = [FileManager.default.temporaryDirectory, URL(fileURLWithPath: "/tmp", isDirectory: true)]+ guard roots.contains(where: {+ directory.path.hasPrefix($0.resolvingSymlinksInPath().path + "/")+ }) else { throw GraphError.invalidReference }+ return directory+ }+}
diff --git a/Halo Family/Halo Family/PersonMergeHistoryView.swift b/Halo Family/Halo Family/PersonMergeHistoryView.swiftnew file mode 100644index 0000000..d4ecf6c--- /dev/null+++ b/Halo Family/Halo Family/PersonMergeHistoryView.swift @@ -0,0 +1,124 @@+import Combine+import CoreData+import SwiftUI++struct PersonMergeHistoryView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ @State private var history: [PersonMergeHistoryRow] = []+ @State private var recoveries: [PersonMergeRecoveryRow] = []+ @State private var failure: String?++ var body: some View {+ List {+ if history.isEmpty && recoveries.isEmpty { Text("No people have been merged in this family.").foregroundStyle(.secondary) }+ ForEach(history) { merge in+ NavigationLink {+ MergeHistoryDetail(repository: repository, familyID: familyID, merge: merge)+ } label: {+ VStack(alignment: .leading) {+ Text("\(merge.sourceName) → \(merge.survivorName)")+ if let date = merge.createdAt { Text(date.formatted(date: .abbreviated, time: .shortened)).font(.caption) }+ Text(merge.undone ? "Undone" :+ (merge.undoAvailable ? "Undo available" : "Affected records changed; undo unavailable"))+ .font(.caption).foregroundStyle(.secondary)+ }+ }+ }+ if !recoveries.isEmpty {+ Section("Recovery history") {+ ForEach(recoveries) { recovery in+ NavigationLink {+ MemoryForm {+ MemorySection("Separate identities recovered") {+ Text("Recovery kept the current references and earlier merge audits. " ++ "These are the person details observed before clearing the competing aliases.")+ ForEach(recovery.people, id: \.id) { person in+ if case .text(let name) = person.attributes["displayName"] { Text(name).font(.headline) }+ if case .text(let notes) = person.attributes["notes"], !notes.isEmpty { Text(notes) }+ }+ }+ }.navigationTitle("Merge recovery")+ } label: {+ VStack(alignment: .leading) {+ Text("Separate identities recovered")+ if let date = recovery.createdAt {+ Text(date.formatted(date: .abbreviated, time: .shortened)).font(.caption)+ }+ }+ }+ }+ }+ }+ }+ .navigationTitle("Merge history")+ .task { reload() }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in reload() }+ .graphFailure($failure)+ }++ private func reload() {+ do {+ let history = try repository.mergeHistory(in: familyID)+ let recoveries = try repository.mergeRecoveryHistory(in: familyID)+ self.history = history; self.recoveries = recoveries+ } catch { failure = error.localizedDescription }+ }+}++private struct MergeHistoryDetail: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let merge: PersonMergeHistoryRow+ @State private var records: [MergeRecord] = []+ @State private var connections: [GraphRow] = []+ @State private var confirmingUndo = false+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ MemoryForm {+ MemorySection("Earlier person details") {+ ForEach(records.filter { $0.entity == "Person" }, id: \.id) { record in+ if case .text(let name) = record.attributes["displayName"] { Text(name).font(.headline) }+ if case .text(let notes) = record.attributes["notes"], !notes.isEmpty { Text(notes) }+ }+ }+ if let survivorID = merge.survivorID {+ MemorySection("Kept person") {+ NavigationLink(merge.survivorName) {+ PersonDetailView(repository: repository, familyID: familyID, personID: survivorID)+ }+ }+ }+ if !connections.isEmpty {+ MemorySection("Earlier relationship accounts") {+ ForEach(connections) { connection in+ NavigationLink(connection.name) {+ ConnectionDetailView(repository: repository, familyID: familyID, connection: connection, readOnly: true)+ }+ }+ }+ }+ MemorySection("Undo") {+ Text("Undo restores both people and their references only while affected records remain unchanged. " ++ "A fresh check is made before saving. Unrelated family records are preserved.")+ Button("Undo this merge") { confirmingUndo = true }.disabled(!merge.undoAvailable)+ }+ }+ .navigationTitle("\(merge.sourceName) → \(merge.survivorName)")+ .task {+ do {+ records = try repository.mergePreviousDetails(merge.id)+ connections = try repository.archivedMergeConnections(merge.id)+ } catch { failure = error.localizedDescription }+ }+ .confirmationDialog("Restore both people and their previous references?", isPresented: $confirmingUndo) {+ Button("Undo merge") {+ do { try repository.undoPersonMerge(merge.id); dismiss() } catch { failure = error.localizedDescription }+ }+ }+ .graphFailure($failure)+ }+}
diff --git a/Halo Family/Halo Family/PersonMergeView.swift b/Halo Family/Halo Family/PersonMergeView.swiftnew file mode 100644index 0000000..9bdc90f--- /dev/null+++ b/Halo Family/Halo Family/PersonMergeView.swift @@ -0,0 +1,200 @@+import CoreData+import SwiftUI++struct PersonMergeView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let sourceID: NSManagedObjectID+ @State private var survivorID: NSManagedObjectID?+ @State private var people: [GraphRow] = []+ @State private var preview: PersonMergePreview?+ @State private var choices = PersonMergeChoices()+ @State private var confirmed = false+ @State private var failure: String?+ @Environment(\.dismiss) private var dismiss++ init(repository: FamilyRepository, familyID: NSManagedObjectID, sourceID: NSManagedObjectID,+ preferredSurvivor: NSManagedObjectID? = nil) {+ self.repository = repository; self.familyID = familyID; self.sourceID = sourceID+ _survivorID = State(initialValue: preferredSurvivor)+ }++ var body: some View {+ NavigationStack {+ MemoryForm {+ MemorySection("Choose the person to keep") {+ MemoryField("Kept person") {+ Picker("Kept person", selection: $survivorID) {+ Text("Choose a person").tag(nil as NSManagedObjectID?)+ ForEach(people.filter { $0.id != sourceID }) { Text($0.name).tag(Optional($0.id)) }+ }+ }+ Button(preview == nil ? "Preview merge" : "Refresh preview") { prepare() }.disabled(survivorID == nil)+ Text("Only merge records that represent the same person. Similar names can belong to different people.")+ .font(.callout).foregroundStyle(.secondary)+ }+ if let preview {+ personChoices(preview)+ MemorySection("References and history") {+ ForEach(preview.referenceCounts.keys.sorted(), id: \.self) { key in+ Text("\(referenceLabel(key)): \(preview.referenceCounts[key] ?? 0)")+ }+ Text("The kept person's identity remains. The other person is retained as a hidden merge record. " ++ "Existing notes, photos and relationship accounts remain in the records or merge history.")+ if preview.combinesChildProfiles {+ Text("Both records are marked as our child. The kept person's child profile remains; " ++ "peer relationships are combined and the other profile is archived.")+ }+ if preview.selfRelationships > 0 {+ Text("\(preview.selfRelationships) family facts between these records will be archived, " ++ "because they would otherwise describe a person related to themselves.")+ }+ if !preview.selfConnections.isEmpty {+ Text("\(preview.selfConnections.count) child relationships will be archived because they would " ++ "otherwise list the child as someone they know. Their accounts remain in history.")+ }+ if preview.duplicateEventAccounts > 0 {+ Text("Existing participation accounts for the same event stay separate, " ++ "including their roles, invitations, attendance and notes.")+ }+ }+ ForEach(preview.overlaps) { overlap in overlapChoices(overlap) }+ MemorySection("Confirm the preview") {+ Toggle("These records are the same person, and I have reviewed these choices", isOn: $confirmed)+ Text("Undo is available in merge history while the affected records remain unchanged. " ++ "A later edit or new reference can make undo unavailable.")+ .font(.caption).foregroundStyle(.secondary)+ Button("Merge people") {+ do { _ = try repository.mergePeople(preview, choices: choices); dismiss() } catch {+ failure = error.localizedDescription+ }+ }.disabled(!confirmed || !complete(preview))+ }+ }+ }+ .navigationTitle("Merge people")+ .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } }+ }+ .frame(minWidth: 340, minHeight: 480)+ .task {+ do { people = try repository.people(in: familyID) } catch { failure = error.localizedDescription }+ }+ .onChange(of: survivorID) { preview = nil; confirmed = false }+ .onChange(of: choices) { confirmed = false }+ .graphFailure($failure)+ }++ @ViewBuilder private func personChoices(_ preview: PersonMergePreview) -> some View {+ MemorySection("\(preview.source.name) → \(preview.survivor.name)") {+ MemoryField("Name") {+ Picker("Name", selection: $choices.name) {+ Text(preview.survivor.name).tag(MergeSide.survivor)+ Text(preview.source.name).tag(MergeSide.source)+ }+ }+ if !preview.source.notes.isEmpty || !preview.survivor.notes.isEmpty {+ MemoryField("Notes") {+ Picker("Notes", selection: $choices.notes) {+ ForEach(MergeNotesChoice.allCases) { Text($0.label).tag($0) }+ }+ }+ if !preview.survivor.notes.isEmpty { Text("Kept person's notes: \(preview.survivor.notes)") }+ if !preview.source.notes.isEmpty { Text("Other person's notes: \(preview.source.notes)") }+ }+ if preview.source.photoID != nil || preview.survivor.photoID != nil {+ MemoryField("Primary photo") {+ Picker("Primary photo", selection: $choices.photo) {+ Text("Kept person: \(preview.survivor.photoID == nil ? "no photo" : "photo")").tag(MergeSide.survivor)+ Text("Other person: \(preview.source.photoID == nil ? "no photo" : "photo")").tag(MergeSide.source)+ }+ }+ }+ if preview.source.sensitive != preview.survivor.sensitive {+ MemoryField("Sensitive Details") {+ Picker("Sensitive Details", selection: $choices.sensitive) {+ Text("Kept person: \(sensitiveLabel(preview.survivor.sensitive))").tag(MergeSide.survivor)+ Text("Other person: \(sensitiveLabel(preview.source.sensitive))").tag(MergeSide.source)+ }+ }+ }+ }+ }++ @ViewBuilder private func overlapChoices(_ overlap: MergeConnectionOverlap) -> some View {+ MemorySection("\(overlap.childName) knows \(overlap.personName)") {+ Text("These records contain overlapping child relationships. One connection remains current; " ++ "the other connections and their accounts remain in merge history.")+ MemoryField("First meeting") {+ Picker("First meeting", selection: connectionBinding(overlap.id, \.originID)) {+ Text("Choose an account").tag(nil as UUID?)+ ForEach(overlap.origins) { Text($0.label).tag(Optional($0.id)) }+ }+ }+ ForEach(overlap.origins) { origin in+ if !origin.narrative.isEmpty { Text("\(origin.label) · \(origin.narrative)").font(.caption) }+ }+ if !overlap.closeness.isEmpty {+ MemoryField("Closeness") {+ Picker("Closeness", selection: connectionBinding(overlap.id, \.closenessID)) {+ Text("Choose a value").tag(nil as NSManagedObjectID?)+ ForEach(overlap.closeness) { Text($0.label).tag(Optional($0.id)) }+ }+ }+ }+ if !overlap.statuses.isEmpty {+ MemoryField("Contact status") {+ Picker("Contact status", selection: connectionBinding(overlap.id, \.statusID)) {+ Text("Choose an account").tag(nil as NSManagedObjectID?)+ ForEach(overlap.statuses) { Text($0.label + ($0.note.isEmpty ? "" : " · " + $0.note)).tag(Optional($0.id)) }+ }+ }+ }+ }+ }++ private func connectionBinding<Value>(_ id: UUID, _ key: WritableKeyPath<MergeConnectionChoices, Value>) -> Binding<Value> {+ Binding(get: { (choices.connections[id] ?? MergeConnectionChoices())[keyPath: key] }, set: { value in+ var current = choices.connections[id] ?? MergeConnectionChoices()+ current[keyPath: key] = value+ choices.connections[id] = current+ confirmed = false+ })+ }++ private func complete(_ preview: PersonMergePreview) -> Bool {+ preview.overlaps.allSatisfy {+ guard let selected = choices.connections[$0.id] else { return false }+ return selected.originID != nil && ($0.closeness.isEmpty || selected.closenessID != nil) &&+ ($0.statuses.isEmpty || selected.statusID != nil)+ }+ }++ private func prepare() {+ guard let survivorID else { return }+ do {+ preview = try repository.mergePreview(sourceID: sourceID, survivorID: survivorID)+ choices = PersonMergeChoices(); confirmed = false+ } catch { preview = nil; failure = error.localizedDescription }+ }++ private func sensitiveLabel(_ value: SensitiveSnapshot) -> String {+ value.isDeceased ? "Deceased" + (value.date.label.isEmpty ? "" : " · " + value.date.label) : "Not marked deceased"+ }++ private func referenceLabel(_ entity: String) -> String {+ switch entity {+ case "Connection": "Child relationships"+ case "ChildProfile": "Our child profiles"+ case "ContextPerson": "Roles in contexts"+ case "PersonRelationship": "Family facts"+ case "RelationshipAssertion": "Entered family descriptions"+ case "AddressLabel": "Address labels"+ case "GroupMembership": "Group memberships"+ case "EventPerson": "Event participation accounts"+ case "Event": "Event subjects"+ case "GiftRecord": "Gifts"+ case "Asset": "Photos"+ default: "Other references"+ }+ }+}
diff --git a/Halo Family/Halo Family/PhotoAssetViews.swift b/Halo Family/Halo Family/PhotoAssetViews.swiftnew file mode 100644index 0000000..927eecd--- /dev/null+++ b/Halo Family/Halo Family/PhotoAssetViews.swift @@ -0,0 +1,186 @@+import CoreData+import PhotosUI+import SwiftUI+import UniformTypeIdentifiers+import QuickLook+import ImageIO+import Combine+import CoreTransferable++nonisolated struct PickedPhoto: Transferable, Sendable {+ let data: Data+ static var transferRepresentation: some TransferRepresentation {+ FileRepresentation(importedContentType: .image) { received in+ // Photos supplies a temporary file. Check its size before materializing the bytes.+ PickedPhoto(data: try ImportedFile.read(received.file))+ }+ }+}++nonisolated enum ImportedFile {+ static func read(_ url: URL) throws -> Data {+ let scoped = url.startAccessingSecurityScopedResource()+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }+ let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0+ guard size <= ImageImport.attachmentLimit else { throw MemoryError.fileTooLarge }+ let data = try Data(contentsOf: url, options: .mappedIfSafe)+ guard data.count <= ImageImport.attachmentLimit else { throw MemoryError.fileTooLarge }+ return data+ }+}++private actor ThumbnailCache {+ static let shared = ThumbnailCache()+ private var images: [String: Data] = [:]+ func cached(_ key: String) -> Data? { images[key] }++ func thumbnail(data: Data, key: String) throws -> Data {+ if let cached = images[key] { return cached }+ guard let source = CGImageSourceCreateWithData(data as CFData, nil),+ let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [+ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceThumbnailMaxPixelSize: 320,+ kCGImageSourceCreateThumbnailWithTransform: true,+ ] as CFDictionary) else { throw MemoryError.invalidImage }+ let output = NSMutableData()+ guard let destination = CGImageDestinationCreateWithData(output, UTType.jpeg.identifier as CFString, 1, nil) else {+ throw MemoryError.invalidImage+ }+ CGImageDestinationAddImage(destination, image, nil)+ guard CGImageDestinationFinalize(destination) else { throw MemoryError.invalidImage }+ if images.count >= 60 { images.removeAll() }+ images[key] = output as Data+ return output as Data+ }+}++struct AssetThumbnail: View {+ let assets: AssetRepository+ let assetID: NSManagedObjectID+ @State private var image: Image?+ @State private var failure: String?+ @State private var refresh = 0++ var body: some View {+ Group {+ if let image { image.resizable().scaledToFit() } else if let failure {+ Text(failure).font(.caption).foregroundStyle(.secondary)+ } else { ProgressView() }+ }+ .frame(maxWidth: 160, maxHeight: 160)+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: assets.container)+ .receive(on: DispatchQueue.main)) { _ in refresh += 1 }+ .task(id: "\(assetID.uriRepresentation().absoluteString)|\(refresh)") {+ do {+ let revision = try await assets.revision(for: assetID)+ let thumbnail: Data+ if let cached = await ThumbnailCache.shared.cached(revision) { thumbnail = cached } else {+ let data = try await assets.data(for: assetID)+ thumbnail = try await ThumbnailCache.shared.thumbnail(data: data, key: revision)+ }+ try Task.checkCancellation()+ #if os(macOS)+ if let native = NSImage(data: thumbnail) { image = Image(nsImage: native) }+ #else+ if let native = UIImage(data: thumbnail) { image = Image(uiImage: native) }+ #endif+ } catch { failure = error.localizedDescription }+ }+ }+}++struct PhotoImportControls: View {+ let repository: FamilyRepository+ let personID: NSManagedObjectID+ @State private var photo: PhotosPickerItem?+ @State private var importing = false+ @State private var working = false+ @State private var failure: String?+ @State private var importTask: Task<Void, Never>?++ var body: some View {+ VStack(alignment: .leading, spacing: 12) {+ PhotosPicker("Choose a photo", selection: $photo, matching: .images, preferredItemEncoding: .compatible)+ .disabled(working).accessibilityIdentifier("person.photo.choose")+ Button("Import image from Files") { importing = true }.disabled(working)+ if working { ProgressView("Saving photo…") }+ Text("JPEG/PNG; saved at up to 2048 pixels and 4 MB. Image location metadata is removed.")+ .font(.caption).foregroundStyle(.secondary)+ }+ .fileImporter(isPresented: $importing, allowedContentTypes: [.jpeg, .png]) { result in+ do {+ let url = try result.get()+ begin {+ let data = try await Task.detached { try ImportedFile.read(url) }.value+ _ = try await AssetRepository(stack: repository.stack).importPhoto(data, filename: url.lastPathComponent,+ personID: personID)+ }+ } catch { failure = error.localizedDescription }+ }+ .onChange(of: photo) {+ guard let photo else { return }+ begin {+ guard let selected = try await photo.loadTransferable(type: PickedPhoto.self) else { throw MemoryError.invalidImage }+ _ = try await AssetRepository(stack: repository.stack).importPhoto(selected.data, filename: "Person.jpg",+ personID: personID)+ }+ }+ .onDisappear { importTask?.cancel() }+ .graphFailure($failure)+ }++ private func begin(_ action: @escaping () async throws -> Void) {+ guard !working else { return }+ working = true+ importTask = Task {+ defer { working = false; importTask = nil; photo = nil }+ do { try await action() } catch { if !Task.isCancelled { failure = error.localizedDescription } }+ }+ }+}++struct AttachmentPreview: View {+ let assets: AssetRepository+ let attachment: AttachmentRow+ @State private var previewURL: URL?+ @State private var folder: URL?+ @State private var failure: String?+ @State private var preparation: Task<Void, Never>?+ @State private var working = false++ var body: some View {+ Button(attachment.title, systemImage: "doc") {+ guard !working else { return }+ working = true+ preparation = Task {+ var createdDirectory: URL?+ defer { working = false; preparation = nil }+ do {+ let data = try await assets.data(for: attachment.assetID)+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)+ createdDirectory = directory+ let suffix = attachment.contentType == UTType.pdf.identifier ? "pdf" :+ (attachment.contentType == UTType.png.identifier ? "png" : "jpg")+ let url = directory.appendingPathComponent("Attachment.\(suffix)")+ try await Task.detached {+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ try data.write(to: url, options: .atomic)+ }.value+ try Task.checkCancellation()+ if let folder { try? FileManager.default.removeItem(at: folder) }+ folder = directory+ previewURL = url+ } catch {+ if let createdDirectory { try? FileManager.default.removeItem(at: createdDirectory) }+ if !Task.isCancelled { failure = error.localizedDescription }+ }+ }+ }+ .disabled(working)+ .quickLookPreview($previewURL)+ .onDisappear {+ preparation?.cancel()+ if let folder { try? FileManager.default.removeItem(at: folder) }+ }+ .graphFailure($failure)+ }+}
diff --git a/Halo Family/Halo Family/ShareInvitations.swift b/Halo Family/Halo Family/ShareInvitations.swiftnew file mode 100644index 0000000..c83fcd7--- /dev/null+++ b/Halo Family/Halo Family/ShareInvitations.swift @@ -0,0 +1,69 @@+import CloudKit+import Observation+import SwiftUI++@MainActor+@Observable+final class ShareInvitations {+ static let shared = ShareInvitations()+ private(set) var issue: String?+ private(set) var isAccepting = false+ private var pending: [CKShare.Metadata] = []++ func receive(_ metadata: CKShare.Metadata) {+ guard metadata.containerIdentifier == StoreConfiguration.cloudContainer else {+ issue = SharingError.wrongContainer.localizedDescription+ return+ }+ guard !pending.contains(where: { $0.share.recordID == metadata.share.recordID }) else { return }+ pending.append(metadata)+ Task { await retry() }+ }++ func retry() async {+ guard !isAccepting, !pending.isEmpty else { return }+ isAccepting = true+ defer { isAccepting = false }+ do {+ let sharing = FamilySharing(stack: try await .production())+ while let metadata = pending.first {+ try await sharing.accept(metadata)+ pending.removeFirst()+ }+ issue = nil+ } catch {+ issue = "Couldn’t accept the family invitation: \(error.localizedDescription)"+ }+ }+}++#if os(iOS)+import UIKit++final class HaloApplicationDelegate: NSObject, UIApplicationDelegate {+ func application(_ application: UIApplication, configurationForConnecting session: UISceneSession,+ options: UIScene.ConnectionOptions) -> UISceneConfiguration {+ let configuration = UISceneConfiguration(name: session.configuration.name, sessionRole: session.role)+ configuration.delegateClass = HaloSceneDelegate.self+ return configuration+ }+}++final class HaloSceneDelegate: NSObject, UIWindowSceneDelegate {+ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) {+ if let metadata = options.cloudKitShareMetadata { ShareInvitations.shared.receive(metadata) }+ }++ func windowScene(_ windowScene: UIWindowScene, userDidAcceptCloudKitShareWith metadata: CKShare.Metadata) {+ ShareInvitations.shared.receive(metadata)+ }+}+#elseif os(macOS)+import AppKit++final class HaloApplicationDelegate: NSObject, NSApplicationDelegate {+ func application(_ application: NSApplication, userDidAcceptCloudKitShareWith metadata: CKShare.Metadata) {+ ShareInvitations.shared.receive(metadata)+ }+}+#endif
diff --git a/Halo Family/Halo Family/TemporalConflictReview.swift b/Halo Family/Halo Family/TemporalConflictReview.swiftnew file mode 100644index 0000000..9d311fe--- /dev/null+++ b/Halo Family/Halo Family/TemporalConflictReview.swift @@ -0,0 +1,41 @@+import CoreData+import SwiftUI++struct TemporalConflictReview: View {+ let repository: FamilyRepository+ let connectionID: NSManagedObjectID+ let closeness: Bool+ let resolved: () throws -> Void+ @State private var periods: [StatePeriodRow] = []+ @State private var failure: String?+ var body: some View {+ VStack(alignment: .leading, spacing: 12) {+ Text("Choose the current value. Every earlier account stays in the relationship history.").foregroundStyle(.secondary)+ ForEach(periods) { period in+ VStack(alignment: .leading, spacing: 4) {+ let label = period.value.map { ClosenessChoice(rawValue: $0)?.label ?? "\($0) of 10" } ?? period.state?.label ?? "Not recorded"+ Text(label).font(.headline)+ if !period.note.isEmpty { Text(period.note) }+ if let date = period.startedAt { Text(date, style: .date).font(.caption).foregroundStyle(.secondary) }+ Button("Use this value") {+ do {+ let reviewed = Set(periods.map(\.id))+ if let value = period.value {+ try repository.resolveCloseness(value, connectionID: connectionID, reviewed: reviewed)+ } else if let state = period.state {+ try repository.resolveStatus(state, note: period.note, connectionID: connectionID, reviewed: reviewed)+ }+ try resolved()+ } catch { failure = error.localizedDescription }+ }+ }+ }+ }+ .task {+ do {+ periods = try repository.currentStatePeriods(connectionID, closeness: closeness)+ } catch { failure = error.localizedDescription }+ }+ .graphFailure($failure)+ }+}
diff --git a/Halo Family/Halo-Family-Info.plist b/Halo Family/Halo-Family-Info.plistindex ca9a074..9ef96ef 100644--- a/Halo Family/Halo-Family-Info.plist +++ b/Halo Family/Halo-Family-Info.plist @@ -2,6 +2,8 @@ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict>+ <key>CKSharingSupported</key>+ <true/> <key>UIBackgroundModes</key> <array> <string>remote-notification</string>
diff --git a/Makefile b/Makefileindex 18dde14..b531e3e 100644--- a/Makefile+++ b/Makefile@@ -9,6 +9,7 @@ DERIVED_DATA ?= ./DerivedData IOS_DESTINATION ?= generic/platform=iOS Simulator MAC_DESTINATION ?= platform=macOS APP_NAME ?= Halo Family+TEST_FLAGS ?= # Match paired devices even when their wireless tunnel is idle. Device names # and product types remain available when devicectl's marketingName is null.@@ -131,4 +132,4 @@ clean: .PHONY: test test:- swift test --scratch-path "$(DERIVED_DATA)/swift-tests"+ swift test --scratch-path "$(DERIVED_DATA)/swift-tests" $(TEST_FLAGS)
diff --git a/Tests/HaloPersistenceTests/ApprovedDefaultsTests.swift b/Tests/HaloPersistenceTests/ApprovedDefaultsTests.swiftnew file mode 100644index 0000000..4c97947--- /dev/null+++ b/Tests/HaloPersistenceTests/ApprovedDefaultsTests.swift@@ -0,0 +1,327 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct ApprovedDefaultsTests {+ private func withConnection(_ test: (PersistenceStack, FamilyRepository, NSManagedObjectID, NSManagedObjectID) 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+ let graph = FamilyRepository(stack: stack)+ let family = try graph.createFamily(name: "Synthetic family")+ let child = try graph.addChild(name: "Child", familyID: family)+ let connection = try graph.quickCapture(name: "Friend", childID: child)+ try test(stack, graph, family, connection)+ }++ /// Models an imported immutable proposal made by another offline observer of this predecessor.+ /// This is a causal branch fixture, not live CloudKit transport evidence.+ private func importedProposal(stack: PersistenceStack, connectionID: NSManagedObjectID, predecessor: NSManagedObjectID,+ narrative: String, cleared: Bool = false) throws -> NSManagedObjectID {+ let context = stack.container.viewContext+ let connection = try context.existingObject(with: connectionID)+ let family = try #require(connection.value(forKey: "familySpace") as? NSManagedObject)+ let parent = try context.existingObject(with: predecessor)+ let proposal = NSEntityDescription.insertNewObject(forEntityName: "OriginProposal", into: context)+ context.assign(proposal, to: try #require(family.objectID.persistentStore))+ proposal.setValue(UUID(), forKey: "id")+ proposal.setValue(family, forKey: "familySpace")+ proposal.setValue(connection, forKey: "connection")+ proposal.setValue(narrative, forKey: "narrative")+ proposal.setValue(cleared, forKey: "isCleared")+ proposal.setValue(Date(timeIntervalSince1970: 1), forKey: "createdAt")+ proposal.setValue(Set([parent]), forKey: "predecessors")+ try context.save()+ return proposal.objectID+ }++ @Test func simultaneousFirstOriginAccountsRemainSeparateWithoutAPredecessor() throws {+ try withConnection { stack, graph, _, connection in+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Birthday"), expectedOrigin: nil)+ let first = try #require(try graph.originHistory(for: connection).first)+ let second = try importedProposal(stack: stack, connectionID: connection, predecessor: first.id, narrative: "Swimming")+ let object = try stack.container.viewContext.existingObject(with: second)+ object.setValue(Set<NSManagedObject>(), forKey: "predecessors")+ try stack.container.viewContext.save()+ let conflicts = try graph.originOverview(for: connection)+ #expect(Set(conflicts.conflicts.map(\.narrative)) == ["Birthday", "Swimming"])+ try graph.resolveOrigin(connectionID: connection, choosing: second, expectedHeads: conflicts.headIDs)+ #expect(try graph.origin(for: connection)?.narrative == "Swimming")+ #expect(try graph.originHistory(for: connection).count == 3)+ }+ }++ @Test func contextMembershipRowsKeepChildIdentityAndHistoryForOneSharedPerson() throws {+ try withConnection { _, graph, family, connection in+ let person = try graph.personID(for: connection)+ let sibling = try graph.addChild(name: "Sibling", familyID: family)+ let second = try graph.connect(personID: person, childID: sibling)+ let source = try graph.createContext(name: "Swimming", familyID: family)+ let old = try graph.addMembership(connectionID: connection, contextID: source)+ _ = try graph.addMembership(connectionID: second, contextID: source)+ try graph.endMembership(old, at: Date())+ let rows = try graph.contextConnections(source)+ #expect(Set(rows.map(\.childName)) == ["Child", "Sibling"])+ #expect(Set(rows.map(\.connectionID)) == [connection, second])+ #expect(rows.first(where: { $0.connectionID == connection })?.endedAt != nil)+ #expect(rows.first(where: { $0.connectionID == second })?.endedAt == nil)+ }+ }++ @Test func reviewQueriesAreFamilyScopedAndOriginResolutionClearsTheItem() throws {+ try withConnection { stack, graph, family, connection in+ let otherFamily = try graph.createFamily(name: "Other synthetic family")+ let child = try graph.addChild(name: "Other child", familyID: otherFamily)+ let otherConnection = try graph.quickCapture(name: "Other friend", childID: child)+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Birthday"), expectedOrigin: nil)+ let first = try #require(try graph.originHistory(for: connection).first)+ let second = try importedProposal(stack: stack, connectionID: connection, predecessor: first.id, narrative: "Swimming")+ let object = try stack.container.viewContext.existingObject(with: second)+ object.setValue(Set<NSManagedObject>(), forKey: "predecessors")+ try stack.container.viewContext.save()+ let items = try graph.reviewConnections(in: family)+ #expect(items.map(\.id) == [connection])+ #expect(items.first?.childName == "Child")+ #expect(items.first?.originNeedsReview == true)+ #expect(try graph.reviewConnections(in: otherFamily).isEmpty)+ try graph.setCloseness(.friend, connectionID: connection, expectedID: nil)+ try graph.setCloseness(.bff, connectionID: otherConnection, expectedID: nil)+ let batch = try graph.connectionStates([connection, connection, otherConnection])+ #expect(batch.count == 2)+ #expect(batch[connection]?.closeness == .friend)+ #expect(batch[otherConnection]?.closeness == .bff)+ let heads = try graph.originOverview(for: connection).headIDs+ try graph.resolveOrigin(connectionID: connection, choosing: second, expectedHeads: heads)+ #expect(try graph.reviewConnections(in: family).isEmpty)+ }+ }++ @Test func competingOriginsNeedReviewAndResolutionRetainsEveryAlternative() throws {+ try withConnection { stack, graph, _, connection in+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Original meeting"), expectedOrigin: nil)+ let root = try #require(try graph.originHistory(for: connection).first)+ let initial = try #require(try graph.origin(for: connection))+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Birthday"), expectedOrigin: initial)+ let swimming = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Swimming")+ let conflicts = try graph.originOverview(for: connection)+ #expect(Set(conflicts.conflicts.map(\.narrative)) == ["Birthday", "Swimming"])+ #expect(conflicts.origin == nil)+ #expect(throws: GraphError.self) { try graph.origin(for: connection) }+ #expect(throws: GraphError.self) {+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Overwrite"), expectedOrigin: nil)+ }+ try graph.resolveOrigin(connectionID: connection, choosing: swimming, expectedHeads: conflicts.headIDs)+ #expect(try graph.origin(for: connection)?.narrative == "Swimming")+ #expect(try graph.originOverview(for: connection).conflicts.isEmpty)+ let history = try graph.originHistory(for: connection)+ #expect(history.count == 4)+ #expect(Set(history.map(\.narrative)) == ["Original meeting", "Birthday", "Swimming"])+ #expect(Set(history.map(\.stableID)).count == 4)+ }+ }++ @Test func clearCompetingWithEditAndLateArrivalRemainReviewable() throws {+ try withConnection { stack, graph, _, connection in+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Playground"), expectedOrigin: nil)+ let original = try #require(try graph.origin(for: connection))+ let root = try #require(try graph.originHistory(for: connection).first)+ try graph.clearOrigin(connectionID: connection, expectedOrigin: original)+ #expect(try graph.origin(for: connection) == nil)+ _ = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Party")+ let conflicts = try graph.originOverview(for: connection)+ let clear = try #require(conflicts.conflicts.first(where: { $0.isCleared }))+ try graph.resolveOrigin(connectionID: connection, choosing: clear.id, expectedHeads: conflicts.headIDs)+ #expect(try graph.origin(for: connection) == nil)+ _ = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Late swimming account")+ #expect(try graph.originOverview(for: connection).conflicts.count == 2)+ #expect(try graph.originHistory(for: connection).count == 5)+ }+ }++ @Test func staleResolutionDoesNotConsumeANewlyArrivedAccount() throws {+ try withConnection { stack, graph, _, connection in+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Original"), expectedOrigin: nil)+ let root = try #require(try graph.originHistory(for: connection).first)+ let original = try #require(try graph.origin(for: connection))+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Birthday"), expectedOrigin: original)+ let first = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Swimming")+ let old = try graph.originOverview(for: connection)+ _ = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "School")+ #expect(throws: GraphError.self) {+ try graph.resolveOrigin(connectionID: connection, choosing: first, expectedHeads: old.headIDs)+ }+ #expect(try graph.originOverview(for: connection).conflicts.count == 3)+ #expect(try graph.originHistory(for: connection).count == 4)+ }+ }++ @Test func aBlankEditorCannotAcknowledgeAnUnseenClear() throws {+ try withConnection { _, graph, _, connection in+ let blank = try graph.originOverview(for: connection)+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Meeting"), expectedOrigin: nil)+ try graph.clearOrigin(connectionID: connection, expectedOrigin: #require(try graph.origin(for: connection)))+ #expect(throws: GraphError.self) {+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Stale draft"),+ expectedOrigin: nil, expectedHeads: blank.headIDs)+ }+ let reopened = try graph.originOverview(for: connection)+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "New account"),+ expectedOrigin: nil, expectedHeads: reopened.headIDs)+ #expect(try graph.origin(for: connection)?.narrative == "New account")+ #expect(try graph.originHistory(for: connection).count == 3)+ }+ }++ @Test func malformedImportedHistoryIsPreservedWithoutInventingValues() throws {+ try withConnection { stack, graph, _, connection in+ try graph.setCloseness(.friend, connectionID: connection, expectedID: nil)+ let id = try #require(try graph.connectionState(connection).closenessID)+ let period = try stack.container.viewContext.existingObject(with: id)+ period.setValue(Int16(0), forKey: "value")+ try stack.container.viewContext.save()+ #expect(throws: GraphError.self) { try graph.connectionState(connection) }+ #expect((period.value(forKey: "value") as? NSNumber)?.int16Value == 0)+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Meeting"), expectedOrigin: nil)+ let proposal = try #require(try graph.originHistory(for: connection).first)+ let object = try stack.container.viewContext.existingObject(with: proposal.id)+ object.setValue(Set([object]), forKey: "predecessors")+ try stack.container.viewContext.save()+ #expect(throws: GraphError.self) { try graph.originOverview(for: connection) }+ #expect(try stack.container.viewContext.count(for: NSFetchRequest<NSManagedObject>(entityName: "OriginProposal")) == 1)+ }+ }++ @Test func aCycleAlongsideAValidHeadCannotBeDisplayedAsAnUnambiguousOrigin() throws {+ try withConnection { stack, graph, _, connection in+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Root"), expectedOrigin: nil)+ let root = try #require(try graph.originHistory(for: connection).first)+ let second = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Second")+ let third = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Valid head")+ let context = stack.container.viewContext+ let firstObject = try context.existingObject(with: root.id)+ let secondObject = try context.existingObject(with: second)+ firstObject.setValue(Set([secondObject]), forKey: "predecessors")+ try context.save()+ #expect(throws: GraphError.self) { try graph.originOverview(for: connection) }+ #expect(try context.existingObject(with: third).value(forKey: "narrative") as? String == "Valid head")+ #expect(try context.count(for: NSFetchRequest<NSManagedObject>(entityName: "OriginProposal")) == 3)+ }+ }++ @Test func closenessOnlyCreatesHistoryForExplicitValueChanges() throws {+ try withConnection { stack, graph, _, connection in+ #expect(ClosenessChoice.allCases.map(\.rawValue) == [1, 3, 5, 7, 10])+ #expect(ClosenessChoice(rawValue: 0) == nil)+ #expect(try graph.connectionState(connection).closeness == nil)+ for value: Int16 in [0, 11] {+ #expect(throws: GraphError.self) { try graph.setClosenessValue(value, connectionID: connection, expectedID: nil) }+ }+ try graph.setCloseness(.friend, connectionID: connection, expectedID: nil)+ let first = try graph.connectionState(connection)+ try graph.setCloseness(.friend, connectionID: connection, expectedID: first.closenessID)+ let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionClosenessPeriod")+ #expect(try stack.container.viewContext.count(for: request) == 1)+ try graph.setCloseness(.goodFriend, connectionID: connection, expectedID: first.closenessID)+ let second = try graph.connectionState(connection)+ try graph.setCloseness(.bff, connectionID: connection, expectedID: second.closenessID)+ #expect(throws: GraphError.self) { try graph.setCloseness(.metOnce, connectionID: connection, expectedID: first.closenessID) }+ let history = try stack.container.viewContext.fetch(request)+ #expect(Set(history.compactMap { ($0.value(forKey: "value") as? NSNumber)?.int16Value }) == [5, 7, 10])+ #expect(history.filter { $0.value(forKey: "endedAt") == nil }.count == 1)+ #expect(try graph.connectionState(connection).closeness == .bff)+ #expect(history.allSatisfy { $0.objectID.persistentStore == connection.persistentStore })+ }+ }++ @Test func numericClosenessDomainPreservesValuesBetweenTheFiveUIPositions() throws {+ try withConnection { _, graph, _, connection in+ try graph.setClosenessValue(2, connectionID: connection, expectedID: nil)+ let snapshot = try graph.connectionState(connection)+ #expect(snapshot.closenessValue == 2)+ #expect(snapshot.closeness == nil)+ #expect(!snapshot.closenessNeedsReview)+ }+ }++ @Test func lostContactAndReconnectPreserveConnectionPersonAndCloseness() throws {+ try withConnection { stack, graph, _, connection in+ let person = try graph.personID(for: connection)+ try graph.setCloseness(.goodFriend, connectionID: connection, expectedID: nil)+ try graph.setConnectionState(.lostContact, note: "Moved away", connectionID: connection, expectedID: nil)+ let lost = try graph.connectionState(connection)+ #expect(lost.state == .lostContact)+ #expect(lost.note == "Moved away")+ try graph.setConnectionState(.active, note: "Reconnected", connectionID: connection, expectedID: lost.statusID)+ #expect(try graph.personID(for: connection) == person)+ #expect(try graph.connectionState(connection).closeness == .goodFriend)+ #expect(try graph.connectionState(connection).state == .active)+ let periods = try stack.container.viewContext.fetch(NSFetchRequest<NSManagedObject>(entityName: "ConnectionStatusPeriod"))+ #expect(periods.count == 2)+ #expect(periods.filter { $0.value(forKey: "endedAt") == nil }.count == 1)+ }+ }++ @Test func multipleCustomDatedRolesReusePersonAndRejectInvalidRange() throws {+ try withConnection { _, graph, family, connection in+ let source = try graph.createContext(name: "Swimming", familyID: family)+ let adult = try graph.addPerson(name: "Adult", familyID: family)+ let start = Date(timeIntervalSince1970: 10)+ let end = Date(timeIntervalSince1970: 20)+ let teacher = try graph.associatePerson(adult, contextID: source, role: "Teacher", startedAt: start, endedAt: end)+ let repeated = try graph.associatePerson(adult, contextID: source, role: "Teacher", startedAt: start, endedAt: end)+ _ = try graph.associatePerson(adult, contextID: source, role: "Coach")+ #expect(teacher == repeated)+ #expect(throws: GraphError.self) {+ try graph.associatePerson(adult, contextID: source, role: "Invalid", startedAt: end, endedAt: start)+ }+ try graph.archiveContext(source, archived: true)+ let roles = try graph.contextPeople(source)+ #expect(Set(roles.map(\.role)) == ["Teacher", "Coach"])+ #expect(roles.allSatisfy { $0.personID == adult })+ #expect(roles.first(where: { $0.role == "Teacher" })?.endedAt == end)+ #expect(try graph.personID(for: connection) != adult)+ }+ }++ @Test func editingRoleDatesKeepsIdentityAndRejectsStaleEdits() throws {+ try withConnection { _, graph, family, _ in+ let source = try graph.createContext(name: "Swimming", familyID: family)+ let adult = try graph.addPerson(name: "Adult", familyID: family)+ let roleID = try graph.associatePerson(adult, contextID: source, role: "Coach")+ let old = try #require(try graph.contextPeople(source).first)+ let end = Date()+ try graph.updateRole(roleID, role: "Former coach", startedAt: nil, endedAt: end, expected: old)+ #expect(throws: GraphError.self) {+ try graph.updateRole(roleID, role: "Stale role", startedAt: nil, endedAt: nil, expected: old)+ }+ let changed = try #require(try graph.contextPeople(source).first)+ #expect(changed.id == roleID && changed.personID == adult && changed.contextID == source)+ #expect(changed.role == "Former coach" && changed.endedAt == end)+ }+ }++ @Test func overlappingTemporalEditsRemainRetainedAndAreNotGivenAnAutomaticWinner() throws {+ try withConnection { stack, graph, familyID, connection in+ try graph.setCloseness(.friend, connectionID: connection, expectedID: nil)+ let context = stack.container.viewContext+ let root = try context.existingObject(with: connection)+ let family = try #require(root.value(forKey: "familySpace") as? NSManagedObject)+ let other = NSEntityDescription.insertNewObject(forEntityName: "ConnectionClosenessPeriod", into: context)+ context.assign(other, to: try #require(connection.persistentStore))+ other.setValue(UUID(), forKey: "id")+ other.setValue(root, forKey: "connection")+ other.setValue(family, forKey: "familySpace")+ other.setValue(Int16(10), forKey: "value")+ other.setValue(Date(), forKey: "startedAt")+ try context.save()+ let state = try graph.connectionState(connection)+ #expect(state.closenessNeedsReview)+ #expect(state.closeness == nil)+ #expect(throws: GraphError.self) { try graph.setCloseness(.goodFriend, connectionID: connection, expectedID: nil) }+ #expect(try context.count(for: NSFetchRequest<NSManagedObject>(entityName: "ConnectionClosenessPeriod")) == 2)+ #expect(try graph.reviewConnections(in: familyID).first?.relationshipNeedsReview == true)+ }+ }+}
diff --git a/Tests/HaloPersistenceTests/DefaultsMigrationHistoryTests.swift b/Tests/HaloPersistenceTests/DefaultsMigrationHistoryTests.swiftnew file mode 100644index 0000000..2b36010--- /dev/null+++ b/Tests/HaloPersistenceTests/DefaultsMigrationHistoryTests.swift@@ -0,0 +1,107 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct DefaultsMigrationHistoryTests {+ @Test func bothV3StoresMigrateAndTheFirstEditRetainsLegacyOriginIdentityAndAccount() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let old = try PersistenceStack(directory: directory, model: PersistenceStack.loadModel(version: "HaloModelV3"))+ old.container.viewContext.automaticallyMergesChangesFromParent = false+ let graph = FamilyRepository(stack: old)+ let privateFamily = try graph.createFamily(name: "Synthetic owner")+ let context = old.container.viewContext+ let shared = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+ context.assign(shared, to: old.sharedStore)+ shared.setValue(UUID(), forKey: "id")+ shared.setValue("Synthetic participant", forKey: "name")+ try context.save()+ var originIDs: Set<UUID> = []+ for familyID in [privateFamily, shared.objectID] {+ let child = try graph.addChild(name: "Child", familyID: familyID)+ let connectionID = try graph.quickCapture(name: "Friend", childID: child)+ let sourceID = try graph.createContext(name: "Playgroup", familyID: familyID)+ let family = try context.existingObject(with: familyID)+ let origin = NSEntityDescription.insertNewObject(forEntityName: "ConnectionOrigin", into: context)+ context.assign(origin, to: try #require(familyID.persistentStore))+ let id = UUID()+ originIDs.insert(id)+ origin.setValue(id, forKey: "id")+ origin.setValue(family, forKey: "familySpace")+ origin.setValue(try context.existingObject(with: connectionID), forKey: "connection")+ origin.setValue(try context.existingObject(with: sourceID), forKey: "context")+ origin.setValue("First lesson", forKey: "originDescription")+ let adultID = try graph.addPerson(name: "Teacher", familyID: familyID)+ let association = NSEntityDescription.insertNewObject(forEntityName: "ContextPerson", into: context)+ context.assign(association, to: try #require(familyID.persistentStore))+ association.setValue(UUID(), forKey: "id")+ association.setValue(family, forKey: "familySpace")+ association.setValue(try context.existingObject(with: sourceID), forKey: "context")+ association.setValue(try context.existingObject(with: adultID), forKey: "person")+ try context.save()+ }+ context.reset()+ for store in old.container.persistentStoreCoordinator.persistentStores {+ try old.container.persistentStoreCoordinator.remove(store)+ }+ let current = try PersistenceStack(directory: directory)+ current.container.viewContext.automaticallyMergesChangesFromParent = false+ let migrated = FamilyRepository(stack: current)+ let origins = try current.container.viewContext.fetch(NSFetchRequest<NSManagedObject>(entityName: "ConnectionOrigin"))+ #expect(Set(origins.compactMap { $0.value(forKey: "id") as? UUID }) == originIDs)+ for family in try migrated.families() {+ let child = try #require(try migrated.children(in: family.id).first)+ let connection = try #require(try migrated.connections(for: child.id).first)+ let legacy = try #require(try migrated.origin(for: connection.id))+ #expect(legacy.narrative == "First lesson")+ #expect(try migrated.originHistory(for: connection.id).isEmpty)+ let sourceID = try #require(legacy.contextID)+ let roles = try migrated.contextPeople(sourceID)+ #expect(roles.count == 1 && roles.first?.role == "")+ try migrated.saveOrigin(connectionID: connection.id, input: OriginInput(narrative: "Updated account"),+ expectedOrigin: legacy)+ #expect(try migrated.origin(for: connection.id)?.id == legacy.id)+ let history = try migrated.originHistory(for: connection.id)+ #expect(Set(history.map(\.narrative)) == ["First lesson", "Updated account"])+ #expect(history.allSatisfy { $0.id.persistentStore == family.id.persistentStore })+ #expect(try migrated.connectionState(connection.id).closeness == nil)+ }+ }++ @Test func secondCoordinatorProposalAndRelationshipWritesRefreshTogether() async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let host = try PersistenceStack(directory: directory)+ host.container.viewContext.automaticallyMergesChangesFromParent = false+ let graph = FamilyRepository(stack: host)+ let family = try graph.createFamily(name: "Synthetic family")+ let child = try graph.addChild(name: "Child", familyID: family)+ let connection = try graph.quickCapture(name: "Friend", childID: child)+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Playground"), expectedOrigin: nil)+ let original = try #require(try graph.origin(for: connection))+ let processor = HistoryProcessor(container: host.container,+ directory: directory.appendingPathComponent("History"), consumer: "host")+ _ = try await processor.process()+ let writer = try await PersistenceStack.open(+ configuration: StoreConfiguration(directory: directory, role: .appIntent, mirrorsCloud: false)+ )+ writer.container.viewContext.automaticallyMergesChangesFromParent = false+ let external = FamilyRepository(stack: writer)+ let writerFamily = try #require(try external.families().first)+ let writerChild = try #require(try external.children(in: writerFamily.id).first)+ let writerConnection = try #require(try external.connections(for: writerChild.id).first)+ let baseline = try #require(try external.origin(for: writerConnection.id))+ try external.saveOrigin(connectionID: writerConnection.id, input: OriginInput(narrative: "Birthday"), expectedOrigin: baseline)+ try external.setCloseness(.friend, connectionID: writerConnection.id, expectedID: nil)+ try external.setConnectionState(.lostContact, note: "Moved", connectionID: writerConnection.id, expectedID: nil)+ #expect(try await processor.process() == 3)+ #expect(try graph.origin(for: connection)?.narrative == "Birthday")+ #expect(try graph.originHistory(for: connection).count == 2)+ #expect(try graph.connectionState(connection).closeness == .friend)+ #expect(try graph.connectionState(connection).state == .lostContact)+ #expect(throws: GraphError.self) {+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Stale account"), expectedOrigin: original)+ }+ }+}
diff --git a/Tests/HaloPersistenceTests/FamilyMemoryTests.swift b/Tests/HaloPersistenceTests/FamilyMemoryTests.swiftnew file mode 100644index 0000000..8aca147--- /dev/null+++ b/Tests/HaloPersistenceTests/FamilyMemoryTests.swift@@ -0,0 +1,399 @@+import CoreData+import CoreGraphics+import ImageIO+import Testing+import UniformTypeIdentifiers+@testable import HaloPersistence++@MainActor+private struct MemoryFixture {+ let stack: PersistenceStack+ let graph: FamilyRepository+ let family: NSManagedObjectID+ let person: NSManagedObjectID+ let event: NSManagedObjectID+ init(directory: URL, shared: Bool = false) throws {+ stack = try PersistenceStack(directory: directory)+ stack.container.viewContext.automaticallyMergesChangesFromParent = false+ graph = FamilyRepository(stack: stack)+ if shared {+ 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 participant", forKey: "name")+ try context.save()+ self.family = family.objectID+ } else { family = try graph.createFamily(name: "Synthetic family") }+ person = try graph.addPerson(name: "Mia", familyID: family)+ event = try graph.createEvent(title: "Birthday", date: Date(timeIntervalSince1970: 1000), familyID: family)+ }+}++@MainActor+struct FamilyMemoryTests {+ private func withFixture(shared: Bool = false, _ body: (MemoryFixture, URL) async throws -> Void) async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ try await body(MemoryFixture(directory: directory, shared: shared), directory)+ }++ @Test func partialDatesRetainOnlyKnownPrecisionAndRejectImpossibleDates() throws {+ #expect(try PartialDate(year: 2024).label == "2024")+ #expect(try PartialDate(year: 2024, month: 2).label == "2024-02")+ #expect(try PartialDate(year: 2024, month: 2, day: 29).label == "2024-02-29")+ let invalid: [(Int?, Int?, Int?)] = [(nil, 2, nil), (2024, nil, 1), (2023, 2, 29), (2024, 13, 1), (2024, 1, 0), (0, nil, nil)]+ for input in invalid {+ #expect(throws: MemoryError.self) { try PartialDate(year: input.0, month: input.1, day: input.2) }+ }+ }++ @Test func deceasedSuppressionPreservesIdentityConnectionAndExplicitHistory() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let child = try graph.addChild(name: "Child", familyID: fixture.family)+ let connection = try graph.connect(personID: fixture.person, childID: child)+ try graph.setCloseness(.friend, connectionID: connection, expectedID: nil)+ let original = try graph.sensitiveDetails(fixture.person)+ try graph.setSensitiveDetails(fixture.person, deceased: true, date: PartialDate(year: 2024), expected: original)+ #expect(try graph.connections(for: child, includeDeceased: false).isEmpty)+ #expect(try graph.connections(for: child).map(\.id) == [connection])+ #expect(try graph.people(in: fixture.family, search: "Mia").map(\.id) == [fixture.person])+ #expect(try graph.people(in: fixture.family, needsReview: true).isEmpty)+ #expect(try graph.connectionState(connection).state == .active)+ #expect(try graph.connectionState(connection).closeness == .friend)+ #expect(throws: MemoryError.self) {+ try graph.setSensitiveDetails(fixture.person, deceased: false, date: PartialDate(), expected: original)+ }+ }+ }++ @Test func grandmotherAssertionNeedsNoMissingAncestorsAndRejectsForeignTarget() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let grandmother = try graph.addPerson(name: "Helen", familyID: fixture.family)+ try graph.addFamilyFact(sourceID: grandmother, targetID: fixture.person, kind: nil, label: "Grandmother")+ #expect(try graph.familyFacts(for: fixture.person).map(\.label) == ["Grandmother"])+ #expect(try graph.people(in: fixture.family).count == 2)+ let other = try graph.createFamily(name: "Other")+ let foreign = try graph.addPerson(name: "Foreign", familyID: other)+ #expect(throws: GraphError.self) { try graph.addFamilyFact(sourceID: grandmother, targetID: foreign, kind: .parentOf) }+ #expect(try graph.familyFacts(for: grandmother).count == 1)+ #expect(throws: MemoryError.self) { try graph.addFamilyFact(sourceID: grandmother, targetID: grandmother, kind: .partnerOf) }+ let fact = try #require(try graph.familyFacts(for: grandmother).first)+ let end = Date(timeIntervalSince1970: 1000)+ try graph.endFamilyFact(fact.id, at: end)+ #expect(throws: MemoryError.self) { try graph.endFamilyFact(fact.id, at: end.addingTimeInterval(60)) }+ #expect(try graph.familyFacts(for: grandmother).first?.endedAt == end)+ }+ }++ @Test func knownFamilyPathsAreDerivedWithoutReplacingEnteredTitles() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let parent = try graph.addPerson(name: "Parent", familyID: fixture.family)+ let grandparent = try graph.addPerson(name: "Grandparent", familyID: fixture.family)+ let relative = try graph.addPerson(name: "May", familyID: fixture.family)+ try graph.addFamilyFact(sourceID: parent, targetID: fixture.person, kind: .parentOf)+ try graph.addFamilyFact(sourceID: grandparent, targetID: parent, kind: .parentOf)+ try graph.addFamilyFact(sourceID: grandparent, targetID: relative, kind: .siblingOf)+ let derived = try graph.derivedKinship(for: fixture.person)+ #expect(derived.first(where: { $0.id == grandparent })?.label == "Grandparent through known family facts")+ #expect(derived.first(where: { $0.id == relative })?.label == "Grandparent’s sibling")+ try graph.addFamilyFact(sourceID: relative, targetID: fixture.person, kind: nil, label: "Auntie May")+ #expect(try graph.derivedKinship(for: fixture.person).contains { $0.id == relative } == false)+ #expect(try graph.familyFacts(for: fixture.person).contains { $0.label == "Auntie May" })+ }+ }++ @Test func multipleHouseholdsAndAddressLabelsRemainIndependentOfKinship() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let first = try graph.createGroup(name: "First household", familyID: fixture.family)+ let second = try graph.createGroup(name: "Second household", familyID: fixture.family)+ try graph.addGroupMember(fixture.person, groupID: first, role: "Member")+ try graph.addGroupMember(fixture.person, groupID: second)+ let relative = try graph.addPerson(name: "May", familyID: fixture.family)+ try graph.addAddressLabel(targetID: relative, label: "Auntie May", usedByPerson: fixture.person)+ try graph.addAddressLabel(targetID: relative, label: "姨姨", usedByGroup: first, language: "Chinese", script: "Traditional")+ #expect(try graph.groupMembers(first).map(\.personID) == [fixture.person])+ #expect(try graph.groupMembers(second).map(\.personID) == [fixture.person])+ let membership = try #require(try graph.groupMembers(first).first)+ try graph.endGroupMembership(membership.id, at: Date())+ #expect(try graph.groupMembers(first).first?.endedAt != nil)+ #expect(try graph.groupMembers(second).first?.endedAt == nil)+ #expect(try graph.addressLabels(for: relative).count == 2)+ #expect(try graph.familyFacts(for: relative).isEmpty)+ let original = try #require(try graph.addressLabels(for: relative).first { $0.label == "Auntie May" })+ try graph.updateAddressLabel(original.id, label: "Aunt May", language: "English", script: "Latin", expected: original)+ #expect(try graph.addressLabels(for: relative).first { $0.id == original.id }?.label == "Aunt May")+ #expect(try graph.familyFacts(for: relative).isEmpty)+ #expect(throws: MemoryError.self) {+ try graph.updateAddressLabel(original.id, label: "Stale", language: "", script: "", expected: original)+ }+ #expect(throws: MemoryError.self) {+ try graph.addAddressLabel(targetID: relative, label: "Title", usedByPerson: fixture.person, usedByGroup: first)+ }+ }+ }++ @Test func invitationAndAttendanceRoundTripIndependentlyWithoutCreatingConnections() async throws {+ try await withFixture { fixture, directory in+ let graph = fixture.graph+ try graph.saveParticipant(eventID: fixture.event, personID: fixture.person, roles: ["Host", "Guest"],+ invitation: .unknown, attendance: .attended)+ let original = try #require(try graph.participants(fixture.event).first)+ #expect(original.roles == ["Host", "Guest"])+ #expect(original.invitation == .unknown)+ #expect(original.attendance == .attended)+ #expect(try graph.connections(to: fixture.person).isEmpty)+ try graph.saveParticipant(eventID: fixture.event, personID: fixture.person, roles: original.roles,+ invitation: .invited, attendance: .attended, expected: original)+ #expect(throws: MemoryError.self) {+ try graph.saveParticipant(eventID: fixture.event, personID: fixture.person, roles: [],+ invitation: .declined, attendance: .didNotAttend, expected: original)+ }+ let reopened = FamilyRepository(stack: try PersistenceStack(directory: directory))+ let family = try #require(try reopened.families().first)+ let event = try #require(try reopened.events(in: family.id).first)+ #expect(try reopened.participants(event.id).first?.invitation == .invited)+ #expect(try graph.socialEvents(for: fixture.person).map(\.id) == [fixture.event])+ }+ }++ @Test func multiPartyGiftsRemainQueryableAndRejectAnotherEventsAttachment() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let giver = try graph.addPerson(name: "Giver", familyID: fixture.family)+ let recipient = try graph.addPerson(name: "Recipient", familyID: fixture.family)+ let group = try graph.createGroup(name: "Our family", familyID: fixture.family)+ try graph.addGift(eventID: fixture.event, input: GiftInput(description: "Craft kit", givers: [giver], groups: [group],+ recipients: [fixture.person, recipient]))+ let gift = try #require(try graph.gifts(fixture.event).first)+ #expect(Set(gift.givers) == ["Giver", "Our family"])+ #expect(Set(gift.recipients) == ["Mia", "Recipient"])+ #expect(try graph.socialEvents(for: giver).map(\.id) == [fixture.event])+ let otherEvent = try graph.createEvent(title: "Other party", date: Date(), familyID: fixture.family)+ _ = try await AssetRepository(stack: fixture.stack).importAttachment(Self.imageData(), filename: "Invitation.jpg",+ eventID: otherEvent)+ let attachment = try #require(try graph.attachments(otherEvent).first)+ #expect(throws: MemoryError.self) {+ try graph.addGift(eventID: fixture.event, input: GiftInput(description: "Invalid", attachments: [attachment.id]))+ }+ #expect(try graph.gifts(fixture.event).count == 1)+ try graph.saveGift(eventID: fixture.event, input: GiftInput(description: "Corrected craft kit", givers: [giver],+ groups: [group], recipients: [fixture.person, recipient]), expected: gift)+ #expect(try graph.gifts(fixture.event).first?.id == gift.id)+ #expect(try graph.gifts(fixture.event).first?.description == "Corrected craft kit")+ #expect(throws: MemoryError.self) {+ try graph.saveGift(eventID: fixture.event, input: GiftInput(description: "Stale edit"), expected: gift)+ }+ }+ }++ @Test func photoImportIsBoundedMetadataFreeAndUsesTheParticipantStore() async throws {+ try await withFixture(shared: true) { fixture, directory in+ let assets = AssetRepository(stack: fixture.stack)+ let photo = try await assets.importPhoto(Self.imageData(width: 3000, height: 1500), filename: "Original.jpeg",+ personID: fixture.person)+ let payload = try await assets.data(for: photo)+ let source = try #require(CGImageSourceCreateWithData(payload as CFData, nil))+ let properties = try #require(CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any])+ #expect(properties[kCGImagePropertyGPSDictionary] == nil)+ #expect((properties[kCGImagePropertyPixelWidth] as? Int) == 2048)+ #expect(payload.count <= ImageImport.photoLimit)+ #expect(photo.persistentStore == fixture.stack.sharedStore)+ #expect(try fixture.graph.primaryPhoto(fixture.person) == photo)+ let oldID = try fixture.stack.container.viewContext.existingObject(with: photo).value(forKey: "id") as? UUID+ let replacement = try await assets.importPhoto(Self.imageData(), filename: "New.png", personID: fixture.person)+ #expect(replacement != photo)+ #expect(try fixture.stack.container.viewContext.existingObject(with: photo).value(forKey: "id") as? UUID == oldID)+ try fixture.graph.removePhoto(fixture.person)+ #expect(try fixture.graph.primaryPhoto(fixture.person) == nil)+ #expect(try await assets.data(for: photo) == payload)+ let reopened = try PersistenceStack(directory: directory)+ #expect(try FamilyRepository(stack: reopened).people(in: FamilyRepository(stack: reopened).families()[0].id).count == 1)+ }+ }++ @Test func unsupportedOversizedAndInvalidImportsNeverCreateAssets() async throws {+ try await withFixture { fixture, _ in+ let assets = AssetRepository(stack: fixture.stack)+ await #expect(throws: MemoryError.self) {+ try await assets.importPhoto(Data("not an image".utf8), filename: "bad.jpg", personID: fixture.person)+ }+ await #expect(throws: MemoryError.self) {+ try await assets.importAttachment(Data(repeating: 0, count: ImageImport.attachmentLimit + 1),+ filename: "big.pdf", eventID: fixture.event)+ }+ await #expect(throws: MemoryError.self) {+ try await assets.importAttachment(Data("%PDF-invalid".utf8), filename: "bad.pdf", eventID: fixture.event)+ }+ let photo = try fixture.graph.primaryPhoto(fixture.person)+ let attachments = try fixture.graph.attachments(fixture.event)+ let assetsCount = try fixture.stack.container.viewContext.count(for: NSFetchRequest<NSManagedObject>(entityName: "Asset"))+ #expect(photo == nil)+ #expect(attachments.isEmpty)+ #expect(assetsCount == 0)+ }+ }++ @Test func widgetCannotSaveOrImportAssets() async throws {+ try await withFixture { fixture, directory in+ let widget = try PersistenceStack(directory: directory, role: .widget)+ let uri = fixture.family.uriRepresentation()+ let family = try #require(widget.container.persistentStoreCoordinator.managedObjectID(forURIRepresentation: uri))+ await #expect(throws: GraphError.self) { try await AssetRepository(stack: widget).save(data: Data([1]), familyID: family) }+ }+ }++ @Test func thumbnailRevisionChangesWhenPayloadIsReplacedWithoutChangingIdentity() async throws {+ try await withFixture { fixture, _ in+ let assets = AssetRepository(stack: fixture.stack)+ let photo = try await assets.importPhoto(Self.imageData(), filename: "First.jpg", personID: fixture.person)+ let firstRevision = try await assets.revision(for: photo)+ #expect(try await assets.save(data: Self.imageData(width: 64), familyID: fixture.family, replacing: photo) == photo)+ #expect(try await assets.revision(for: photo) != firstRevision)+ #expect(try fixture.graph.primaryPhoto(fixture.person) == photo)+ }+ }++ @Test func familyDerivationUsesKnownDateIntervals() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let parent = try graph.addPerson(name: "Parent", familyID: fixture.family)+ let grandparent = try graph.addPerson(name: "Grandparent", familyID: fixture.family)+ let start = Date(timeIntervalSince1970: 100), end = Date(timeIntervalSince1970: 200)+ try graph.addFamilyFact(sourceID: parent, targetID: fixture.person, kind: .parentOf, dates: (start, end))+ try graph.addFamilyFact(sourceID: grandparent, targetID: parent, kind: .parentOf)+ #expect(try graph.derivedKinship(for: fixture.person, asOf: Date(timeIntervalSince1970: 50)).isEmpty)+ #expect(try graph.derivedKinship(for: fixture.person, asOf: Date(timeIntervalSince1970: 150)).map(\.id) == [grandparent])+ #expect(try graph.derivedKinship(for: fixture.person, asOf: end).isEmpty)+ }+ }++ @Test func pngAndPDFImportsKeepContentTypesAndIndependentEventLinks() async throws {+ try await withFixture { fixture, _ in+ let assets = AssetRepository(stack: fixture.stack)+ let image = try await assets.importAttachment(Self.imageData(type: .png), filename: "Invitation.png", eventID: fixture.event)+ let output = NSMutableData()+ let consumer = try #require(CGDataConsumer(data: output))+ var box = CGRect(x: 0, y: 0, width: 100, height: 100)+ let pdf = try #require(CGContext(consumer: consumer, mediaBox: &box, nil))+ pdf.beginPDFPage(nil); pdf.endPDFPage(); pdf.closePDF()+ let document = try await assets.importAttachment(output as Data, filename: "Invitation.pdf", eventID: fixture.event)+ #expect(try await assets.data(for: document) == output as Data)+ let rows = try fixture.graph.attachments(fixture.event)+ #expect(Set(rows.map(\.contentType)) == [UTType.png.identifier, UTType.pdf.identifier])+ #expect(Set(rows.map(\.assetID)) == [image, document])+ #expect(try fixture.graph.socialEvents(for: fixture.person).isEmpty)+ }+ }++ @Test func statusResolutionPreservesNotesAndRejectsAStaleReviewedSet() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let child = try graph.addChild(name: "Child", familyID: fixture.family)+ let connection = try graph.connect(personID: fixture.person, childID: child)+ try graph.setConnectionState(.active, note: "Still friends", connectionID: connection, expectedID: nil)+ let first = try #require(try graph.connectionState(connection).statusID)+ let imported = try graph.write { context in+ let period = graph.insert("ConnectionStatusPeriod", in: context, store: fixture.stack.privateStore)+ period.setValue(try graph.record(fixture.family, entity: "FamilySpace", in: context), forKey: "familySpace")+ period.setValue(try graph.record(connection, entity: "Connection", in: context), forKey: "connection")+ period.setValue("lostContact", forKey: "state")+ period.setValue("Moved away", forKey: "note")+ period.setValue(Date(), forKey: "startedAt")+ return period+ }+ #expect(try graph.connectionState(connection).statusNeedsReview)+ #expect(throws: GraphError.self) {+ try graph.resolveStatus(.lostContact, note: "Moved away", connectionID: connection, reviewed: [first])+ }+ try graph.resolveStatus(.lostContact, note: "Moved away", connectionID: connection, reviewed: [first, imported])+ #expect(try graph.connectionState(connection).state == .lostContact)+ #expect(try graph.connectionState(connection).note == "Moved away")+ #expect(try fixture.stack.container.viewContext.existingObject(with: first).value(forKey: "note") as? String == "Still friends")+ #expect(throws: GraphError.self) {+ try graph.resolveStatus(.active, note: "Stale", connectionID: connection, reviewed: [first, imported])+ }+ }+ }++ @Test func eventEditsKeepOriginReferencesAndRejectStaleEdits() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let child = try graph.addChild(name: "Child", familyID: fixture.family)+ let connection = try graph.connect(personID: fixture.person, childID: child)+ try graph.saveOrigin(connectionID: connection, input: OriginInput(eventID: fixture.event, narrative: "First party"),+ expectedOrigin: nil)+ let initial = try graph.event(fixture.event)+ try graph.updateEvent(fixture.event, title: "Renamed birthday", date: initial.date!, type: "Birthday", notes: "Memory",+ links: (fixture.person, nil), expected: initial)+ #expect(try graph.origin(for: connection)?.sourceName?.contains("Renamed birthday") == true)+ #expect(try graph.origin(for: connection)?.narrative == "First party")+ try graph.archiveEvent(fixture.event, archived: true)+ #expect(try graph.events(in: fixture.family, includeArchived: false).isEmpty)+ #expect(try graph.origin(for: connection)?.eventID == fixture.event)+ #expect(throws: MemoryError.self) {+ try graph.updateEvent(fixture.event, title: "Stale", date: Date(), type: "", notes: "", links: (nil, nil),+ expected: initial)+ }+ // Legacy/imported records may have no date. Enrichment must not invent one.+ _ = try graph.write { context in+ let event = try graph.record(fixture.event, entity: "Event", in: context)+ event.setValue(nil, forKey: "date")+ return event+ }+ let undated = try graph.event(fixture.event)+ try graph.updateEvent(fixture.event, title: undated.title, date: nil, notes: "More details",+ links: (undated.subjectID, undated.contextID), expected: undated)+ #expect(try graph.event(fixture.event).date == nil)+ #expect(throws: MemoryError.self) {+ try graph.updateEvent(fixture.event, title: "Stale undated", date: nil, notes: "",+ links: (nil, nil), expected: undated)+ }+ }+ }++ @Test func temporalResolutionClosesOnlyReviewedPeriodsAndRetainsLateConflicts() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let child = try graph.addChild(name: "Child", familyID: fixture.family)+ let connection = try graph.connect(personID: fixture.person, childID: child)+ @MainActor func imported(_ value: Int16) throws -> NSManagedObjectID {+ try graph.write { context in+ let period = graph.insert("ConnectionClosenessPeriod", in: context, store: fixture.stack.privateStore)+ period.setValue(try graph.record(fixture.family, entity: "FamilySpace", in: context), forKey: "familySpace")+ period.setValue(try graph.record(connection, entity: "Connection", in: context), forKey: "connection")+ period.setValue(value, forKey: "value")+ period.setValue(Date(), forKey: "startedAt")+ return period+ }+ }+ let first = try imported(3), second = try imported(7)+ #expect(try graph.connectionState(connection).closenessNeedsReview)+ #expect(throws: GraphError.self) { try graph.resolveCloseness(7, connectionID: connection, reviewed: [first]) }+ try graph.resolveCloseness(7, connectionID: connection, reviewed: [first, second])+ #expect(try graph.connectionState(connection).closeness == .goodFriend)+ #expect(try fixture.stack.container.viewContext.existingObject(with: first).value(forKey: "endedAt") != nil)+ _ = try imported(5)+ #expect(try graph.connectionState(connection).closenessNeedsReview)+ let history = NSFetchRequest<NSManagedObject>(entityName: "ConnectionClosenessPeriod")+ #expect(try fixture.stack.container.viewContext.count(for: history) == 4)+ }+ }++ private static func imageData(width: Int = 32, height: Int = 32, type: UTType = .jpeg) throws -> Data {+ let context = try #require(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4,+ space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue))+ context.setFillColor(CGColor(red: 0.2, green: 0.4, blue: 0.8, alpha: 1))+ context.fill(CGRect(x: 0, y: 0, width: width, height: height))+ let image = try #require(context.makeImage())+ let output = NSMutableData()+ let destination = try #require(CGImageDestinationCreateWithData(output, type.identifier as CFString, 1, nil))+ CGImageDestinationAddImage(destination, image, [kCGImagePropertyGPSDictionary: [kCGImagePropertyGPSLatitude: 1.0]] as CFDictionary)+ #expect(CGImageDestinationFinalize(destination))+ return output as Data+ }+}
diff --git a/Tests/HaloPersistenceTests/GraphMigrationHistoryTests.swift b/Tests/HaloPersistenceTests/GraphMigrationHistoryTests.swiftnew file mode 100644index 0000000..24dd4a4--- /dev/null+++ b/Tests/HaloPersistenceTests/GraphMigrationHistoryTests.swift@@ -0,0 +1,94 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct GraphMigrationHistoryTests {+ @Test func bothV2StoresMigrateToCurrentModelPreservingGraphAndAssetIdentity() async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let old = try PersistenceStack(directory: directory, model: PersistenceStack.loadModel(version: "HaloModelV2"))+ let graph = FamilyRepository(stack: old)+ let privateFamily = try graph.createFamily(name: "Synthetic owner")+ let context = old.container.viewContext+ let shared = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+ context.assign(shared, to: old.sharedStore)+ shared.setValue(UUID(), forKey: "id")+ shared.setValue("Synthetic participant", forKey: "name")+ try context.save()+ let payload = Data(repeating: 42, count: 100_000)+ for familyID in [privateFamily, shared.objectID] {+ let child = try graph.addChild(name: "Child", familyID: familyID)+ _ = try graph.quickCapture(name: "Friend", childID: child)+ _ = try await AssetRepository(stack: old).save(data: payload, familyID: familyID)+ }+ let before = try identities(in: old)+ for store in old.container.persistentStoreCoordinator.persistentStores {+ try old.container.persistentStoreCoordinator.remove(store)+ }+ let current = try PersistenceStack(directory: directory)+ #expect(try identities(in: current) == before)+ let currentGraph = FamilyRepository(stack: current)+ for family in try currentGraph.families() {+ let child = try #require(try currentGraph.children(in: family.id).first)+ let connection = try #require(try currentGraph.connections(for: child.id).first)+ #expect(try currentGraph.origin(for: connection.id) == nil)+ let source = try currentGraph.createContext(name: "New context", familyID: family.id)+ #expect(source.persistentStore == family.id.persistentStore)+ }+ let assets = try current.container.viewContext.fetch(NSFetchRequest<NSManagedObject>(entityName: "Asset"))+ #expect(assets.count == 2)+ for asset in assets { #expect(try await AssetRepository(stack: current).data(for: asset.objectID) == payload) }+ }++ @Test func secondCoordinatorGraphEditsRefreshOriginMembershipAndContextQueries() async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let host = try PersistenceStack(directory: directory)+ let graph = FamilyRepository(stack: host)+ let family = try graph.createFamily(name: "Synthetic family")+ let child = try graph.addChild(name: "Child", familyID: family)+ let connection = try graph.quickCapture(name: "Friend", childID: child)+ let processor = HistoryProcessor(container: host.container,+ directory: directory.appendingPathComponent("History"), consumer: "host")+ _ = try await processor.process()+ let writer = try await PersistenceStack.open(+ configuration: StoreConfiguration(directory: directory, role: .appIntent, mirrorsCloud: false)+ )+ let external = FamilyRepository(stack: writer)+ let writerFamily = try #require(try external.families().first)+ let writerChild = try #require(try external.children(in: writerFamily.id).first)+ let writerConnection = try #require(try external.connections(for: writerChild.id).first)+ let source = try external.createContext(name: "Swimming", familyID: writerFamily.id)+ let membership = try external.addMembership(connectionID: writerConnection.id, contextID: source)+ try external.saveOrigin(connectionID: writerConnection.id, input: OriginInput(contextID: source, narrative: "First lesson"),+ expectedOrigin: nil)+ #expect(try await processor.process() == 3)+ #expect(try graph.memberships(for: connection).map(\.name) == ["Swimming"])+ let origin = try #require(try graph.origin(for: connection))+ #expect(origin.narrative == "First lesson")+ let writerOrigin = try #require(try external.origin(for: writerConnection.id))+ try external.saveOrigin(connectionID: writerConnection.id, input: OriginInput(narrative: "Actually, at a playground"),+ expectedOrigin: writerOrigin)+ try external.endMembership(membership, at: Date())+ try external.archiveContext(source, archived: true)+ #expect(try await processor.process() == 3)+ #expect(try graph.origin(for: connection)?.narrative == "Actually, at a playground")+ #expect(try graph.origin(for: connection)?.contextID == nil)+ #expect(try graph.memberships(for: connection).first?.endedAt != nil)+ #expect(try graph.contexts(in: family, includeArchived: false).isEmpty)+ try external.clearOrigin(connectionID: writerConnection.id, expectedOrigin: #require(try external.origin(for: writerConnection.id)))+ #expect(try await processor.process() == 1)+ #expect(try graph.origin(for: connection) == nil)+ #expect(try graph.connections(for: child).count == 1)+ }++ private func identities(in stack: PersistenceStack) throws -> [String: Set<UUID>] {+ var identities: [String: Set<UUID>] = [:]+ for entity in ["FamilySpace", "Person", "ChildProfile", "Connection", "Asset"] {+ let objects = try stack.container.viewContext.fetch(NSFetchRequest<NSManagedObject>(entityName: entity))+ identities[entity] = Set(objects.compactMap { $0.value(forKey: "id") as? UUID })+ }+ return identities+ }+}
diff --git a/Tests/HaloPersistenceTests/MemoryMigrationTests.swift b/Tests/HaloPersistenceTests/MemoryMigrationTests.swiftnew file mode 100644index 0000000..dfe8676--- /dev/null+++ b/Tests/HaloPersistenceTests/MemoryMigrationTests.swift@@ -0,0 +1,74 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct MemoryMigrationTests {+ @Test func bothV4StoresMigrateWithoutLosingOriginsRolesAndTemporalHistory() throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let previous = try PersistenceStack(directory: directory, model: PersistenceStack.loadModel(version: "HaloModelV4"))+ previous.container.viewContext.automaticallyMergesChangesFromParent = false+ let old = FamilyRepository(stack: previous)+ let owned = try old.createFamily(name: "Owner")+ let context = previous.container.viewContext+ let shared = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+ context.assign(shared, to: previous.sharedStore)+ shared.setValue(UUID(), forKey: "id")+ shared.setValue("Participant", forKey: "name")+ try context.save()+ var stablePeople: Set<UUID> = []+ for family in [owned, shared.objectID] {+ let child = try old.addChild(name: "Child", familyID: family)+ let connection = try old.quickCapture(name: "Friend", childID: child)+ let person = try old.personID(for: connection)+ stablePeople.insert(try #require(try context.existingObject(with: person).value(forKey: "id") as? UUID))+ let source = try old.createContext(name: "Swimming", familyID: family)+ _ = try old.associatePerson(person, contextID: source, role: "Coach")+ try old.saveOrigin(connectionID: connection, input: OriginInput(contextID: source, narrative: "First lesson"),+ expectedOrigin: nil)+ try old.setCloseness(.friend, connectionID: connection, expectedID: nil)+ try old.setConnectionState(.lostContact, note: "Moved", connectionID: connection, expectedID: nil)+ }+ for store in previous.container.persistentStoreCoordinator.persistentStores {+ try previous.container.persistentStoreCoordinator.remove(store)+ }+ let migrated = try PersistenceStack(directory: directory)+ migrated.container.viewContext.automaticallyMergesChangesFromParent = false+ let graph = FamilyRepository(stack: migrated)+ for family in try graph.families() {+ let child = try #require(try graph.children(in: family.id).first)+ let connection = try #require(try graph.connections(for: child.id).first)+ let person = try graph.personID(for: connection.id)+ let personUUID = try #require(try migrated.container.viewContext.existingObject(with: person).value(forKey: "id") as? UUID)+ #expect(stablePeople.contains(personUUID))+ #expect(try graph.sensitiveDetails(person).isDeceased == false)+ #expect(try graph.primaryPhoto(person) == nil)+ #expect(try graph.origin(for: connection.id)?.narrative == "First lesson")+ #expect(try graph.connectionState(connection.id).closeness == .friend)+ #expect(try graph.connectionState(connection.id).state == .lostContact)+ let source = try #require(try graph.contexts(in: family.id).first)+ #expect(try graph.contextPeople(source.id).first?.role == "Coach")+ let group = try graph.createGroup(name: "Household", familyID: family.id)+ try graph.addGroupMember(person, groupID: group)+ #expect(try graph.groupMembers(group).first?.id.persistentStore == family.id.persistentStore)+ }+ }++ @Test func currentModelKeepsCloudCompatibleOptionalInversesAndExternalBinaryStorage() throws {+ let model = try PersistenceStack.loadModel()+ for entity in model.entities {+ #expect(entity.uniquenessConstraints.isEmpty)+ for property in entity.properties { #expect(property.isOptional) }+ for relationship in entity.relationshipsByName.values {+ #expect(relationship.inverseRelationship != nil)+ #expect(relationship.deleteRule == .nullifyDeleteRule)+ #expect(!relationship.isOrdered)+ }+ }+ #expect(model.entitiesByName["Asset"]?.attributesByName["data"]?.allowsExternalBinaryDataStorage == true)+ #expect(model.entitiesByName["EventAttachment"]?.relationshipsByName["asset"]?.maxCount == 1)+ #expect(model.entitiesByName["Person"]?.relationshipsByName["primaryPhoto"]?.maxCount == 1)+ #expect(model.entitiesByName["GiftRecord"]?.relationshipsByName["givers"]?.isToMany == true)+ }+}
diff --git a/Tests/HaloPersistenceTests/PersonMergeTests.swift b/Tests/HaloPersistenceTests/PersonMergeTests.swiftnew file mode 100644index 0000000..369ac0d--- /dev/null+++ b/Tests/HaloPersistenceTests/PersonMergeTests.swift@@ -0,0 +1,577 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+private struct MergeFixture {+ let stack: PersistenceStack+ let graph: FamilyRepository+ let family: NSManagedObjectID+ let source: NSManagedObjectID+ let survivor: NSManagedObjectID++ init(directory: URL, shared: Bool = false, model: NSManagedObjectModel? = nil) throws {+ stack = try PersistenceStack(directory: directory, model: model)+ stack.container.viewContext.automaticallyMergesChangesFromParent = false+ graph = FamilyRepository(stack: stack)+ if shared {+ 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 family", forKey: "name")+ try context.save(); self.family = family.objectID+ } else { family = try graph.createFamily(name: "Synthetic family") }+ source = try graph.addPerson(name: "Sophie C", familyID: family)+ survivor = try graph.addPerson(name: "Sophie Chen", familyID: family)+ }+}++@MainActor+struct PersonMergeTests {+ private func withFixture(shared: Bool = false,+ _ body: @MainActor (MergeFixture, URL) async throws -> Void) async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ try await body(MergeFixture(directory: directory, shared: shared), directory)+ }++ private func choices(_ preview: PersonMergePreview) -> PersonMergeChoices {+ var choices = PersonMergeChoices()+ for overlap in preview.overlaps {+ choices.connections[overlap.id] = MergeConnectionChoices(originID: overlap.origins.first?.id,+ closenessID: overlap.closeness.first?.id, statusID: overlap.statuses.first?.id)+ }+ return choices+ }++ @Test func suggestionsNeverMergeOrSuppressValidSameNamePeople() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let sameName = try graph.addPerson(name: "Sophie Chen", familyID: fixture.family)+ let before = try graph.people(in: fixture.family)+ let pairs = try graph.likelyDuplicates(in: fixture.family)+ #expect(pairs.contains { Set([$0.source.id, $0.survivor.id]) == [fixture.source, fixture.survivor] })+ #expect(pairs.contains { Set([$0.source.id, $0.survivor.id]) == [fixture.survivor, sameName] })+ #expect(try graph.people(in: fixture.family) == before)+ #expect(try graph.mergeHistory(in: fixture.family).isEmpty)+ try graph.setSensitiveDetails(sameName, deceased: true, date: PartialDate(), expected: graph.sensitiveDetails(sameName))+ #expect(try graph.likelyDuplicates(in: fixture.family).allSatisfy { $0.source.id != sameName && $0.survivor.id != sameName })+ }+ }++ @Test func mergeRepointsAllReferenceKindsAndUndoRestoresStableRecordsInBothStores() async throws {+ for shared in [false, true] {+ try await withFixture(shared: shared) { fixture, _ in+ let graph = fixture.graph, source = fixture.source, survivor = fixture.survivor+ let firstChild = try graph.addChild(name: "Alex", familyID: fixture.family)+ let secondChild = try graph.addChild(name: "Robin", familyID: fixture.family)+ let first = try graph.connect(personID: source, childID: firstChild)+ let second = try graph.connect(personID: survivor, childID: secondChild)+ let contextID = try graph.createContext(name: "Swimming", familyID: fixture.family)+ let role = try graph.associatePerson(source, contextID: contextID, role: "Coach")+ try graph.saveOrigin(connectionID: first, input: OriginInput(contextID: contextID, narrative: "Lesson"),+ expectedOrigin: nil)+ let relative = try graph.addPerson(name: "Relative", familyID: fixture.family)+ try graph.addFamilyFact(sourceID: source, targetID: relative, kind: .parentOf)+ try graph.addFamilyFact(sourceID: relative, targetID: source, kind: nil, label: "Auntie")+ let group = try graph.createGroup(name: "Household", familyID: fixture.family)+ try graph.addGroupMember(source, groupID: group)+ try graph.addAddressLabel(targetID: source, label: "Auntie Sophie", usedByPerson: relative)+ let event = try graph.createEvent(title: "Party", date: Date(), familyID: fixture.family)+ let originalEvent = try graph.event(event)+ try graph.updateEvent(event, title: originalEvent.title, date: originalEvent.date, notes: "",+ links: (source, contextID), expected: originalEvent)+ try graph.saveParticipant(eventID: event, personID: source,+ roles: ["guest"], invitation: .accepted, attendance: .didNotAttend)+ try graph.addGift(eventID: event,+ input: GiftInput(description: "Book", givers: [source, survivor], recipients: [relative, source]))+ let assets = AssetRepository(stack: fixture.stack)+ let photo = try await assets.save(data: Data([1, 2, 3]), familyID: fixture.family)+ let otherPhoto = try await assets.save(data: Data([4, 5]), familyID: fixture.family)+ _ = try graph.write { context in+ let sourcePerson = try graph.record(source, entity: "Person", in: context)+ let survivorPerson = try graph.record(survivor, entity: "Person", in: context)+ sourcePerson.setValue(try graph.record(photo, entity: "Asset", in: context), forKey: "primaryPhoto")+ survivorPerson.setValue(try graph.record(otherPhoto, entity: "Asset", in: context), forKey: "primaryPhoto")+ sourcePerson.setValue("Source note", forKey: "notes"); survivorPerson.setValue("Kept note", forKey: "notes")+ return sourcePerson+ }+ let family = try graph.readable(fixture.family, entity: "FamilySpace")+ let before = try MergeSnapshot.records(family: family, in: fixture.stack.container.viewContext)+ let preview = try graph.mergePreview(sourceID: source, survivorID: survivor)+ #expect(preview.overlaps.isEmpty)+ var selection = choices(preview); selection.photo = .source+ let audit = try graph.mergePeople(preview, choices: selection)+ #expect(try graph.people(in: fixture.family).contains { $0.id == source } == false)+ #expect(try graph.mergedPersonTarget(source) == survivor)+ #expect(try Set(graph.connections(to: survivor).map(\.id)) == [first, second])+ #expect(try graph.origin(for: first)?.narrative == "Lesson")+ #expect(try graph.contextPeople(contextID).first?.id == role)+ #expect(try graph.contextPeople(contextID).first?.personID == survivor)+ #expect(try graph.familyFacts(for: survivor).count == 2)+ #expect(try graph.groupMembers(group).first?.personID == survivor)+ #expect(try graph.addressLabels(for: survivor).first?.label == "Auntie Sophie")+ #expect(try graph.event(event).subjectID == survivor)+ #expect(try graph.participants(event).first?.personID == survivor)+ #expect(try graph.gifts(event).first?.giverIDs == [survivor])+ #expect(try graph.primaryPhoto(survivor) == photo)+ #expect(try graph.person(survivor).notes == "Kept note\n\nSource note")+ #expect(try await assets.data(for: otherPhoto) == Data([4, 5]))+ #expect(audit.persistentStore == fixture.family.persistentStore)+ try graph.undoPersonMerge(audit)+ #expect(try MergeSnapshot.records(family: family, in: fixture.stack.container.viewContext) == before)+ #expect(try await assets.data(for: photo) == Data([1, 2, 3]))+ #expect(try graph.mergeHistory(in: fixture.family).first?.undone == true)+ #expect(throws: MergeError.self) { try graph.undoPersonMerge(audit) }+ }+ }+ }++ @Test func overlappingConnectionsRequireChoicesAndRetainAllOriginsMembershipsAndStateHistory() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let child = try graph.addChild(name: "Child", familyID: fixture.family)+ let first = try graph.connect(personID: fixture.source, childID: child)+ let second = try graph.connect(personID: fixture.survivor, childID: child)+ let source = try graph.createContext(name: "School", familyID: fixture.family)+ let other = try graph.createContext(name: "Playgroup", familyID: fixture.family)+ try graph.addMembership(connectionID: first, contextID: source)+ try graph.addMembership(connectionID: second, contextID: other)+ try graph.saveOrigin(connectionID: first, input: OriginInput(contextID: source, narrative: "First lesson"), expectedOrigin: nil)+ try graph.saveOrigin(connectionID: second, input: OriginInput(contextID: other, narrative: "First playdate"),+ expectedOrigin: nil)+ try graph.setCloseness(.knowThem, connectionID: first, expectedID: nil)+ try graph.setCloseness(.goodFriend, connectionID: second, expectedID: nil)+ try graph.setConnectionState(.lostContact, note: "Moved away", connectionID: first, expectedID: nil)+ try graph.setConnectionState(.active, note: "See at school", connectionID: second, expectedID: nil)+ let originalHead = try #require(try graph.originHistory(for: first).first)+ let family = try graph.readable(fixture.family, entity: "FamilySpace")+ let before = try MergeSnapshot.records(family: family, in: fixture.stack.container.viewContext)+ let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ let overlap = try #require(preview.overlaps.first)+ #expect(throws: MergeError.self) { try graph.mergePeople(preview, choices: PersonMergeChoices()) }+ #expect(try MergeSnapshot.records(family: family, in: fixture.stack.container.viewContext) == before)+ var selected = choices(preview)+ selected.connections[overlap.id] = MergeConnectionChoices(+ originID: overlap.origins.first { $0.contextID == source }?.id,+ closenessID: overlap.closeness.first { $0.value == 7 }?.id,+ statusID: overlap.statuses.first { $0.state == .lostContact }?.id)+ let audit = try graph.mergePeople(preview, choices: selected)+ #expect(try graph.connections(for: child).map(\.id) == [second])+ #expect(try graph.memberships(for: second).count == 2)+ #expect(try graph.origin(for: second)?.contextID == source)+ #expect(try graph.originHistory(for: first).first?.stableID == originalHead.stableID)+ #expect(try graph.originHistory(for: second).count == 3)+ #expect(try graph.connectionState(second).closeness == .goodFriend)+ #expect(try graph.connectionState(second).note == "Moved away")+ #expect(try graph.archivedMergeConnections(audit).map(\.id) == [first])+ try graph.undoPersonMerge(audit)+ #expect(try MergeSnapshot.records(family: family, in: fixture.stack.container.viewContext) == before)+ #expect(try graph.origin(for: second)?.contextID == other)+ }+ }++ @Test func childProfileMergeConsolidatesPeerConnectionsAndUndoRestoresBothProfiles() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let firstChild = try graph.addChild(name: "Alex old capture", familyID: fixture.family)+ let keptChild = try graph.addChild(name: "Alex", familyID: fixture.family)+ let firstProfile = try graph.readable(firstChild, entity: "ChildProfile")+ let keptProfile = try graph.readable(keptChild, entity: "ChildProfile")+ let firstPerson = try #require(firstProfile.value(forKey: "person") as? NSManagedObject)+ let keptPerson = try #require(keptProfile.value(forKey: "person") as? NSManagedObject)+ let peer = try graph.addPerson(name: "Peer", familyID: fixture.family)+ let first = try graph.connect(personID: peer, childID: firstChild)+ let kept = try graph.connect(personID: peer, childID: keptChild)+ try graph.saveOrigin(connectionID: first, input: OriginInput(narrative: "Playgroup"), expectedOrigin: nil)+ try graph.saveOrigin(connectionID: kept, input: OriginInput(narrative: "School"), expectedOrigin: nil)+ let preview = try graph.mergePreview(sourceID: firstPerson.objectID, survivorID: keptPerson.objectID)+ #expect(preview.combinesChildProfiles)+ #expect(preview.overlaps.count == 1)+ let audit = try graph.mergePeople(preview, choices: choices(preview))+ #expect(try graph.children(in: fixture.family).map(\.id) == [keptChild])+ #expect(try graph.connections(for: keptChild).map(\.id) == [kept])+ #expect(try graph.readable(firstChild, entity: "ChildProfile").value(forKey: "archivedAt") != nil)+ try graph.undoPersonMerge(audit)+ #expect(Set(try graph.children(in: fixture.family).map(\.id)) == [firstChild, keptChild])+ #expect(try graph.connections(for: firstChild).map(\.id) == [first])+ }+ }++ @Test func stalePreviewRejectsChangesButUnrelatedEditsAfterMergeSurviveUndo() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let other = try graph.addPerson(name: "Other", familyID: fixture.family)+ let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ try graph.updatePerson(other, name: "Other", notes: "Independent before merge", needsReview: false,+ expected: graph.person(other))+ #expect(throws: MergeError.self) { try graph.mergePeople(preview, choices: choices(preview)) }+ let fresh = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ let audit = try graph.mergePeople(fresh, choices: choices(fresh))+ try graph.updatePerson(other, name: "Other", notes: "Independent after merge", needsReview: false,+ expected: graph.person(other))+ #expect(try graph.mergeHistory(in: fixture.family).first?.undoAvailable == true)+ try graph.undoPersonMerge(audit)+ #expect(try graph.person(other).notes == "Independent after merge")+ }+ }++ @Test func affectedEditsAndNewReferencesMakeUndoUnavailable() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ let audit = try graph.mergePeople(preview, choices: choices(preview))+ let child = try graph.addChild(name: "Child", familyID: fixture.family)+ let connection = try graph.connect(personID: fixture.survivor, childID: child)+ #expect(try graph.mergeHistory(in: fixture.family).first?.undoAvailable == false)+ #expect(throws: MergeError.self) { try graph.undoPersonMerge(audit) }+ #expect(try graph.connections(for: child).map(\.id) == [connection])+ #expect(try graph.mergedPersonTarget(fixture.source) == fixture.survivor)+ #expect(throws: MergeError.self) {+ try graph.updatePerson(fixture.source, name: "Stale hidden person", notes: "", needsReview: false,+ expected: graph.person(fixture.source))+ }+ }+ }++ @Test func selfFactsAreArchivedAndCompetingEventAccountsRemainSeparate() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ try graph.addFamilyFact(sourceID: fixture.source, targetID: fixture.survivor, kind: .parentOf)+ let event = try graph.createEvent(title: "Party", date: Date(), familyID: fixture.family)+ try graph.saveParticipant(eventID: event, personID: fixture.source,+ roles: ["host"], invitation: .accepted, attendance: .attended, note: "First account")+ try graph.saveParticipant(eventID: event, personID: fixture.survivor,+ roles: ["guest"], invitation: .declined, attendance: .didNotAttend, note: "Second account")+ let before = try graph.participants(event)+ let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ #expect(preview.selfRelationships == 1)+ #expect(preview.duplicateEventAccounts == 1)+ let audit = try graph.mergePeople(preview, choices: choices(preview))+ #expect(try graph.familyFacts(for: fixture.survivor).isEmpty)+ #expect(try graph.familyFacts(for: fixture.survivor, includeArchived: true).first?.isArchived == true)+ #expect(try graph.derivedKinship(for: fixture.survivor).isEmpty)+ let after = try graph.participants(event)+ #expect(Set(after.map(\.id)) == Set(before.map(\.id)))+ #expect(Set(after.map(\.note)) == ["First account", "Second account"])+ #expect(after.allSatisfy { $0.personID == fixture.survivor })+ try graph.undoPersonMerge(audit)+ #expect(try graph.familyFacts(for: fixture.source).first?.targetID == fixture.survivor)+ #expect(Set(try graph.participants(event).map(\.personID)) == [fixture.source, fixture.survivor])+ }+ }++ @Test func invalidFamilyAndReadOnlyMergeNeverWrite() async throws {+ try await withFixture { fixture, directory in+ let graph = fixture.graph+ let foreignFamily = try graph.createFamily(name: "Other family")+ let foreign = try graph.addPerson(name: "Other Sophie", familyID: foreignFamily)+ #expect(throws: GraphError.self) { try graph.mergePreview(sourceID: fixture.source, survivorID: foreign) }+ #expect(throws: MergeError.self) { try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.source) }+ let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ let widget = try PersistenceStack(directory: directory, role: .widget)+ #expect(throws: GraphError.self) { try FamilyRepository(stack: widget).mergePeople(preview, choices: choices(preview)) }+ #expect(try graph.mergeHistory(in: fixture.family).isEmpty)+ }+ }++ @Test func corruptedUndoHistoryCannotDeleteOrChangePeople() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ let audit = try graph.mergePeople(preview, choices: choices(preview))+ _ = try graph.write { context in+ let row = try graph.record(audit, entity: "PersonMerge", in: context)+ row.setValue(Data("corrupted history".utf8), forKey: "beforeData")+ return row+ }+ #expect(throws: MergeError.self) { try graph.undoPersonMerge(audit) }+ #expect(try graph.mergedPersonTarget(fixture.source) == fixture.survivor)+ #expect(try graph.people(in: fixture.family).map(\.id) == [fixture.survivor])+ }+ }++ @Test func staleConnectionEditorsAndMergedChildCaptureCannotWriteHiddenRecords() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let firstChild = try graph.addChild(name: "Child", familyID: fixture.family)+ let secondChild = try graph.addChild(name: "Child duplicate", familyID: fixture.family)+ let source = try #require(try graph.readable(firstChild, entity: "ChildProfile").value(forKey: "person") as? NSManagedObject)+ let survivor = try #require(try graph.readable(secondChild, entity: "ChildProfile").value(forKey: "person") as? NSManagedObject)+ let first = try graph.connect(personID: fixture.source, childID: firstChild)+ let second = try graph.connect(personID: fixture.source, childID: secondChild)+ let context = try graph.createContext(name: "Class", familyID: fixture.family)+ let membership = try graph.addMembership(connectionID: first, contextID: context)+ let preview = try graph.mergePreview(sourceID: source.objectID, survivorID: survivor.objectID)+ _ = try graph.mergePeople(preview, choices: choices(preview))+ #expect(throws: MergeError.self) { try graph.quickCapture(name: "Stale capture", childID: firstChild) }+ #expect(throws: MergeError.self) {+ try graph.saveOrigin(connectionID: first, input: OriginInput(narrative: "Stale draft"), expectedOrigin: nil)+ }+ #expect(throws: MergeError.self) { try graph.setCloseness(.bff, connectionID: first, expectedID: nil) }+ #expect(try graph.connections(for: secondChild).map(\.id) == [second])+ // Memberships move to the kept connection, so their own retained ID remains useful.+ try graph.endMembership(membership, at: Date())+ #expect(try graph.memberships(for: second).first?.endedAt != nil)+ }+ }++ @Test func childPeerDuplicateBecomesArchivedSelfConnectionAndUndoRestoresIt() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let child = try graph.addChild(name: "Child", familyID: fixture.family)+ let childPerson = try #require(try graph.readable(child, entity: "ChildProfile").value(forKey: "person") as? NSManagedObject)+ let connection = try graph.connect(personID: fixture.source, childID: child)+ try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Earlier account"), expectedOrigin: nil)+ let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: childPerson.objectID)+ #expect(preview.selfConnections == [connection])+ let audit = try graph.mergePeople(preview, choices: choices(preview))+ #expect(try graph.connections(for: child).isEmpty)+ #expect(try graph.origin(for: connection)?.narrative == "Earlier account")+ #expect(throws: MergeError.self) { try graph.setConnectionState(.active, note: "", connectionID: connection, expectedID: nil) }+ #expect(try graph.archivedMergeConnections(audit).map(\.id) == [connection])+ try graph.undoPersonMerge(audit)+ #expect(try graph.connections(for: child).map(\.id) == [connection])+ #expect(try graph.personID(for: connection) == fixture.source)+ }+ }++ @Test func lateImportedAccountsStayVisibleAndBecomeReviewableAlternatives() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let child = try graph.addChild(name: "Child", familyID: fixture.family)+ let first = try graph.connect(personID: fixture.source, childID: child)+ let kept = try graph.connect(personID: fixture.survivor, childID: child)+ try graph.saveOrigin(connectionID: first, input: OriginInput(narrative: "First account"), expectedOrigin: nil)+ try graph.saveOrigin(connectionID: kept, input: OriginInput(narrative: "Kept account"), expectedOrigin: nil)+ try graph.setConnectionState(.active, note: "", connectionID: first, expectedID: nil)+ try graph.setConnectionState(.active, note: "", connectionID: kept, expectedID: nil)+ let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ _ = try graph.mergePeople(preview, choices: choices(preview))+ #expect(try graph.lateMergeAccounts(in: fixture.family).isEmpty)+ // Simulate imported rows; local editors are intentionally unable to write this archived connection.+ let late = try graph.write { context in+ let connection = try context.existingObject(with: first)+ let proposal = try graph.makeProposal(input: OriginInput(narrative: "Offline account"), cleared: false,+ connection: connection, predecessors: [], in: context)+ let family = try graph.family(of: connection)+ let period = graph.insert("ConnectionStatusPeriod", in: context, store: try graph.owningStore(of: family))+ period.setValue(family, forKey: "familySpace"); period.setValue(connection, forKey: "connection")+ period.setValue(Date(), forKey: "startedAt"); period.setValue(ConnectionState.lostContact.rawValue, forKey: "state")+ period.setValue("Offline status", forKey: "note")+ return proposal+ }+ let review = try #require(try graph.lateMergeAccounts(in: fixture.family).first)+ #expect(review.id == first && review.targetID == kept)+ _ = try graph.write { context in+ try graph.makeProposal(input: OriginInput(narrative: "Another unseen account"), cleared: false,+ connection: context.existingObject(with: first), predecessors: [], in: context)+ }+ #expect(throws: MergeError.self) { try graph.reviewLateMergeAccounts(review) }+ let freshReview = try #require(try graph.lateMergeAccounts(in: fixture.family).first)+ try graph.reviewLateMergeAccounts(freshReview)+ #expect(try graph.lateMergeAccounts(in: fixture.family).isEmpty)+ let copied = try graph.originHistory(for: kept).map(\.id)+ #expect(throws: MergeError.self) { try graph.reviewLateMergeAccounts(freshReview) }+ #expect(try graph.originHistory(for: kept).map(\.id) == copied)+ #expect(try graph.originHistory(for: first).contains { $0.id == late })+ #expect(try graph.originOverview(for: kept).conflicts.contains { $0.narrative == "Offline account" })+ #expect(try graph.connectionState(kept).statusNeedsReview)+ #expect(try graph.reviewConnections(in: fixture.family).contains { $0.id == kept })+ #expect(throws: MergeError.self) { try graph.undoPersonMerge(try #require(graph.mergeHistory(in: fixture.family).first?.id)) }+ }+ }++ @Test func opposingOfflineMergesExposePeopleAndRecoverWithoutOverwritingReferences() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let peer = try MergeFixture(directory: directory)+ let originalFamily = try graph.readable(fixture.family, entity: "FamilySpace")+ let sourceUUID = try graph.stable(graph.readable(fixture.source, entity: "Person"))+ let survivorUUID = try graph.stable(graph.readable(fixture.survivor, entity: "Person"))+ _ = try peer.graph.write { context in+ let family = try context.existingObject(with: peer.family)+ family.setValue(try graph.stable(originalFamily), forKey: "id")+ try context.existingObject(with: peer.source).setValue(sourceUUID, forKey: "id")+ try context.existingObject(with: peer.survivor).setValue(survivorUUID, forKey: "id")+ return family+ }+ let first = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ let opposite = try peer.graph.mergePreview(sourceID: peer.survivor, survivorID: peer.source)+ let firstAudit = try graph.mergePeople(first, choices: choices(first))+ let peerAuditID = try peer.graph.mergePeople(opposite, choices: choices(opposite))+ let peerAudit = try peer.graph.readable(peerAuditID, entity: "PersonMerge")+ let child = try graph.addChild(name: "Unrelated child", familyID: fixture.family)+ let connection = try graph.connect(personID: fixture.survivor, childID: child)+ _ = try graph.write { context in+ let family = try context.existingObject(with: fixture.family)+ let audit = graph.insert("PersonMerge", in: context, store: try graph.owningStore(of: family))+ for key in peerAudit.entity.attributesByName.keys { audit.setValue(peerAudit.value(forKey: key), forKey: key) }+ audit.setValue(family, forKey: "familySpace")+ let survivor = try context.existingObject(with: fixture.survivor)+ survivor.setValue(try context.existingObject(with: fixture.source), forKey: "mergedInto")+ survivor.setValue(Date(), forKey: "archivedAt")+ return audit+ }+ let conflict = try #require(try graph.mergeConflicts(in: fixture.family).first)+ #expect(Set(conflict.people.map(\.id)) == [fixture.source, fixture.survivor])+ #expect(try graph.people(in: fixture.family).contains { $0.id == fixture.source })+ #expect(try graph.people(in: fixture.family).contains { $0.id == fixture.survivor })+ #expect(throws: MergeError.self) { try graph.undoPersonMerge(firstAudit) }+ _ = try graph.addPerson(name: "Intervening independent capture", familyID: fixture.family)+ #expect(throws: MergeError.self) { try graph.recoverCompetingMerges(conflict) }+ let refreshed = try #require(try graph.mergeConflicts(in: fixture.family).first)+ try graph.recoverCompetingMerges(refreshed)+ #expect(try graph.mergeConflicts(in: fixture.family).isEmpty)+ #expect(try graph.mergedPersonTarget(fixture.source) == nil)+ #expect(try graph.mergedPersonTarget(fixture.survivor) == nil)+ #expect(try graph.personID(for: connection) == fixture.survivor)+ #expect(try graph.mergeHistory(in: fixture.family).count == 2)+ #expect(try graph.mergeHistory(in: fixture.family).allSatisfy { !$0.undone })+ }+ }++ @Test func sequentialMergesRemainValidWithoutInventingAConflict() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let third = try graph.addPerson(name: "Third identity", familyID: fixture.family)+ let first = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ _ = try graph.mergePeople(first, choices: choices(first))+ let next = try graph.mergePreview(sourceID: fixture.survivor, survivorID: third)+ _ = try graph.mergePeople(next, choices: choices(next))+ #expect(try graph.mergeConflicts(in: fixture.family).isEmpty)+ #expect(try graph.mergedPersonTarget(fixture.source) == third)+ }+ }++ @Test func aliasesBeforeAuditsAndDelayedRecoveryAliasesCannotHidePeople() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ _ = try graph.write { context in+ let source = try context.existingObject(with: fixture.source)+ let survivor = try context.existingObject(with: fixture.survivor)+ source.setValue(survivor, forKey: "mergedInto"); survivor.setValue(source, forKey: "mergedInto")+ source.setValue(Date(), forKey: "archivedAt"); survivor.setValue(Date(), forKey: "archivedAt")+ return source+ }+ let conflict = try #require(try graph.mergeConflicts(in: fixture.family).first)+ #expect(conflict.mergeIDs.isEmpty)+ #expect(try graph.people(in: fixture.family).count == 2)+ try graph.recoverCompetingMerges(conflict)+ #expect(try graph.mergeConflicts(in: fixture.family).isEmpty)+ _ = try graph.write { context in+ let source = try context.existingObject(with: fixture.source)+ source.setValue(try context.existingObject(with: fixture.survivor), forKey: "mergedInto")+ source.setValue(Date(), forKey: "archivedAt")+ return source+ }+ let delayed = try #require(try graph.mergeConflicts(in: fixture.family).first)+ #expect(try graph.people(in: fixture.family).count == 2)+ try graph.recoverCompetingMerges(delayed)+ // A new explicit merge acknowledges both recoveries and is allowed; old aliases cannot do so.+ let fresh = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ _ = try graph.mergePeople(fresh, choices: choices(fresh))+ #expect(try graph.mergeConflicts(in: fixture.family).isEmpty)+ #expect(try graph.people(in: fixture.family).map(\.id) == [fixture.survivor])+ }+ }++ @Test func repeatedOriginOnlyReviewsPreserveUnchangedPeriodsAndMemberships() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let child = try graph.addChild(name: "Child", familyID: fixture.family)+ let first = try graph.connect(personID: fixture.source, childID: child)+ let kept = try graph.connect(personID: fixture.survivor, childID: child)+ try graph.saveOrigin(connectionID: first, input: OriginInput(narrative: "Earlier"), expectedOrigin: nil)+ try graph.saveOrigin(connectionID: kept, input: OriginInput(narrative: "Kept"), expectedOrigin: nil)+ try graph.setCloseness(.knowThem, connectionID: first, expectedID: nil)+ try graph.setCloseness(.goodFriend, connectionID: kept, expectedID: nil)+ try graph.setConnectionState(.lostContact, note: "", connectionID: first, expectedID: nil)+ try graph.setConnectionState(.active, note: "", connectionID: kept, expectedID: nil)+ let group = try graph.createContext(name: "Class", familyID: fixture.family)+ _ = try graph.addMembership(connectionID: first, contextID: group)+ let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ _ = try graph.mergePeople(preview, choices: choices(preview))+ let statuses = try graph.currentStatePeriods(kept, closeness: false).map(\.id)+ let closeness = try graph.currentStatePeriods(kept, closeness: true).map(\.id)+ let memberships = try graph.memberships(for: kept).map(\.id)+ for narrative in ["Late one", "Late two"] {+ _ = try graph.write { context in+ try graph.makeProposal(input: OriginInput(narrative: narrative), cleared: false,+ connection: context.existingObject(with: first), predecessors: [], in: context)+ }+ let review = try #require(try graph.lateMergeAccounts(in: fixture.family).first)+ try graph.reviewLateMergeAccounts(review)+ #expect(try graph.currentStatePeriods(kept, closeness: false).map(\.id) == statuses)+ #expect(try graph.currentStatePeriods(kept, closeness: true).map(\.id) == closeness)+ #expect(try graph.memberships(for: kept).map(\.id) == memberships)+ }+ }+ }++ @Test func lateStatusWithoutOriginDoesNotInventAFirstMeetingClear() async throws {+ try await withFixture { fixture, _ in+ let graph = fixture.graph+ let child = try graph.addChild(name: "Child", familyID: fixture.family)+ let first = try graph.connect(personID: fixture.source, childID: child)+ let kept = try graph.connect(personID: fixture.survivor, childID: child)+ try graph.saveOrigin(connectionID: kept, input: OriginInput(narrative: "Known first meeting"), expectedOrigin: nil)+ try graph.setConnectionState(.active, note: "", connectionID: first, expectedID: nil)+ try graph.setConnectionState(.active, note: "", connectionID: kept, expectedID: nil)+ let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+ let overlap = try #require(preview.overlaps.first)+ var selected = choices(preview)+ selected.connections[overlap.id]?.originID = overlap.origins.first { $0.narrative == "Known first meeting" }?.id+ _ = try graph.mergePeople(preview, choices: selected)+ let originalHeads = try graph.originOverview(for: kept).headIDs+ _ = try graph.write { context in+ let connection = try context.existingObject(with: first)+ let family = try graph.family(of: connection)+ let period = graph.insert("ConnectionStatusPeriod", in: context, store: try graph.owningStore(of: family))+ period.setValue(family, forKey: "familySpace"); period.setValue(connection, forKey: "connection")+ period.setValue(Date(), forKey: "startedAt"); period.setValue(ConnectionState.lostContact.rawValue, forKey: "state")+ return period+ }+ let late = try #require(try graph.lateMergeAccounts(in: fixture.family).first)+ try graph.reviewLateMergeAccounts(late)+ #expect(try graph.originOverview(for: kept).headIDs == originalHeads)+ #expect(try graph.origin(for: kept)?.narrative == "Known first meeting")+ #expect(try graph.connectionState(kept).statusNeedsReview)+ }+ }++ @Test func bothV5StoresMigrateWithStableRecordsAndMergeSurvivesRelaunch() async throws {+ for shared in [false, true] {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let old = try MergeFixture(directory: directory, shared: shared, model: PersistenceStack.loadModel(version: "HaloModelV5"))+ let uuids = try [old.source, old.survivor].map { try old.graph.stable(old.graph.readable($0, entity: "Person")) }+ for store in old.stack.container.persistentStoreCoordinator.persistentStores {+ try old.stack.container.persistentStoreCoordinator.remove(store)+ }+ let migrated = try PersistenceStack(directory: directory)+ migrated.container.viewContext.automaticallyMergesChangesFromParent = false+ let graph = FamilyRepository(stack: migrated)+ let family = try #require(try graph.families().first)+ let people = try graph.people(in: family.id)+ let ids = try people.map { try graph.stable(graph.readable($0.id, entity: "Person")) }+ #expect(Set(ids) == Set(uuids))+ let source = try #require(people.first { $0.name == "Sophie C" })+ let survivor = try #require(people.first { $0.name == "Sophie Chen" })+ let preview = try graph.mergePreview(sourceID: source.id, survivorID: survivor.id)+ _ = try graph.mergePeople(preview, choices: choices(preview))+ let reopened = try PersistenceStack(directory: directory)+ reopened.container.viewContext.automaticallyMergesChangesFromParent = false+ let reloaded = FamilyRepository(stack: reopened)+ let familyAgain = try #require(try reloaded.families().first)+ #expect(try reloaded.people(in: familyAgain.id).count == 1)+ let audit = try #require(try reloaded.mergeHistory(in: familyAgain.id).first)+ #expect(audit.undoAvailable)+ try reloaded.undoPersonMerge(audit.id)+ #expect(try reloaded.people(in: familyAgain.id).count == 2)+ }+ }++}
diff --git a/Tests/HaloPersistenceTests/RelationshipGraphTests.swift b/Tests/HaloPersistenceTests/RelationshipGraphTests.swiftnew file mode 100644index 0000000..dd328a0--- /dev/null+++ b/Tests/HaloPersistenceTests/RelationshipGraphTests.swift@@ -0,0 +1,239 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+private struct GraphFixture {+ let stack: PersistenceStack+ let graph: FamilyRepository+ let family: NSManagedObjectID+ let child: NSManagedObjectID+ let connection: NSManagedObjectID++ init(directory: URL, shared: Bool = false) throws {+ stack = try PersistenceStack(directory: directory)+ // The repository explicitly merges local writes before returning. Avoid queued automatic+ // merges retaining a context after this synchronous fixture removes its temporary files.+ stack.container.viewContext.automaticallyMergesChangesFromParent = false+ graph = FamilyRepository(stack: stack)+ if shared {+ let context = stack.container.viewContext+ let object = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+ context.assign(object, to: stack.sharedStore)+ object.setValue(UUID(), forKey: "id")+ object.setValue("Synthetic participant family", forKey: "name")+ try context.save()+ family = object.objectID+ } else { family = try graph.createFamily(name: "Synthetic family") }+ child = try graph.addChild(name: "Child", familyID: family)+ connection = try graph.quickCapture(name: "Friend", childID: child)+ }+}++@MainActor+struct RelationshipGraphTests {+ private func withGraph(shared: Bool = false, _ test: (GraphFixture, URL) throws -> Void) throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ try test(GraphFixture(directory: directory, shared: shared), directory)+ }++ @Test func originsRoundTripEditAndClearWithoutChangingGraphIdentity() throws {+ try withGraph { fixture, directory in+ let graph = fixture.graph+ let source = try graph.createContext(name: "Swimming", familyID: fixture.family)+ let event = try graph.createEvent(title: "Birthday", date: Date(timeIntervalSince1970: 1000), familyID: fixture.family)+ let inputs = [OriginInput(narrative: "Met at a playground"),+ OriginInput(contextID: source, narrative: "First lesson"),+ OriginInput(eventID: event, narrative: "Played together")]+ for input in inputs {+ try graph.saveOrigin(connectionID: fixture.connection, input: input, expectedOrigin: nil,+ expectedHeads: graph.originOverview(for: fixture.connection).headIDs)+ let original = try #require(try graph.origin(for: fixture.connection))+ let reopened = FamilyRepository(stack: try PersistenceStack(directory: directory))+ let reopenedChild = try #require(try reopened.children(in: reopened.families()[0].id).first)+ let reopenedConnection = try #require(try reopened.connections(for: reopenedChild.id).first)+ let persisted = try #require(try reopened.origin(for: reopenedConnection.id))+ #expect(persisted.narrative == input.narrative)+ #expect((persisted.contextID != nil) == (input.contextID != nil))+ #expect((persisted.eventID != nil) == (input.eventID != nil))+ try graph.saveOrigin(connectionID: fixture.connection, input: OriginInput(narrative: "More detail"),+ expectedOrigin: original)+ #expect(try graph.origin(for: fixture.connection)?.id == original.id)+ try graph.clearOrigin(connectionID: fixture.connection, expectedOrigin: #require(try graph.origin(for: fixture.connection)))+ #expect(try graph.origin(for: fixture.connection) == nil)+ #expect(try graph.connections(for: fixture.child).count == 1)+ #expect(try graph.contexts(in: fixture.family).count == 1)+ #expect(try graph.events(in: fixture.family).count == 1)+ }+ }+ }++ @Test func originValidationRejectsInvalidSourcesAndStaleCreationWithoutPartialWrites() throws {+ try withGraph { fixture, _ in+ let graph = fixture.graph+ let source = try graph.createContext(name: "School", familyID: fixture.family)+ let event = try graph.createEvent(title: "Party", date: Date(), familyID: fixture.family)+ let other = try graph.createFamily(name: "Other")+ let foreign = try graph.createContext(name: "Foreign", familyID: other)+ let foreignEvent = try graph.createEvent(title: "Foreign event", date: Date(), familyID: other)+ let inputs = [OriginInput(), OriginInput(narrative: " \n "), OriginInput(contextID: source, eventID: event),+ OriginInput(contextID: foreign), OriginInput(eventID: foreignEvent)]+ for input in inputs {+ #expect(throws: GraphError.self) {+ try graph.saveOrigin(connectionID: fixture.connection, input: input, expectedOrigin: nil)+ }+ #expect(try graph.origin(for: fixture.connection) == nil)+ }+ try graph.saveOrigin(connectionID: fixture.connection, input: OriginInput(eventID: event), expectedOrigin: nil)+ #expect(throws: GraphError.self) {+ try graph.saveOrigin(connectionID: fixture.connection, input: OriginInput(contextID: source), expectedOrigin: nil)+ }+ #expect(try graph.origin(for: fixture.connection)?.eventID == event)+ let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionOrigin")+ #expect(try fixture.stack.container.viewContext.count(for: request) == 1)+ }+ }++ @Test func laterMembershipsAndArchivalPreserveFirstMeetingAndConnection() throws {+ try withGraph { fixture, _ in+ let graph = fixture.graph+ let source = try graph.createContext(name: "Playgroup", familyID: fixture.family)+ let later = try graph.createContext(name: "School", familyID: fixture.family)+ try graph.saveOrigin(connectionID: fixture.connection, input: OriginInput(contextID: source), expectedOrigin: nil)+ let first = try graph.addMembership(connectionID: fixture.connection, contextID: source)+ let second = try graph.addMembership(connectionID: fixture.connection, contextID: later)+ try graph.endMembership(first, at: Date())+ try graph.endMembership(second, at: Date())+ try graph.archiveContext(source, archived: true)+ #expect(try graph.memberships(for: fixture.connection).allSatisfy { $0.endedAt != nil })+ #expect(try graph.origin(for: fixture.connection)?.contextID == source)+ #expect(try graph.contexts(in: fixture.family, includeArchived: false).map(\.id) == [later])+ #expect(try graph.connections(for: fixture.child).count == 1)+ }+ }++ @Test func staleOriginEditOrClearCannotOverwriteANewerValueWithTheSameIdentity() throws {+ try withGraph { fixture, _ in+ let graph = fixture.graph+ try graph.saveOrigin(connectionID: fixture.connection, input: OriginInput(narrative: "Playground"), expectedOrigin: nil)+ let old = try #require(try graph.origin(for: fixture.connection))+ try graph.saveOrigin(connectionID: fixture.connection, input: OriginInput(narrative: "Birthday"), expectedOrigin: old)+ #expect(throws: GraphError.self) {+ try graph.saveOrigin(connectionID: fixture.connection, input: OriginInput(narrative: "Swimming"), expectedOrigin: old)+ }+ #expect(throws: GraphError.self) { try graph.clearOrigin(connectionID: fixture.connection, expectedOrigin: old) }+ #expect(try graph.origin(for: fixture.connection)?.narrative == "Birthday")+ #expect(try graph.origin(for: fixture.connection)?.id == old.id)+ }+ }++ @Test func twoChildrenRetainIndependentOriginsForOnePerson() throws {+ try withGraph { fixture, _ in+ let graph = fixture.graph+ let sibling = try graph.addChild(name: "Sibling", familyID: fixture.family)+ let person = try graph.personID(for: fixture.connection)+ let second = try graph.connect(personID: person, childID: sibling)+ let event = try graph.createEvent(title: "Party", date: Date(), familyID: fixture.family)+ let source = try graph.createContext(name: "Swimming", familyID: fixture.family)+ try graph.saveOrigin(connectionID: fixture.connection, input: OriginInput(eventID: event), expectedOrigin: nil)+ try graph.saveOrigin(connectionID: second, input: OriginInput(contextID: source), expectedOrigin: nil)+ #expect(try graph.origin(for: fixture.connection)?.eventID == event)+ #expect(try graph.origin(for: second)?.contextID == source)+ #expect(try graph.people(in: fixture.family, search: "Friend").count == 1)+ }+ }++ @Test func hierarchyMembershipAndFamilyValidationPreserveExistingData() throws {+ try withGraph { fixture, _ in+ let graph = fixture.graph+ let school = try graph.createContext(name: "School", familyID: fixture.family)+ let grade = try graph.createContext(name: "2026", familyID: fixture.family, parentID: school)+ let classroom = try graph.createContext(name: "Prep A", familyID: fixture.family, parentID: grade)+ #expect(try graph.contexts(in: fixture.family).first(where: { $0.id == classroom })?.path == "School › 2026 › Prep A")+ #expect(throws: GraphError.self) { try graph.moveContext(school, parentID: classroom) }+ let other = try graph.createFamily(name: "Other")+ let foreign = try graph.createContext(name: "Foreign", familyID: other)+ #expect(throws: GraphError.self) { try graph.createContext(name: "Invalid", familyID: fixture.family, parentID: foreign) }+ #expect(throws: GraphError.self) { try graph.addMembership(connectionID: fixture.connection, contextID: foreign) }+ #expect(throws: GraphError.self) {+ try graph.addMembership(connectionID: fixture.connection, contextID: classroom,+ startedAt: Date(timeIntervalSince1970: 20), endedAt: Date(timeIntervalSince1970: 10))+ }+ _ = try graph.addMembership(connectionID: fixture.connection, contextID: classroom)+ #expect(throws: GraphError.self) { try graph.addMembership(connectionID: fixture.connection, contextID: classroom) }+ #expect(try graph.memberships(for: fixture.connection).count == 1)+ #expect(try graph.origin(for: fixture.connection) == nil)+ #expect(try graph.contexts(in: fixture.family).count == 3)+ }+ }++ @Test func contextPeopleReuseIdentityWithoutCreatingPeerConnectionAndEnrichmentStaysStable() throws {+ try withGraph { fixture, _ in+ let graph = fixture.graph+ let source = try graph.createContext(name: "Prep A", familyID: fixture.family)+ let adult = try graph.addPerson(name: "Mrs Brown", familyID: fixture.family)+ let first = try graph.associatePerson(adult, contextID: source)+ let repeated = try graph.associatePerson(adult, contextID: source)+ #expect(first == repeated)+ #expect(try graph.contextPeople(source).map(\.name) == ["Mrs Brown"])+ #expect(try graph.connections(for: fixture.child).count == 1)+ try graph.updatePerson(adult, name: "Mrs Brown Smith", notes: "Teacher",+ needsReview: false, expected: graph.person(adult))+ #expect(try graph.people(in: fixture.family, search: "brown").first?.id == adult)+ #expect(try graph.people(in: fixture.family, needsReview: true).allSatisfy { $0.id != adult })+ #expect(try graph.person(adult).notes == "Teacher")+ #expect(try graph.contextPeople(source).map(\.name) == ["Mrs Brown Smith"])+ }+ }++ @Test func everyNewRelatedEntityUsesFamilyStore() throws {+ for shared in [false, true] {+ try withGraph(shared: shared) { fixture, _ in+ let graph = fixture.graph+ let source = try graph.createContext(name: "Swimming", familyID: fixture.family)+ let event = try graph.createEvent(title: "Playdate", date: Date(), familyID: fixture.family)+ _ = try graph.addMembership(connectionID: fixture.connection, contextID: source)+ let adult = try graph.addPerson(name: "Coach", familyID: fixture.family)+ _ = try graph.associatePerson(adult, contextID: source)+ try graph.saveOrigin(connectionID: fixture.connection, input: OriginInput(eventID: event), expectedOrigin: nil)+ try graph.setCloseness(.friend, connectionID: fixture.connection, expectedID: nil)+ try graph.setConnectionState(.lostContact, note: "Moved", connectionID: fixture.connection, expectedID: nil)+ for entity in ["Context", "Event", "ConnectionContext", "ContextPerson", "ConnectionOrigin", "Person",+ "OriginProposal", "ConnectionClosenessPeriod", "ConnectionStatusPeriod"] {+ let objects = try fixture.stack.container.viewContext.fetch(NSFetchRequest<NSManagedObject>(entityName: entity))+ #expect(!objects.isEmpty)+ #expect(objects.allSatisfy { $0.objectID.persistentStore == fixture.family.persistentStore })+ }+ }+ }+ }++ @Test func stalePersonReviewCannotDiscardNewerEnrichment() throws {+ try withGraph { fixture, _ in+ let graph = fixture.graph+ let personID = try graph.personID(for: fixture.connection)+ let old = try graph.person(personID)+ try graph.updatePerson(personID, name: "Friend Smith", notes: "Swimming friend", needsReview: true, expected: old)+ #expect(throws: GraphError.self) {+ try graph.updatePerson(personID, name: old.name, notes: old.notes, needsReview: false, expected: old)+ }+ #expect(try graph.person(personID).name == "Friend Smith")+ #expect(try graph.person(personID).notes == "Swimming friend")+ #expect(try graph.person(personID).needsReview)+ }+ }++ @Test func localAndExtensionCoordinatorsCannotPrepareCloudShares() async throws {+ let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ defer { try? FileManager.default.removeItem(at: directory) }+ let fixture = try GraphFixture(directory: directory)+ await #expect(throws: SharingError.self) { try await FamilySharing(stack: fixture.stack).prepare(familyID: fixture.family) }+ let writer = try await PersistenceStack.open(+ configuration: StoreConfiguration(directory: directory, role: .appIntent, mirrorsCloud: false)+ )+ let family = try #require(FamilyRepository(stack: writer).families().first)+ await #expect(throws: SharingError.self) { try await FamilySharing(stack: writer).prepare(familyID: family.id) }+ #expect(try fixture.graph.families().count == 1)+ }+}
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5e9e9b6..2c27214 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,40 @@ ### Added +- V6 duplicate suggestions, explicit merge previews and choices, retained reference/+ account history, affected-record undo and conservative recovery of competing merges.+- Read-only archived relationships, stale editor/capture guards and explicit transfer+ of unreviewed late accounts as alternatives without duplicating unchanged values.+- Eighteen additional synthetic merge/recovery/migration test cases. V6 source+ passes 79 cases/10 suites, strict lint (0/55) and both Debug platform builds.++- V5 family facts/assertions, groups, editable scoped address labels and conservative+ date-aware kinship paths; partial deceased dates in deliberate Sensitive Details.+- Social-event participation with independent invitations/attendance, multiple roles,+ multi-party gifts and Event-owned attachment references.+- Bounded background primary-photo/Event imports, image metadata removal, retained+ replaced assets, versioned thumbnails and cancellable document previews.+- Explicit reviewed-set resolution for closeness/status conflicts, preserving every period.+- Eighteen additional synthetic memory/image/temporal/migration test cases;+ all 61 cases pass with strict lint and both Debug platform builds.++- Retained causal first-meeting proposals with explicit conflict review, stale-resolution+ guards and late-arrival preservation.+- Five closeness choices, numeric 1...10 validation, explicit retained relationship+ history, and active/lost-contact controls.+- Multiple custom dated roles per Person/Context, guarded role/date editing, and+ child-qualified membership links.+- Seventeen additional synthetic conflict, defaults, review, V3 migration and refresh tests.+- Native Children/People/Contexts/Events/Review workspace with Mac sidebar and iOS tabs,+ family selection, focused name-only capture and a consolidated review queue.++- Native FamilySpace sharing controls, share reuse, invitation acceptance and retry.+- Nested Contexts, independent membership history, optional first-meeting memory,+ minimal dated Events and relevant-person Context associations in model V3.+- People search/review, sparse record enrichment and existing-person reuse across children.+- Twelve additional local graph, stale-edit, migration and cross-coordinator tests.+- Debug-only synthetic-store launch path for isolated UI checks.+ - Family and child selection with name-only Person capture and direct Connection lists. - Versioned Core Data graph and generic Asset payload storage, including V1-to-V2 migration. - App Group Private/Shared stores with host-owned CloudKit mirroring, local-only@@ -22,6 +56,21 @@ ### Changed +- Select model V6 while retaining V1–V5. Keep merge/recovery audits metadata-only+ and preserve existing encoded photo/attachment assets.++- Preserve all earlier models while migrating both stores to V5; retain existing+ Event identity, references and unknown dates during enrichment.++- Preserve V1–V3 models while migrating both stores to V4; retain each legacy origin+ account when first edited in the proposal model.+- Use a native macOS Grid relationship form with calm fields and section glass.++- Preserve prior models while migrating both stores to V3; merge local repository+ changes explicitly and reject stale Person/origin edits.+- Scope graph refresh notifications to the owning stack and show dates/notes for Events.+- Allow structured test/coverage options through the Makefile test target.+ - Configure the production bundle ID, CloudKit container, App Group, and notification capabilities; share one host coordinator across app windows. - Include test sources in strict SwiftLint validation.
diff --git a/README.md b/README.mdindex 629988f..f92e548 100644--- a/README.md+++ b/README.md@@ -1,7 +1,8 @@ # Halo Family -SwiftUI app for iPhone, iPad, and macOS. The repository currently contains the-capture UI and persistence foundation and the [design pack](docs/halo_family_design_pack/README.md).+SwiftUI app for iPhone, iPad, and macOS, with quick capture, People, Contexts,+first-meeting memory, family knowledge, social-event memory, photos and native family-sharing plumbing.+The [design pack](docs/halo_family_design_pack/README.md) tracks the staged scope. ## Setup @@ -32,7 +33,7 @@ make lint # SwiftLint; warnings count as failures make build-ios # Generic iOS Simulator build; no simulator boot required make build-macos # macOS build make check # Lint and build both platforms-make test # Local persistence/history/Asset/migration tests on macOS+make test # Local synthetic persistence/domain/history/Asset/migration tests on macOS make build-release # Release builds make clean # Remove local build output ```@@ -46,14 +47,50 @@ The Swift package compiles the same persistence sources and versioned model as the app. `make test` runs Swift Testing against temporary SQLite stores on macOS; it does not test iOS UI or CloudKit. Test artifacts use `DerivedData/swift-tests`. -## Try the first increment+## Try the app Run the shared scheme in Xcode on a simulator or on My Mac. Create a family,-add a child, then enter a name or description and select **Save person**. Select-another child or family to change the displayed connections. Quit and reopen to-read saved data. Same-name captures intentionally create distinct People.--This is temporary navigation for exercising the data layer. The app now opens+add a child, then choose **Remember someone**, enter a name or description and+select **Save person**. Select another child or use the family toolbar button to+change family. Mac uses a sidebar; iPhone/iPad uses tabs. Quit and reopen to read+saved data. Same-name captures intentionally create distinct People.++Open a captured Connection to record its first meeting independently of Context+membership. Create nested Contexts and dated birthday/playdate memories through+the family links. A meeting with an unknown date can use a description. Ending+memberships or archiving a Context preserves the Connection and its origin.+Review collects new captures and competing relationship accounts. People supports+name search, review filtering, enrichment and linking one existing+Person to another child. Contexts can associate relevant people with multiple custom+roles and optional dates, without creating peer Connections. Membership rows identify+the child and link to that child's Connection. Relationship controls offer Met once,+Know them, Friend, Good friend and BFF, plus active/lost-contact status and an optional+explanation. Only explicit value changes create closeness periods; history is retained.++Person detail links to structural family facts, entered assertions, address labels+and groups/households. Known kinship paths are derived conservatively, independently+of entered family titles. Use the ellipsis menu to deliberately open Sensitive Details:+deceased status and optional partial date preserve all history and Connection state.+Default child/review/participation suggestions suppress deceased People; explicit+People search and historical inclusion remain available.++Social Events retain invitations and attendance separately, multiple custom roles,+multi-person/group gift givers and multiple recipients. Gifts can refer to that Event's+attachments. These are social memories, without calendar or reminder scheduling.+All family notes, photos and Sensitive Details are visible to invited co-parents;+this is stated before opening system sharing controls.++**Share family** prepares/reuses a FamilySpace share and presents native private+read/write invitations. Accepted invitations open in the Shared store; downloads+arrive asynchronously. Signed device/two-account sharing is not yet verified in+this implementation. Referenced sources can be archived while preserving their links.+V6 merge source passes its local domain/build gate. Explicit previews+retain original identities and accounts; guarded undo restores affected references+only while unchanged. Review surfaces late accounts and competing merges. Recovery+shows separate identities while preserving current references and earlier audits.++The workspace is a reversible navigation implementation that can accommodate the+remaining family/social-memory features. The app opens `Persistence/Private.sqlite` and `Persistence/Shared.sqlite` inside the App Group, with host-owned CloudKit mirroring. All windows reuse one host coordinator. The old `HaloFamily-LocalDevelopment` database is left untouched and is not@@ -64,14 +101,37 @@ promise that another device has received the changes. Startup failures offer retry. CloudKit errors and history-refresh failures are visible in the form. The history processor merges store changes before advancing per-store checkpoints; launch, foreground entry and remote-store notifications trigger processing.-History pruning remains deferred until the retention policy is settled.+Persistent history is retained until safe checkpoint-based pruning is verified. The storage factories support local-only intent/widget roles: intents can write, widgets are read-only, and both require stores prepared by the host. There are-no shipped extension targets yet. Generic Asset payloads are saved on a background-context with external storage enabled; photo/import UI is still pending.+no shipped extension targets yet. Asset payloads are saved on a background context with external storage enabled.+Person detail supports Photos/Files imports; primary photos are encoded as JPEG,+up to 2048 pixels and 4 MB. Event JPEG/PNG/PDF imports allow up to 20 MB; image+location metadata is stripped. Each import owns its Asset; replacing/removing a+primary photo preserves the earlier encoded copy pending safe explicit cleanup.++Model V6 preserves V1–V5 for migration and passes both-store migration tests.+Local origin CRUD rejects invalid links,+empty origins and stale edits. Immutable causal proposals retain competing accounts;+the Connection shows **First meeting needs review** until a parent chooses a version.+Resolution retains alternatives, and late arrivals can require another review. Linked+Context/Event and entered description are displayed separately. Overlapping closeness+or contact periods are retained for explicit choice. Resolution closes only the+current periods actually reviewed and creates a fresh selected period; late arrivals+can require review again. Local fixtures do not establish live CloudKit convergence.++For an isolated Debug UI check, launch the built app with+`--synthetic-store /tmp/halo-ui-<unique-id>`. Only a subdirectory of the system+temporary directory or `/tmp` is accepted. This opens plain local SQLite stores+without the App Group or CloudKit. Release builds ignore this Debug launch path.++The V5 gate passes 61 synthetic tests in 9 suites, strict lint in 44 files and+sequential iOS Simulator/macOS Debug builds. Runtime UI and actual two-account+CloudKit delivery remain unverified. Later application phases remain in progress.+V6 passes 79 synthetic cases in 10 suites, strict lint 0/55 files and both Debug+platform builds. The separate Contacts source checkout is outside this gate. -Share invitations/acceptance, Contexts, origins and Events remain to implement. See the [acceptance report](docs/halo_family_design_pack/10-initial-implementation-results.md) for current evidence and verification limits.
diff --git a/docs/halo_family_design_pack/00-design-document.md b/docs/halo_family_design_pack/00-design-document.mdindex 428f3ef..99c3821 100644--- a/docs/halo_family_design_pack/00-design-document.md+++ b/docs/halo_family_design_pack/00-design-document.md@@ -199,7 +199,7 @@ Pacifica can first meet Mia at Sophie's birthday, then later share school class ### 3.6b ContextPerson -Associates a Person with a Context as teacher, coach, educator or another relevant role. These associations do not require peer Connections or separate Adult/Child entity types. Role vocabulary and lifecycle remain open.+Associates a Person with a Context as teacher, coach, educator or another relevant role. These associations do not require peer Connections or separate Adult/Child entity types. Multiple custom roles with optional dates per association are approved; further lifecycle behavior remains open. ### 3.7 PersonRelationship @@ -283,7 +283,7 @@ The app's Person remains the canonical record. Connection state is independent of Context membership and origin. -- Closeness uses five UI positions backed by `1...10`; exact labels/mapping remain open.+- Closeness uses five UI positions: 1 Met once, 3 Know them, 5 Friend, 7 Good friend, 10 BFF. The labels are approved and the numeric mapping is the corresponding implementation choice. - No sentiment model in v1. - Closeness history is recorded only on explicit changes, retained indefinitely and hidden in v1. - Connection status is `active` or `lostContact`, with an optional free-text explanation.@@ -685,7 +685,7 @@ Explicitly not goals: See `03-open-questions.md` for the authoritative unresolved decision queue and `09-implementation-handoff.md` for phase gates. Do not interpret examples, candidate schema or likely UI directions as final decisions. -Outstanding areas include closeness labels/mapping, origin lifecycle and conflict handling, family primitives, Event states, attachment associations, navigation, privacy and production lifecycle policies. First-meeting provenance is settled as ConnectionOrigin; persistence architecture is selected. Neither needs reopening as a general modelling or architecture question.+Outstanding areas include concurrent temporal histories, origin linked-source renames/deletion/merge, family primitives, Event states, attachment associations, navigation, privacy and production lifecycle policies. First-meeting provenance, competing origin preservation/review, five closeness labels/mapping and multiple custom dated roles are settled; persistence architecture is selected. See `decision_log.md` for the approved defaults. ---
diff --git a/docs/halo_family_design_pack/01-data-model.md b/docs/halo_family_design_pack/01-data-model.mdindex f4017d0..9ce5af5 100644--- a/docs/halo_family_design_pack/01-data-model.md+++ b/docs/halo_family_design_pack/01-data-model.md@@ -1,6 +1,6 @@ # Data Model — Halo Family -**Status:** Current domain contract; explicitly marked candidate fields remain unresolved +**Status:** Current domain contract; remaining application defaults approved in Decision 2 **Purpose:** Capture the current entity structure and the reasons behind each modelling decision. ---@@ -56,7 +56,7 @@ erDiagram PERSON ||--o{ EXTERNAL_LINK : has ``` -This is a conceptual domain model, not a final Core Data schema. Candidate attachment cardinalities are not settled. `ConnectionOrigin.context` and `.event` are mutually exclusive; the diagram alone cannot express that rule. Core Data optionality, inverses and defaults must be validated for CloudKit separately from domain validation.+This is a conceptual domain model; the V5 Core Data schema preserves prior models and uses optional inverse relationships. Decision 2 settles attachment ownership and the remaining application defaults. `ConnectionOrigin.context` and `.event` are mutually exclusive; the diagram alone cannot express that rule. Core Data optionality, inverses and defaults must be validated for CloudKit separately from domain validation. This is intentionally a domain model rather than a generic graph model. @@ -95,8 +95,8 @@ Person - familyName: String? - notes: String? - isDeceased: Bool-- dateOfDeath: PartialDate? // persistence representation unresolved-- primaryPhoto: Asset? // whether photos ship in v1 remains open+- dateOfDeath: PartialDate? // optional year/month/day; each more precise field requires the preceding field+- primaryPhoto: Asset? // approved: one app-owned primary photo - reviewState: ReviewState - createdAt: Date - modifiedAt: Date@@ -125,7 +125,7 @@ Noah's mum Girl from swimming ``` -`reviewState` means “surface this again later”, not “invalid record”. Deceased state is Person-level, with optional partial date of death; expose it through Sensitive Details and suppress inappropriate proactive surfacing. Automatic Connection-state changes remain unresolved.+`reviewState` means “surface this again later”, not “invalid record”. Deceased state is Person-level, with optional partial date of death; expose it through Sensitive Details and suppress inappropriate proactive surfacing. Connection state/history remains unchanged; deceased status controls proactive presentation. --- @@ -187,9 +187,9 @@ ConnectionClosenessPeriod - endedAt: Date? ``` -Five discrete UI positions map into the numeric domain `1...10`; zero is invalid. Final labels and the five numeric values remain open. Closeness is optional: no period is required for quick capture.+Five discrete UI positions map to 1 Met once, 3 Know them, 5 Friend, 7 Good friend and 10 BFF. Zero is invalid. The user approved the labels; this numeric mapping is the corresponding implementation choice. Closeness is optional: no period is required for quick capture. -Create a new period only on an explicit value change. Preserve every previous period indefinitely; history is hidden in v1 UI. No sentiment entity, field or control is part of v1. Concurrent period edits need reconciliation policy before multi-writer history is considered complete (open questions section 2).+Create a new period only on an explicit value change. Preserve every previous period indefinitely; history is hidden in v1 UI. No sentiment entity, field or control is part of v1. Competing current periods are retained. Explicit resolution closes exactly the reviewed current set and creates a fresh selected period; late arrivals remain reviewable. Two-account verification remains required. --- @@ -205,7 +205,7 @@ ConnectionStatusPeriod - note: String? // optional free-text explanation ``` -Lost contact preserves the relationship and closeness history. Reconnection reuses the same Person and Connection. No structured loss-reason taxonomy is required. Death belongs to Person, not a Connection loss reason. Exact temporal/concurrent-edit handling remains open.+Lost contact preserves the relationship and closeness history. Reconnection reuses the same Person and Connection. No structured loss-reason taxonomy is required. Death belongs to Person, not a Connection loss reason. Temporal conflict resolution follows the same reviewed-set policy as closeness. --- @@ -241,7 +241,7 @@ Activities Generic recursive hierarchy is more flexible than separate entities for school, class, sport, team, playgroup, etc. -The full path is derived from parent relationships rather than duplicated as a string. Seeded categories start with School, Playgroup, Parent group, Childcare and Activities; categories are user-defined. Seed rename/delete/semantic-identifier rules remain open.+The full path is derived from parent relationships rather than duplicated as a string. Seeded categories start with School, Playgroup, Parent group, Childcare and Activities; categories are user-defined. Seeded labels are editable ordinary categories with no automatic School semantics. Referenced categories/sources are archived instead of silently dropping links. --- @@ -287,7 +287,7 @@ ConnectionOrigin - A Connection has zero or one origin; each origin belongs to exactly one Connection. - An origin references either one Context or one Event, never both; alternatively it contains only a non-blank free-text description.-- A description may supplement the linked Context or Event. Display precedence/wording remains open; preserve both pieces of information.+- A description may supplement the linked Context or Event. Display the linked source and the parent-entered description separately; preserve both pieces of information. - An empty origin is invalid. An unknown origin is represented by no origin record. - All linked records belong to the same FamilySpace and persistent store as the Connection. - Origin is child-specific: two children may first meet the same Person in different places.@@ -311,7 +311,24 @@ Connection: Rigel -> Mia Origin: description = Met at a playground while on holiday ``` -The optional, singular v1 origin follows the accepted design direction. Concurrent origin creation/replacement, deletion of a referenced Context/Event, and conflicting origins during explicit Person/Connection merge need policies before those operations ship; see open questions section 4.+The optional, singular current origin follows the accepted design direction. Keep competing offline proposals for explicit review and retain alternatives as history (Decision 1). Linked display follows the current source name separately from the preserved narrative. Referenced sources are archived. Overlapping Connections require an explicit merge preview and origin choice while retaining all proposals.++### Implemented proposal representation++Model V4 adds `OriginProposal` with UUID, FamilySpace, Connection, optional Context+or Event, narrative, creation date and a cleared flag. Immutable proposals reference+the predecessor proposals actually observed by their author. Heads are proposals+with no known successor. One head supplies the current origin; multiple heads show+review rather than selecting by timestamps. An explicit resolution acknowledges+every displayed head and records a new proposal, leaving alternatives intact.+Late arrivals can create a new conflict after resolution. Blank editors also retain+their observed head set so an unseen clear cannot be overwritten silently.++The existing ConnectionOrigin is a replaceable current projection, retained for+migration compatibility and stable local origin identity. Once proposals exist,+they are authoritative. The first edit of a V3 origin preserves its old account as+an initial proposal before appending the edit. Source deletion and merge policy+remain separate decisions; archiving does not remove references. --- @@ -322,19 +339,19 @@ ContextPerson - id: UUID - context: Context - person: Person-- role? // vocabulary/cardinality unresolved+- role: String? // custom; multiple role associations per Person/Context - startedAt: Date? - endedAt: Date? - notes: String? ``` -Core association for teachers, coaches, educators, coordinators and other Context-associated people. Do not create separate Adult/Child entities or a peer Connection solely to represent these roles. Role vocabulary and lifecycle are open in section 6 of the questions document.+Core association for teachers, coaches, educators, coordinators and other Context-associated people. Do not create separate Adult/Child entities or a peer Connection solely to represent these roles. Multiple custom role associations, each with optional start/end dates, are approved. Archiving a Context preserves every role link; dates are entered explicitly. Successor-copy behavior remains a v2 class-rollover decision. --- ## 10. PersonRelationship -Proposed structural family relationship.+Approved separate structural family relationship (Decision 2). ```swift PersonRelationship@@ -348,7 +365,7 @@ PersonRelationship - note: String? ``` -Candidate primitive kinds:+Primitive kinds: ```text parentOf@@ -357,7 +374,7 @@ partnerOf guardianOf ``` -Possible nature:+Optional nature: ```text biological@@ -375,7 +392,7 @@ This supports deriving family-side information without storing every possible ki ### Open -The final primitive relationship vocabulary is not decided.+The primitive vocabulary and optional qualifiers above are approved implementation defaults. Derived kinship never replaces assertions or address labels. --- @@ -429,7 +446,7 @@ No placeholder parents/grandparents required. ### Open -This may remain a separate entity, or be unified with PersonRelationship using provenance/relationship type.+Keep a separate free-text assertion, useful without complete ancestry. No missing relatives are invented. --- @@ -466,7 +483,7 @@ This is especially important for culturally specific family terminology. ### Open -Whether `usedByGroup` is necessary in v1 and how language/script metadata should work.+Labels may be scoped to one Person, one group, or generally, with optional language/script. Editing a label preserves structural family facts. --- @@ -557,7 +574,7 @@ The date exists for history and querying, not scheduling. ### Open -Exact EventType vocabulary.+Use an optional custom Event type. Events remain social memory, not personal-life timeline events or calendar/reminders. --- @@ -568,7 +585,7 @@ EventPerson - id: UUID - event: Event - person: Person-- role: EventRole?+- roles: Set<String> // multiple custom roles - invitationState: InvitationState? - attendanceState: AttendanceState? - note: String?@@ -588,7 +605,7 @@ Potential invitation states: ```text considering-planned+intendToInvite invited accepted declined@@ -614,7 +631,7 @@ Allows queries such as: ### Open -The exact state model needs refinement to avoid overlapping or contradictory values.+Planning/invitations (unknown, considering, intendToInvite, invited, accepted, declined) are independent from attendance (unknown, attended, didNotAttend). An attended uninvited guest is valid; neither state invents the other. --- @@ -624,12 +641,12 @@ The exact state model needs refinement to avoid overlapping or contradictory val GiftRecord - id: UUID - event: Event-- fromPerson: Person?-- fromGroup: PersonGroup?-- toPerson: Person?+- givers: Set<Person>+- giverGroups: Set<PersonGroup>+- recipients: Set<Person> - description: String - note: String?-- attachment: EventAttachment?+- attachments: Set<EventAttachment> ``` ### Reason@@ -650,7 +667,7 @@ Craft kit ### Open -Whether gifts need multiple givers/recipients and whether attachments should be many-to-many.+Multiple Person/group givers and Person recipients are supported. Optional gift attachment references must belong to the same Event. --- @@ -661,7 +678,7 @@ EventAttachment - id: UUID - event: Event - kind: AttachmentKind-- asset: Asset // conceptual payload reference; ownership/cardinality still open+- asset: Asset // one app-owned payload per import - title: String? - note: String? - createdAt: Date@@ -687,7 +704,7 @@ Supports useful artefacts such as: ### Open -Physical storage is decided: generic `Asset` with Core Data Binary Data and Allows External Storage enabled. Whether EventAttachment remains an association/metadata entity or Events reference Assets directly remains open, along with ownership/cardinality and generic attachment associations beyond Events. Do not implement both alternatives as duplicate sources of truth.+Physical storage is decided: generic `Asset` with Core Data Binary Data and Allows External Storage enabled. EventAttachment is the sole Event/Asset metadata link. Each import creates one app-owned Asset; no payload is shared across families. Person primary photo is a separate optional one-to-one Asset link. ### Asset @@ -702,7 +719,7 @@ Asset - createdAt, modifiedAt ``` -Metadata is a recommended conceptual shape; see `06-attachment-photo-storage.md` for decided storage and outstanding policy.+V5 adds filename/contentType, byteCount, dimensions, kind and a content revision UUID for local thumbnail invalidation. See `06-attachment-photo-storage.md` for approved limits. --- @@ -767,7 +784,7 @@ Merging Person A into Person B should repoint: The survivor retains a stable ID. -Automatic merging is explicitly out of scope. Preserve origins while repointing Connections. If merging produces overlapping Connections for one child with different origins, do not silently discard either origin; resolve the merge policy in open questions section 4 first.+Automatic merging is explicitly out of scope. Preserve origins while repointing Connections. If merging produces overlapping Connections for one child with different origins, do not silently discard either origin; require explicit choice in the merge preview while retaining alternatives and guarded undo. --- @@ -807,4 +824,4 @@ This allows the app to answer historical questions without requiring a general j ## 23. Model questions still open -`03-open-questions.md` is the authoritative decision queue. Major schema gates include family relationship structure, PartialDate, closeness mapping and concurrent history, origin lifecycle/merge reconciliation, Event participation states, attachment associations and private versus shared metadata. Candidate shapes in this document do not settle those questions.+`03-open-questions.md` is the authoritative decision queue. Decision 2 approves the remaining application defaults. Class rollover stays v2; current source/verification and device/release gates are tracked separately. Historical candidate examples do not override the approved defaults.
diff --git a/docs/halo_family_design_pack/02-technical-architecture.md b/docs/halo_family_design_pack/02-technical-architecture.mdindex 7ec6e36..7436b65 100644--- a/docs/halo_family_design_pack/02-technical-architecture.md+++ b/docs/halo_family_design_pack/02-technical-architecture.md@@ -258,7 +258,7 @@ The persistence layer must expose a reliable way to: Persist ConnectionOrigin inside its Connection's FamilySpace graph and store. Any referenced Context or Event must belong to that same FamilySpace/store; reject cross-family links at the domain boundary. -Domain rules: zero or one origin per Connection, Context XOR Event when linked, otherwise non-blank description. Description may supplement a reference. These are application invariants, not a claim that CloudKit enforces uniqueness or atomic cross-device validation. Resolve concurrent origin creation/replacement policy before calling multi-writer support complete.+Domain rules: zero or one current origin per Connection, Context XOR Event when linked, otherwise non-blank description. Description may supplement a reference and is displayed separately. These are application invariants, not a claim that CloudKit enforces uniqueness or atomic cross-device validation. Model V4 implements the approved conflict policy with immutable causal OriginProposal records (Decision 1). It validates same-family references, UUID identity and every component of the predecessor graph. Multiple heads require explicit review; resolution records a new proposal referencing the displayed heads and retains all alternatives. No timestamp decides which account is correct. CloudKit two-account verification remains required before multi-writer transport is considered verified. Include origin changes in relationship fetch/refresh and persistent-history handling. Verify owner-created and participant-created origins, offline edits and references after relaunch. The persistence spike did not test ConnectionOrigin; its coverage must be added, not inferred from the spike report.
diff --git a/docs/halo_family_design_pack/03-open-questions.md b/docs/halo_family_design_pack/03-open-questions.mdindex c7a6d40..812d961 100644--- a/docs/halo_family_design_pack/03-open-questions.md+++ b/docs/halo_family_design_pack/03-open-questions.md@@ -1,500 +1,30 @@ # Open Questions — Halo Family -**Updated:** 2026-09-24--Only unresolved decisions belong here.-------## 1. Production hardening--### 1.1 No-iCloud-account lifecycle--The persistence spike deliberately deferred this.--Need to validate:--- app launch with no iCloud account;-- creation/editing of local data;-- persistence across relaunch;-- how sync unavailability is shown;-- what happens after an iCloud account later becomes available;-- whether pre-existing local data synchronises cleanly after sign-in.--### 1.2 Persistent-history retention--Need production policy for:--- checkpoint storage;-- pruning old persistent history;-- interaction with widgets/App Intents;-- recovery if a process checkpoint is stale or missing.--### 1.3 Migration--Need to define:--- Core Data model versioning policy;-- migration tests for Private + Shared stores;-- migration with existing CKShare-backed graphs;-- rollback/recovery expectations.--### 1.4 Account/share lifecycle--Need behaviour for:--- iCloud account change;-- share owner stops sharing;-- participant leaves/removes access;-- re-invitation;-- orphaned local cached data;-- ownership changes if ever supported.--### 1.5 Release CloudKit schema--Need deployment procedure for:--- development → production schema;-- indexes/record types;-- cloud encryption choices;-- release validation.-------## 2. Closeness--### 2.1 Five-step labels and numeric mapping--Decided:--- five discrete UI positions;-- stored numeric domain `1...10`;-- no zero;-- no sentiment model;-- history is created only on explicit changes;-- all prior values retained;-- history hidden in normal v1 UI.--Still open:--- final labels;-- exact numeric values for the five positions.--Illustrative only:--```text-1 Met once-3 Know them-5 Friend-7 Good friend-10 BFF-```--### 2.2 Concurrent temporal edits--Need reconciliation rules when two parents change closeness or Connection status offline, producing overlapping current periods. The spike established ordinary record convergence, not a production policy for temporal histories. Do not assume a deterministic last writer or discard retained history.-------## 3. Deceased Person handling--Decided:--- deceased status is Person-level;-- optional partial date of death;-- sensitive/deceased controls live in an unobtrusive Sensitive Details sheet;-- deceased People should not be proactively surfaced for actions they cannot take part in.--Still open:--### 3.1 Active Connection presentation--When Person becomes deceased:--- automatically convert active Connections to a historical/lost-contact presentation?-- or leave Connection state untouched and let Person deceased-state control presentation?--### 3.2 Feature suppression rules--Need an explicit production checklist for every feature that can proactively surface a Person.--Examples:--- birthday invite suggestions;-- reconnect prompts;-- enrichment prompts;-- widgets;-- graph defaults;-- recent-people surfaces.--### 3.3 PartialDate representation--Need reusable persistence choice for incomplete dates:--- year/month/day fields;-- or Date + precision enum;-- or another representation.-------## 4. ConnectionOrigin follow-up decisions--Decided: ConnectionOrigin is core, optional and singular per Connection in v1. It references one Context or one Event, or free text alone. A description may supplement a reference. Membership and first meeting are separate facts. There is no `metHere` flag on ConnectionContext.--Only these follow-up decisions remain open:--- **Suggestions:** whether/how the earliest Context is offered, confirmation before treating it as origin, and display wording for unconfirmed suggestions. Do not equate earliest recorded Context with first meeting.-- **Linked text:** display precedence when a description supplements a Context/Event; whether linked renames should change historical wording or retain a snapshot.-- **Deletion:** what happens when the referenced Context/Event is deleted; preserve description/snapshot, block deletion, or another explicit choice. Archiving is not deletion and should keep the reference.-- **Conflicts:** how simultaneous creation/replacement of the one origin is reconciled across parents without silently losing information.-- **Merge:** how origins are resolved if explicit Person merge consolidates two Connections for the same child.--These are UI/lifecycle policies, not a choice between a Connection field and ConnectionContext flag.-------## 5. Context categories--Seeded starting categories are decided:--```text-School-Playgroup-Parent group-Childcare-Activities-```--Categories remain user-defined.--Still open:--- can seeded categories be renamed/deleted?-- do seeded categories retain stable semantic identifiers?-- can a user-created category later be marked equivalent to `School`, etc. for feature behaviour?-------## 6. ContextPerson--`ContextPerson` is core.--### 6.1 Role vocabulary--Need to decide:--- seeded suggestions + custom roles?-- fully free-form roles?-- multiple roles for one Person in one Context?-- date ranges per role versus per ContextPerson record?--Likely seeded examples:--```text-Teacher-Coach-Educator-Coordinator-Leader-Staff-Parent helper-```--### 6.2 Lifecycle--Need to decide:--- exact start/end-date behaviour;-- what archiving a Context does to its ContextPerson links;-- whether a Person continuing into a successor Context is copied or newly associated.--### 6.3 Broad PersonKind--No separate Adult/Child entities.--Still open whether Person needs an optional:--```text-child-adult-unknown-```--presentation hint, or whether UI can infer enough from relationships/roles.-------## 7. School/class rollover — v2--Decided:--- manually triggered;-- no calendar-year assumptions;-- selective exclusions;-- previous Context archives as part of transition.--Still open:--- are all peer members selected by default?-- are ContextPerson adults offered separately?-- what metadata does successor Context inherit?-- how are children who stay in an old Context represented?-------## 8. Family model--### 8.1 Structural relationship primitives--Candidate set:--```text-parentOf-siblingOf-partnerOf-guardianOf-```--Need final decision on:--- stored vs derived sibling relationships;-- guardian overlap;-- former/temporal partnerships.--### 8.2 Relationship nature--Candidate qualifiers:--```text-biological-adoptive-step-foster-unknown-```--Need exact applicability.--### 8.3 PersonRelationship vs RelationshipAssertion--Still open whether to keep two entities or unify into one relationship entity with provenance/structure metadata.--### 8.4 Family side--Need rules for explicit versus derived:--- maternal;-- paternal;-- related through marriage;-- incomplete assertions.--### 8.5 Address labels--Need final behaviour for:--- per-person labels;-- group labels such as “the kids call her …”;-- multiple languages;-- native script/romanisation;-- preferred label selection.--### 8.6 Automatic kinship derivation--Need to decide which relationships are safely derivable and how ambiguity is represented.--Current direction remains conservative: derived relationship does not dictate the preferred family title.-------## 9. Event memory--### 9.1 Event type vocabulary--Do we need structured Event types in v1, or is title/date enough initially?--### 9.2 Invitation/attendance state--Need a model that avoids contradictory combinations across:--```text-role-planning/invitation state-attendance state-```--### 9.3 Future birthday planning--Need to support:--- considering;-- intend to invite;-- invited;-- accepted/declined;-- attended/did not attend.--Need final state machine.--### 9.4 Gifts--Need to decide:--- one or multiple givers;-- one or multiple recipients;-- PersonGroup as giver;-- gift-specific attachments.-------## 10. Assets/photos--Storage architecture is decided:--> Core Data Asset + Binary Data + Allows External Storage.--Still open production policy:--- maximum Person-photo dimensions/byte size;-- invitation image resizing threshold;-- supported document types;-- local thumbnail cache behaviour;-- cloud-encryption choices;-- whether Person photos ship in v1;-- attachment ownership/cardinality, including whether EventAttachment is retained as metadata or Events directly reference Assets;-- attachment ownership rules beyond Person primary photo + Event attachments.-------## 11. UI--### 11.1 Navigation--Final top-level navigation remains unresolved. ChildProfile appearance metadata (if any) also remains unspecified; do not make it a required capture field.--### 11.2 Child overview--Need to determine final prioritisation of:--- close/current relationships;-- recently added people;-- Contexts/groups;-- graph access.--No general upcoming-events/calendar section.--### 11.3 Person detail--Need to fit sparse and rich records without over-tabbed UI.--Must support:--- peer relationship information;-- ContextPerson roles;-- family;-- social-event history;-- Contacts;-- Sensitive Details.--### 11.4 Sensitive Details sheet--Need exact discoverability and interaction design.--Goal:--> a user can use the app normally without ever noticing it unless they deliberately look for sensitive details.--### 11.5 Graph--Need visual grammar for:--- Person vs Context;-- peer Connection vs ContextPerson role;-- current vs historical;-- family relationships;-- filtering dense graphs;-- deceased Person default visibility.--### 11.6 Inbox/review--Need exact rules for:--- what enters inbox;-- review completion;-- duplicate suggestions.--### 11.7 Merge People--Need to decide:--- choose survivor;-- field conflict handling;-- undo;-- preview of affected relationships.-------## 12. Search--Need behaviour across:--- partial names;-- custom labels;-- family titles;-- Contexts;-- ContextPerson roles;-- related adults;-- indirect family relations.-------## 13. Widget/App Intent product design--Architecture is validated.--Still need product decisions:--- one widget per child?-- quick-add only or Context shortcuts?-- Lock Screen support?-- identifying information visible while locked?-- App Intent parameters beyond child/name/Context?-------## 14. Privacy--Need decisions on:--- Person photos in v1;-- Lock Screen disclosure;-- app-switcher masking;-- CloudKit cloud encryption for sensitive attributes/assets;-- local file protection;-- shared vs per-parent private notes;-- export/delete.-------## 15. Export/import--Need to decide:--- when export is required;-- JSON, Markdown, or both;-- attachment bundle;-- whether export is re-importable;-- stable UUID behaviour;-- linked Contacts representation.-------## 16. Scope guardrail--For each proposed feature:--> Does this help remember who people are, how they connect, or the socially important history around those connections?--If not, it probably belongs elsewhere.--## 17. Delivery scope--The build plan is an ordered roadmap, not confirmation that every phase ships in v1. Person photos, export/import timing and final release scope remain open. Phase 10 class rollover is v2 and must not gate a v1 release. See the handoff for the smallest first implementation slice.+**Updated:** 2026-10-07 UTC++The user approved the remaining application defaults in Decision 2 of+`decision_log.md`. Those decisions supersede the former unresolved schema/product+queue. Implementation and verification are tracked separately in the build plan.++## Remaining decisions++- Class rollover is v2: selection defaults, successor metadata and separate+ ContextPerson handling still need a concrete design when that phase starts.+- Child appearance metadata remains optional and unspecified.+- Future first-meeting suggestions must remain unconfirmed until explicitly chosen;+ this release does not infer an origin from the earliest Context.+- Contacts identifiers are device-specific. Use a device-local link separate from+ canonical Person identity; do not mirror another device's address-book identifier.++## Remaining validation/release gates++- No-account launch/local editing/restoration, account change, removed share and+ reinvitation must be exercised without changing global settings in this task.+- Verify safe history pruning against every consumer checkpoint before pruning;+ retention is the approved interim behavior.+- Verify migration in both stores and existing CKShare graphs, real two-account+ delivery/offline conflict behavior, extension execution, and production schema.+- Native UI, image limits, quota/storage failures, large data and backup/import+ need current evidence. Historical spike results do not establish these gates.+- Production schema deployment, live invitations/private data and permanent live+ deletion still require specific authority.
diff --git a/docs/halo_family_design_pack/04-build-plan.md b/docs/halo_family_design_pack/04-build-plan.mdindex 9997464..3d62991 100644--- a/docs/halo_family_design_pack/04-build-plan.md+++ b/docs/halo_family_design_pack/04-build-plan.md@@ -1,6 +1,88 @@ # Build Plan — Halo Family -**Status:** Architecture spike complete; persistence foundation implemented in part+**Status:** Full application implementation in progress; release gates remain separate++### Duplicate/merge implementation — 2026-10-07 UTC++V6 source implements Phase 6 name suggestions, explicit merge previews and field/+overlapping-Connection choices, retained identities/accounts, metadata audit history+and guarded undo. Stale archived Person/Connection/ChildProfile editors reject;+self-Connections are archived rather than shown as current. Late imported accounts+have an explicit Review transfer that copies only unreviewed alternatives, retaining+original UUIDs. Opposing merge accounts and unsupported/circular aliases expose the+affected people. Recovery clears aliases while retaining current references and+all audit history; later explicit merges acknowledge observed recovery UUIDs.++The final sequential **make test → make check** gate passes: **79 tests/10 suites**+(18 new merge cases), **0 lint violations/55 files**, and both iOS Simulator/macOS+Debug builds. Runtime was 5.020 seconds, with no assertion failure or runner stall.+The first attempt failed test compilation because seven fixture status calls omitted+an existing required note argument; those calls were corrected without changing+assertions or inventory. Native UI and actual CloudKit transport remain unrun.+Contacts, backup/import, categories/search/role visibility, extensions and lifecycle+hardening remain active application work. Runtime/two-account/schema gates are separate.++### Family/photo/social-memory increment — 2026-10-07 UTC++Decision 2 records the remaining defaults approved by the user. V5 source adds+Person photos and partial deceased dates, structural facts and entered assertions,+scoped editable address labels, flexible groups, date-aware conservative kinship,+full social Event participation/gifts/attachment links and native forms. Image work+and payload saves run in the background; metadata is stripped and limits enforced.+Closeness/status conflicts now support explicit reviewed-set resolution.++The final make test → make check gate passes: 61 tests in 9 suites, including+18 new cases and both-store V4 migration; strict lint 0/44 files; sequential+iOS Simulator and macOS Debug builds. Runtime UI and two-account delivery have+not run. Initial compiler errors and final-review fixes are recorded in the+evidence document, separately from the passing assertion results.+Merge/duplicates, Contacts, backup/import, final extension UX and account/share+hardening remain active implementation work. Seeded editable Context categories,+richer search and Person-level Context role visibility also remain. Class rollover is v2.++### Approved defaults implementation — 2026-10-07 UTC++V4 adds immutable causal OriginProposal history, explicit conflict choice, retained+alternatives and late-arrival review. Blank/stale editors and stale resolution are+guarded by their observed proposal heads. Existing V3 origins are retained on first+edit. Five closeness controls write explicit numeric 1...10 periods; lost contact and+reconnection retain Person/Connection identity and earlier history. ContextPerson+supports multiple custom roles and optional dates. Context membership lists identify+the child and open the corresponding Connection.++The runnable workspace uses Mac sidebar/iOS tabs for Children, People, Contexts,+Events and Review. Capture stays name-only; child lists show explicit closeness+and can include lost-contact history. Review includes new Person captures and+competing origin/temporal accounts. Batched period/proposal queries keep list+refresh from fetching each Connection's state separately.++The final gates pass: 43 synthetic tests in seven suites, strict lint 0/34 files,+and make check with sequential iOS Simulator/macOS Debug builds. Native UI runtime+and real two-account CloudKit verification have not run. The previous checkpoint's+passing counts below remain historical.+Concurrent temporal histories are retained and flagged, with their explicit resolution+policy still open. Remaining durable family/Event/assets/privacy decisions are being+resolved while independent source work continues.++### Relationship implementation progress — 2026-10-06 UTC++Native share preparation/reuse and invitation acceptance are implemented in the+host, with private read/write system controls and cold/warm launch delivery.+V3 adds nested Contexts, independent memberships, optional first-meeting CRUD,+minimal dated Events and ContextPerson associations. People supports enrichment,+name search, review filtering and reuse across children. Direct queries and local+snapshot guards protect refresh and stale editor behavior.++Twenty-six local tests pass, including both-store V1/V2 → V3 migration. Strict+lint and both Debug platform builds pass individually; the initial combined+gate found a macOS SDK type rename, corrected and rebuilt. Device/two-account+sharing and native UI automation have not run. See the current evidence document.++The user approved origin conflict preservation/review, separate linked-source and+narrative display, five closeness labels/mapping and multiple dated custom roles.+These product defaults are recorded in `decision_log.md`; implementation follows+this checkpoint. Source deletion, merge, temporal history concurrency and later+roadmap/release choices remain gated. ### Implementation progress — 2026-10-07 @@ -109,7 +191,7 @@ Build: - search by name; - inbox/review. -Phase gate: settle closeness labels/mapping before the final control, and origin concurrent-edit/deletion policies before those operations ship. Minimal Event origin support must not depend on unresolved invitation/attendance enums. An unknown meeting date can remain a free-text origin rather than requiring an invented Event date. Validate scenarios 21–28.+Phase gate: implement and verify the approved closeness labels/mapping and retained competing origin proposals/review. Concurrent temporal histories, source deletion and overlapping Connection merge remain gated. Minimal Event origin support must not depend on unresolved invitation/attendance enums. An unknown meeting date can remain a free-text origin rather than requiring an invented Event date. Validate scenarios 21–28. Do not build graph visualisation yet.
diff --git a/docs/halo_family_design_pack/06-attachment-photo-storage.md b/docs/halo_family_design_pack/06-attachment-photo-storage.mdindex 8e2fa06..359ce4c 100644--- a/docs/halo_family_design_pack/06-attachment-photo-storage.md+++ b/docs/halo_family_design_pack/06-attachment-photo-storage.md@@ -58,11 +58,11 @@ Asset - modifiedAt ``` -Conceptual uses (Person-photo v1 scope and Event attachment association/cardinality remain unresolved):+Approved uses (Decision 2): ```text-Person.primaryPhoto -> Asset?-Event attachments -> Asset payloads // directly or through EventAttachment; decision pending+Person.primaryPhoto -> Asset? // one app-owned imported copy+Event -> EventAttachment -> Asset // one payload per imported attachment ``` ---@@ -80,7 +80,7 @@ Production policy should: - generate thumbnails locally; - keep decode/resize work off the main thread. -Exact maximum dimensions/byte target remain open.+Maximum Person photo dimensions are 2048 pixels, with a 4 MB encoded limit. Imports remove image location metadata. --- @@ -95,7 +95,7 @@ Policy should: - preserve PDF as PDF where imported as PDF; - keep filename/content type metadata. -Exact resizing threshold remains open.+Event attachments accept JPEG/PNG/PDF up to 20 MB. Image imports produce fresh metadata-free images; the implementation downsamples to a 4096-pixel bound. PDF remains PDF. --- @@ -121,23 +121,19 @@ Production requirements: ## 8. Privacy -Still to decide before production schema finalisation:+Approved defaults; verification remains required: -- cloud-encryption options for asset/sensitive attributes;-- local file protection policy;-- Lock Screen/widget disclosure;-- export/delete semantics.+- use Apple platform/CloudKit protections without claiming custom end-to-end encryption;+- iOS protection after first unlock supports extensions;+- home-screen capture only; no Lock Screen disclosure;+- explicit versioned ZIP backup/import preview, ordinary archives and separately confirmed permanent deletion. --- -## 9. Remaining production questions+## 9. Implementation and verification -The architecture is decided. Remaining policy questions are:--- Person-photo maximum dimensions/bytes;-- invitation image resize threshold;-- supported document content types;-- local thumbnail cache strategy;-- cloud encryption;-- whether Person photos ship in v1;-- ownership/reference rules if an Asset is ever shared by multiple domain records.+V5 source includes bounded background photo/attachment processing, app-owned imports,+size/type guards, metadata-free image encoding, local versioned thumbnail cache,+retained replaced photos and cancellable temporary document previews. Every related+record follows its FamilySpace store. Tests/builds and native/two-account delivery+are tracked in the implementation evidence; source presence is not transport proof.
diff --git a/docs/halo_family_design_pack/09-implementation-handoff.md b/docs/halo_family_design_pack/09-implementation-handoff.mdindex 0773407..2e2d179 100644--- a/docs/halo_family_design_pack/09-implementation-handoff.md+++ b/docs/halo_family_design_pack/09-implementation-handoff.md@@ -1,9 +1,11 @@ # Halo Family — Implementation Handoff -**Updated:** 2026-09-24 +**Updated:** 2026-10-07 **Working app name:** Halo Family **Product family:** Halo -**Readiness:** Ready to begin staged production implementation; not a fully closed specification.+**Readiness:** Application implementation in progress. Decisions 1 and 2 supersede+the original decision gates below; the current build plan and evidence document+distinguish implemented source from verified behavior. ## Start here @@ -27,10 +29,10 @@ Implement settled requirements and ordinary reversible engineering details. For 2. FamilySpace is the collaboration boundary. Person is canonical identity; ChildProfile marks our children; Connection is child-specific. Sparse records and same-name distinct People are valid. 3. ConnectionContext records shared-context membership. ContextPerson records relevant teachers/coaches/etc. ConnectionOrigin independently records first meeting. 4. ConnectionOrigin is optional and singular per Connection. It links a Context or Event, never both, or uses free text alone; linked descriptions are allowed. No origin is required for quick capture and no earliest-context inference becomes a fact automatically.-5. Closeness: five UI positions, numeric domain 1...10, no sentiment, explicit-change history retained but hidden in v1. Labels/mapping remain open. Connection status: active/lostContact with free-text explanation.-6. Person-level deceased state with optional partial date and discreet Sensitive Details; preserve history and suppress inappropriate proactive surfacing. Representation and state-transition details remain gated.+5. Closeness: five UI positions (1 Met once, 3 Know them, 5 Friend, 7 Good friend, 10 BFF), numeric domain 1...10, no sentiment, explicit-change history retained. Competing temporal histories require explicit review. Connection status: active/lostContact with free-text explanation.+6. Person-level deceased state with optional partial date and discreet Sensitive Details; preserve history, keep explicit search available and suppress routine suggestions. It does not automatically rewrite Connection history. 7. Core Data + NSPersistentCloudKitContainer in host; Private/Shared App Group stores; same-FamilySpace store assignment. Local-only widget/intent coordinators, persistent history, asynchronous notification handling. Intent success means local save.-8. Core Data-managed Asset binary data with external storage. No separate asset sync stack. Photo scope and size/privacy policy remain open.+8. Core Data-managed Asset binary data with external storage. One primary Person photo plus Event images/PDFs; strip photo location metadata, limit photos to 4 MB and attachments to 20 MB. No separate asset sync stack. 9. Events are social memory, not calendar/reminder features. Explicit merge only; no automatic Person deduplication. ## First implementation slice@@ -46,24 +48,27 @@ Start with Phase 1 and the settled subset of Phase 2: A minimal Event needs identity, FamilySpace, a known date and a useful title; optional notes follow the model. Reuse it in Phase 5. Do not introduce invitation-state enums just to support an origin. Use free-text origin when a formal dated Event is not warranted. -ContextPerson associations can proceed independently of final role vocabulary. Keep unresolved role-dependent UI and final closeness control out of the completed-slice claim until decisions are made. Provide a runnable minimal UI without presenting it as approved final navigation.+ContextPerson supports multiple custom roles per Person/Context with optional dates per association. Role vocabulary and five-step closeness labels/mapping are approved; further role lifecycle and concurrent temporal histories remain gated. Provide a runnable minimal UI without presenting it as approved final navigation. -## Decision gates+## Current decision and delivery boundaries -| Before implementing/shipping | Resolve in open questions |+| Area | Current boundary | |---|---|-| Signed app/device validation | §17 production setup values |-| Final closeness control and concurrent history | §2 labels/mapping and temporal reconciliation |-| Origin suggestion/display rules, source deletion, concurrent origin edits or overlapping Connection merge | §4 applicable lifecycle policies |-| Complete ContextPerson role/lifecycle features | §6 vocabulary/cardinality and lifecycle |-| Deceased-date persistence and automatic status changes | §3 PartialDate and Connection presentation |-| Durable family schema | §8 primitives, assertions and address labels |-| Full Event planning/gifts/attachment associations | §9–10 state and ownership models |-| Person photos | §10 and §14 scope, limits and privacy |-| Final navigation, widgets and merge UX | §11–14 relevant decisions |-| Production schema promotion / reliance on release | §1, §14–15 lifecycle, encryption, migration, export/delete policy |--These gates apply to dependent work; they do not block unrelated phases. Class rollover is v2. Phase 11 hardening gates the chosen release without waiting for v2 work. Final v1 scope remains explicit and unresolved where noted.+| Signing and identifiers | Confirmed from repository; device installation still requires specific authority |+| Concurrent histories | Preserve competing accounts and require explicit review; stale review cannot silently replace a later account |+| Origins and ContextPerson | Independent origin/narrative, custom dated roles and retained history are approved |+| Family facts and deceased details | Sparse facts, assertions, custom labels and partial dates are approved; never invent relatives |+| Events and Assets | Separate invitation/attendance, multiple gift parties, images/PDFs and approved size/privacy limits |+| Merge and source deletion | Explicit preview, archived referenced records, undo only while affected records are unchanged |+| Sharing | All family notes/details visible to invited co-parents; warn before sharing; no private-per-parent notes |+| Backup/import | ZIP of JSON and attachments, preview import, never silently overwrite an existing family |+| Navigation and extensions | Routine reversible UX may be implemented; no Lock Screen family capture |+| Release | Actual account/share lifecycle, device/two-account checks, schema deployment and required gates remain separate |++The user approved continuing the full application implementation through the+remaining pack phases. Class rollover remains v2. Approval of the product defaults+does not authorize live family data access, sending invitations, destructive live+operations, signing changes, installation or deployment. ## Verification and delivery
diff --git a/docs/halo_family_design_pack/10-initial-implementation-results.md b/docs/halo_family_design_pack/10-initial-implementation-results.mdindex 4337aa2..7b25029 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,216 @@ # Implementation evidence +## Duplicate/merge implementation — 2026-10-07 UTC++Phase 6 source passes its required local domain/build gate. Model V6 retains+V1–V5 and adds retained Connection/ChildProfile aliases, merge audits, append-only+late-account review and explicit recovery records. Native previews require identity+confirmation and choices for competing first meetings/current periods. All reference+kinds are consolidated, original UUIDs and encoded asset payloads remain, self-facts+and self-Connections archive, and Event participation accounts stay separate.++Undo checks only affected metadata against the saved post-merge snapshot and restores+earlier references without overwriting unrelated edits. It removes only untouched+merge-generated proposals/periods; the audit retains their selection. Stale archived+record editors/captures reject. Earlier Connection details are read-only.++Late offline accounts are compared with ordered per-Connection audit/review snapshots.+Explicit transfer copies only unseen/changed accounts into the kept Connection as+alternatives, retaining the originals. Repeated/stale review actions reject. Circular,+opposing and unsupported merge aliases expose the People in Review. Recovery shows+separate identities while retaining current references/notes/photos and prior audits;+new explicit merges acknowledge observed recovery UUIDs. These are local causal+guards, not a CloudKit transaction or delivery claim.++**Final verified gate:** 79 tests in 10 suites passed in 5.020 seconds, exit 0;+strict lint **0/55 files** and sequential iOS Simulator/macOS Debug builds passed,+exit 0. JUnit contains 79 cases with zero failures/errors/skips. The initial test+attempt stopped at compilation: seven fixture status calls omitted an existing+required note argument. Correcting the calls retained every assertion and test case.+No startup/teardown stall or assertion failure occurred. Native UI and real CloudKit+transport remain unrun; synthetic opposing/offline account imports do not prove live+CloudKit delivery. All owned heavy jobs drained after this gate.++Four final read-only source reviews are clear. Corrections cover stale writes,+self-Connections, late account visibility, opposing/delayed recovery, repeated review+copies, synthetic first-meeting absence and repeated snapshot scans. Evidence:+`/tmp/halo-merge-tests.log`, `/tmp/halo-merge-tests-compile.log`,+`/tmp/halo-merge-build.log` and `/tmp/halo-merge-review-inputs/junit-swift-testing.xml`.+Verification source is `00abc82` plus the recorded fixture argument corrections;+this gate excludes the independent Contacts worktree.++Full application scope remains active after this increment: Contacts, backup/import,+categories/search/role visibility, extension UX and lifecycle hardening. No live+family data, live CloudKit fixtures, account/security changes, physical installation,+push or main merge occurred.++## Family/photo/social-memory implementation — 2026-10-07 UTC++The user approved the remaining defaults in Decision 2. V5 source and native views+now implement family facts/assertions, groups, editable address labels, partial+deceased dates, social invitations/attendance, multiple roles/gift parties, photos+and attachments, and explicit temporal conflict choice. The final gate passes:+**61 tests in 9 suites**, exit 0, 2.700 seconds test runtime; **strict lint 0/44+files**; **make check**, exit 0, with sequential iOS Simulator/macOS Debug builds.+Four source reviews identified and prompted fixes for event draft+baselines, visibility, bounded Photos transfer, temporary preview cleanup, cache+revisions, date-aware/linear kinship validation and guarded address-label edits.+Final review additionally caught invented dates during legacy undated Event edits+and stale relationship endings. Both were corrected with meaningful assertions+inside existing cases, then the suite and both builds passed again. No cases were+removed or weakened. Final read-only review has no outstanding material finding.++Two initial attempts stopped at compilation before running tests: Swift needed+an explicit family-fact result type, then the test macro's throwing inference+and a fixture helper's MainActor annotation needed correction. The successful+61-case runs had no assertion failures, startup stalls or teardown crashes.++| Check | Result | Evidence / limit |+|---|---|---|+| Sparse family facts, entered titles and date-aware kinship | passed | Synthetic direct assertions, absent ancestors, dates and conservative paths |+| Deceased details and suppression | passed | Partial precision, invalid dates, stale edits, preserved Connection identity/history and explicit search |+| Groups and scoped address labels | passed | Independent memberships, guarded corrections and retained endings |+| Invitation, attendance and multi-party gifts | passed | Separate states, stable edited gift identity, stale drafts and same-Event attachment guards |+| Bounded image/PDF imports and revisions | passed | Metadata removal, dimensions/limits, unsupported/invalid files, shared-store placement, replacement and relaunch |+| Reviewed temporal resolution | passed | Exact displayed sets, retained notes/periods, stale resolution and late arrival |+| Event enrichment/archive | passed | Stable origin references, legacy unknown-date preservation and stale guards |+| Both-store V4 → V5 migration | passed | Person UUIDs, role/origin/temporal preservation and new defaults; earlier migration suites retained |+| Strict lint and both Debug builds | passed | Final make check, exit 0 |+| Native UI, Photos/Files/QuickLook and real CloudKit delivery | not run | Local domain tests and compilation do not establish OS runtime behavior |++Evidence: `/tmp/halo-memory-tests.log`, `/tmp/halo-memory-tests-compile.log`,+`/tmp/halo-memory-tests-test-compile.log`, `/tmp/halo-memory-build.log`,+the two `*-before-review-fixes.log` files and+`/tmp/halo-memory-review-inputs/junit-swift-testing.xml` (temporary local files).++Remaining implementation includes merge/undo, Contacts, backup/import, extension+UX and lifecycle hardening, seeded editable Context categories, richer search and+Person-level Context role visibility. Native runtime, two-account delivery and production+schema authority remain separate; no real family data was read or imported.+++## Approved relationship defaults and native workspace — 2026-10-07 UTC++Model V4 retains V1–V3 and implements immutable causal first-meeting proposals.+Simultaneous first creation, replacement, clear/edit competition and late arrivals+retain separate accounts. Review requires an explicit choice; resolution acknowledges+only the heads actually displayed and retains every alternative. Stale drafts,+including a blank editor opened before an unseen clear, cannot silently overwrite+newer accounts. Malformed predecessor graphs are rejected without deleting records.++Five closeness controls map to 1/3/5/7/10; the full numeric 1...10 domain is preserved.+Only explicit changes create closeness history. Lost contact/reconnection retain the+same Person/Connection and earlier closeness/status periods. Overlapping current+periods remain stored and appear in Review, pending their approved resolution policy.+ContextPerson supports multiple custom dated roles and guarded role/date editing.+Context membership rows distinguish children and navigate to their Connection.++The app now uses Mac sidebar/iOS tabs for Children, People, Contexts, Events and+Review. Family selection is per window; changing family resets routes. Capture is+still child + name/description. Child lists prioritize explicit closeness and offer+lost-contact inclusion. Review collects sparse captures and conflicting relationship+accounts; failed refresh retains an error/retry surface rather than claiming completion.++Final local gates: **43 tests in seven suites passed**, exit 0; strict SwiftLint+**0 violations in 34 files**; **make check passed**, exit 0, including sequential+iOS Simulator and macOS Debug builds on Xcode 27.0 (27A266a).++An initial test attempt failed compilation in a Swift Testing key-path macro; the+equivalent predicate closure corrected it without weakening assertions. The first+platform attempt found conditional-layout grouping in a SwiftUI editor; wrapping+the shared modifier target corrected it. Both builds then passed, and a final+focused date-default fix was rebuilt on both platforms. The successful 43-case run+had no assertion failure, startup stall or teardown crash. No domain code changed+after that run; subsequent corrections were UI-only.++| Check | Result | Evidence / limit |+|---|---|---|+| Retained origin branches and explicit resolution | passed | Synthetic simultaneous first writes, edit/clear branches and retained alternative UUIDs |+| Late arrivals and stale resolution/blank editors | passed | New accounts remain reviewable; stale reviewed-head sets reject |+| Malformed history and numeric bounds | passed | Cycles beside valid heads, zero/out-of-range values preserve data and surface errors |+| Closeness, lost contact/reconnection and retained history | passed | Explicit changes, same-value no-op and stable Person/Connection identity |+| Multiple roles, role/date edits and child-qualified memberships | passed | Role identity, invalid ranges and stale-edit guards |+| Scoped Review and batched relationship state | passed | Separate families, duplicate input IDs and resolved review items |+| Both-store V1/V2/V3 → V4 migration | passed | Prior migration suites plus V3 legacy origin/account and roleless-link preservation |+| Cross-coordinator proposal/status/closeness refresh | passed | Local intent-role writes merged through persistent history |+| Strict lint and both Debug platform builds | passed | Final make check, exit 0 |+| Native runtime UI/OS sharing and two-account transport | not run | Compilation/local SQLite evidence does not establish these |+| Remaining family, Event, photo, merge and privacy features | blocked | Concrete durable defaults are awaiting user approval; overall application scope is preserved |+| Release account/share lifecycle and schema promotion | blocked | Policy/device evidence and specific production authority remain required |++Four read-only source reviews ran. Fixes include complete graph cycle validation,+one validated head set per write, accurate numeric-domain display, native section+route resets, invitation cancellation/presentation ownership, honest failed Review+states and compatible unknown-start date defaults. No live family data, CloudKit+fixture writes, account/signing changes, physical-device install or main merge occurred.++Evidence: `/tmp/halo-defaults-tests.log`, `/tmp/halo-defaults-tests-compile.log`,+`/tmp/halo-defaults-build.log`, `/tmp/halo-defaults-build-compile.log`,+`/tmp/halo-defaults-build-before-date-fix.log` and+`/tmp/halo-defaults-review-inputs/junit-swift-testing.xml` (temporary local files).+This completes the settled Phase 2 source increment; later ordered application+features and release evidence remain to be completed.++## Relationship graph and sharing plumbing — 2026-10-06 UTC++Feature branch `feature/relationship-graph` continues the existing two commits.+Native iOS/macOS sharing controls use host-only Core Data share APIs. FamilySpace+shares are reused, invitations are private/read-write, metadata is container-checked,+and cold/warm invitation delivery targets the Shared store. Failed acceptance retains+the invitation for retry. No live account or CloudKit fixtures were used.++Model V3 retains V1/V2 and adds Context hierarchy, ConnectionContext, ConnectionOrigin,+minimal Event and ContextPerson. Repository writes validate family/store boundaries,+cycles, date ranges, origin XOR/nonempty rules and stale editor snapshots. Membership+and origin remain independent. The temporary SwiftUI navigation now exposes People,+name search/review, enrichment, existing-person reuse, Contexts/membership/archive,+dated Event labels/notes and all three local origin forms. Final navigation is still open.++Environment: Xcode 27.0 (27A266a), macOS, actual temporary SQLite stores.+`make test` with coverage/JUnit flags passed **26 tests in five suites**, exit 0.+Strict lint reports **0 violations in 22 files**. iOS Simulator Debug build passed.+The macOS build initially found a renamed sharing-options SDK type; the corrected+`make build-macos` passed, exit 0. The combined `make check` attempt therefore failed;+the affected build and lint subsequently passed, without rerunning the unaffected iOS build.++An earlier runtime attempt recorded **13 passes**, then a signal-6 fault when a queued+automatic merge outlived a synchronous fixture's removed SQLite files. The new fixture+now relies on the repository's explicit local merge before return, preventing queued+automatic merges after teardown. No assertion failure preceded that crash. The final+26-case run passed. Source and throwing-expression fixture compile errors were also+corrected before the successful runtime run.++| Check | Result | Evidence / limit |+|---|---|---|+| Origin description, Context and Event round-trip/edit/clear | passed | Local SQLite; identity and linked description preserved |+| Empty/XOR/cross-family origin and stale origin edit/clear | passed | Invalid operations rejected without partial writes |+| Independent origins for two children sharing one Person | passed | One canonical Person; separate Connections |+| Later/ended memberships and archived origin source | passed | Source, origin and Connection preserved; no automatic origin inference |+| Hierarchy cycles, date ranges, cross-family memberships | passed | Repository validation and unchanged graph assertions |+| ContextPerson reuse and Person enrichment/search/review | passed | Relevant person needs no peer Connection; stale review cannot discard enrichment |+| All new entities placed in owner/participant family store | passed | Synthetic Private/Shared placement, not CloudKit delivery |+| Both-store V1/V2 → V3 migration, graph and Asset UUID/data | passed | Existing V1 migration plus new V2 migration with payload checks |+| Second-coordinator origin/membership/archive refresh | passed | Insert/update/clear through local intent-role coordinator and history merges |+| Host-only sharing boundary | passed | Local and extension coordinators reject CloudKit share preparation |+| Strict lint, iOS Simulator/macOS Debug builds | passed | Individual final gates as described above |+| Native UI launch/automation | not run | Debug-only synthetic-store launch path is available |+| Actual invitations, owner/participant delivery, offline recovery | not run | Plumbing compiles; real device/two-account validation remains required |+| Simultaneous origin conflict preservation/review | not run | Product default approved; next implementation increment |+| Closeness controls and multiple dated ContextPerson roles | not run | Product defaults approved; next implementation increment |+| Source deletion, merge, account/share removal and release hardening | blocked | Policies or device/release evidence still required |++Four read-only source reviews ran. Findings about stale drafts, Event disambiguation,+Person relationship visibility, repeated global refresh and duplicated Person creation+were corrected. Logs/results: `/tmp/halo-graph-tests.log`,+`/tmp/halo-graph-tests-fixture-crash.log`, `/tmp/halo-graph-build.log`,+`/tmp/halo-graph-macos-build.log`, `/tmp/halo-graph-lint.log`, and+`/tmp/halo-graph-review-inputs/junit-swift-testing.xml` (temporary local files).++This is a tested implementation checkpoint. Whole-product completion and live sharing+are not claimed. Continue the approved defaults and remaining ordered roadmap work.++---+ ## Persistence foundation — 2026-10-07 The setup values are confirmed in Xcode and the app uses the production App
diff --git a/docs/halo_family_design_pack/CHANGELOG.md b/docs/halo_family_design_pack/CHANGELOG.mdindex aee02d0..1799f1a 100644--- a/docs/halo_family_design_pack/CHANGELOG.md+++ b/docs/halo_family_design_pack/CHANGELOG.md@@ -1,5 +1,31 @@ # Halo Family — Pack Changes +## 7 October 2026 UTC++- Add V6 duplicate/merge source, explicit previews, retained original records,+ guarded undo, late-account Review and conservative recovery of competing aliases.+ The V6 build/test gate passes: 79 cases/10 suites, strict lint 0/55 and both Debug builds.+- Record the verified V5 family/photo/social-memory gate: 61 tests/9 suites,+ strict lint 0/44 and both Debug builds. Keep runtime/transport evidence separate.++- Document V4 causal origin proposals, clear/resolution guards and legacy migration.+- Implement approved closeness labels/numeric domain, contact periods and dated roles.+- Add synthetic simultaneous-origin, late-arrival, malformed-history, stale editor,+ migration and cross-coordinator fixtures. Final gates pass 43 tests/seven suites,+ strict lint 0/34 files and both Debug builds. Implement reversible native workspace+ navigation and honest Review error states. Preserve remaining temporal, family,+ Event, asset and privacy choices; native/runtime and CloudKit transport are not verified.++## 6 October 2026 UTC++- User approved separate first-meeting source/narrative display, retention/review+ of competing offline origin proposals, five closeness labels and multiple custom+ roles with optional dates. Record the corresponding numeric mapping and causal+ proposal representation as implementation choices in `decision_log.md`.+- Remove resolved label/role/origin-conflict questions. Preserve unrelated rename,+ deletion, merge, temporal history, privacy and release gates.+- Add V3 relationship/sharing implementation progress and precise local verification.+ ## 24 September 2026 Source: the user-supplied `kids_relationship_app_design_current.zip` dated 22 September 2026. Original archive preserved.
diff --git a/docs/halo_family_design_pack/README.md b/docs/halo_family_design_pack/README.mdindex 0596c0f..a0929d8 100644--- a/docs/halo_family_design_pack/README.md+++ b/docs/halo_family_design_pack/README.md@@ -3,7 +3,7 @@ **Working app name:** Halo Family **Broader product family:** Halo **Platform:** Native iOS -**Status:** Ready for staged implementation; unresolved decisions remain explicit +**Status:** Application implementation in progress; remaining defaults approved in Decision 2 **Storage:** On-device + iCloud/CloudKit only **Collaboration:** Shared `FamilySpace` between parents/co-parents
diff --git a/docs/halo_family_design_pack/decision_log.md b/docs/halo_family_design_pack/decision_log.mdnew file mode 100644index 0000000..a77ccad--- /dev/null+++ b/docs/halo_family_design_pack/decision_log.md@@ -0,0 +1,101 @@+# Decision Log: Halo Family++## Quick Decisions++| ID | Date | Decision | Rationale |+|---|---|---|---|+| Q1 | 2026-10-06 UTC | Five closeness choices: 1 Met once, 3 Know them, 5 Friend, 7 Good friend, 10 BFF | User approved the proposed labels; numeric mapping is the corresponding adjustable implementation choice. |+| Q2 | 2026-10-06 UTC | Display the linked first-meeting Context/Event separately from the parent-entered description | User approved preserving both pieces without choosing one display field over the other. |+| Q3 | 2026-10-06 UTC | Allow multiple custom roles for one Person in a Context, with optional dates per role association | User approved custom role multiplicity and optional dates; no Adult/Child entity split. |+| Q4 | 2026-10-07 UTC | Use Children, People, Contexts, Events and Review navigation, with a Mac sidebar and iOS tabs | Reversible implementation choice within the pack's UI direction. Keep per-window family selection and reset routes when changing family. Prioritize explicit closeness in child lists; lost contact can be included deliberately. |+| Q5 | 2026-10-07 UTC | Retain source Connection accounts on archived records; transfer only late unseen/changed accounts as alternatives through Review | Implements the approved retention/review default. Keep original UUIDs, source histories and separate Event accounts; local snapshot checks do not claim a CloudKit compare-and-swap. |+| Q6 | 2026-10-07 UTC | Recover competing merges by exposing separate identities while preserving current references and all earlier audits | Reversible conservative recovery avoids replaying old references over later edits. Current unsupported aliases remain visible; subsequent explicit merges acknowledge observed recovery UUIDs. Recovery is described separately from guarded undo. |++## Decision 1: Retain competing first-meeting proposals for review++**Date**: 2026-10-06 UTC +**Status**: accepted++### Context++Two parents can enter different first-meeting information while offline: one remembers+a birthday, another remembers swimming. A singular current origin must not silently+erase either account when the devices reconnect.++### Decision++Retain competing origin proposals. Show that first meeting needs review and let a+parent explicitly choose the current account while retaining alternatives as history.+Use immutable proposals with causal predecessor references to detect competing edits;+the Connection's origin remains a singular current projection when unambiguous.++### Rationale++The user approved keeping both and asking which to use. Immutable proposals let+independent offline additions survive ordinary CloudKit convergence. Causal references+distinguish a deliberate later edit from an independently concurrent proposal without+claiming a deterministic CloudKit last writer. The representation is an implementation+choice supporting the approved behavior and still needs two-account verification.++### Alternatives Considered++- **Ordinary overwrite of one origin record**: simple, but can silently lose a parent's account.+- **Choose the newest timestamp automatically**: clock ordering does not establish which account is true and discards review.++### Consequences++Both accounts remain available and resolution is explicit. The model gains proposal+history and conflict UI; new offline alternatives can require review even after a prior+resolution. Source deletion and overlapping Connection merge remain separate gates.+++## Decision 2: Complete the application with the approved remaining defaults++**Date**: 2026-10-07 UTC+**Status**: accepted++The user approved the remaining defaults presented in message+`Sentinel_b953d9a66c448191bf7f1d13c3d98944`, replying+`Sentinel_2b42678b57f48191a35d548895c82ac8`: “Yes, these defaults are approved”.+The approval covers design and implementation with synthetic fixtures, not live+invitations, private-data sharing, permanent deletion, signing changes or deployment.++- Family knowledge may be incomplete. Keep structural relationships, entered+ assertions and address labels separate, with custom labels and optional dates;+ never invent missing relatives. The implementation uses parentOf, guardianOf,+ siblingOf and partnerOf primitives, optional nature qualifiers, flexible groups,+ and conservative derived kinship. These representations follow the recommended+ pack defaults; the user approved the behavior rather than every field name.+- Deceased status belongs to Person. Allow partial dates, retain Connection state+ and history, and suppress routine suggestions while preserving explicit search.+ Use a deliberate Sensitive Details sheet and optional year/month/day fields.+- Event planning/invitations and actual attendance are separate. Support multiple+ roles, gift givers and recipients, including group givers. No calendar/reminders.+ Use an optional custom Event type and one EventAttachment metadata link per+ imported Asset; gifts may refer to that Event's attachments.+- Include one primary Person photo and Event JPEG/PNG/PDF attachments. Strip image+ location metadata. Enforce 4 MB encoded photo and 20 MB attachment limits;+ downsample Person photos to 2048 pixels and keep processing off the main thread.+ Imports are app-owned copies within one FamilySpace.+- Preserve competing temporal edits for explicit review. Resolution closes only+ reviewed current periods and creates a fresh selected period, retaining history.+ Linked-origin display follows the source name separately from the narrative.+ Archive referenced sources, preserving membership/role links. Categories are+ ordinary editable labels, initially seeded with the five pack names.+- Require an explicit merge preview and survivor/conflicting-field choices.+ Repoint all references, retain the old Person as a hidden merge record, and+ resolve overlapping child Connections/origins explicitly. Undo is offered only+ while affected records remain unchanged. Never merge same-name People automatically.+- All FamilySpace notes/details are visible to invited co-parents; state that+ before sharing. No per-parent private notes. Use Apple platform/CloudKit+ protections without a custom end-to-end encryption claim. Account/access changes+ lock affected caches and preserve them for deliberate removal/reinvitation.+ Keep persistent history until safe pruning is verified.+- Export a versioned JSON and attachments ZIP. Preview import; preserve UUIDs only+ into an absent family, reject an existing-family overwrite, and offer an explicit+ fresh-ID copy. Ordinary removal archives. Permanent deletion requires a separate+ explicit action showing its sharing impact.++These decisions unblock the remaining application phases. Class rollover remains+v2; real device/two-account verification and production schema promotion remain+separate release gates. No automatic origin inference is introduced.
79 synthetic SQLite cases, zero JUnit failures/errors/skips, 5.020 seconds. Seven omitted fixture note arguments caused the initial compile failure; no assertions were changed or removed.
Contacts source has an isolated checkout; backup/import, categories/search, extensions and lifecycle continue. Native UI, real two-account delivery and schema promotion remain separate gates.