Three local increments compared with preserved baseline 8c5262f. No remote-tracking refs exist in this checkout. All earlier commits remain intact; no actual private family data or live cloud fixtures were used.
Native family facts, sparse deceased dates, scoped labels and independent households.
Social memory keeps invitation and attendance separate, with multi-party editable gifts and Event-owned images/PDFs.
Bounded background image processing strips metadata; thumbnails query revision metadata before fetching payload.
Explicit temporal conflict choice retains all reviewed periods and rejects stale resolutions.
Local V5 source verified
The final synthetic suite and sequential make check pass. Four read-only reviews have no outstanding material finding. The complete application is still in progress: merge, Contacts, backup, extensions, richer search and lifecycle hardening remain. Native UI runtime and real two-account delivery are not established by these checks.
Pass rate: 100% (61 of 61)
New tests: 47
Diff coverage: 94% (2370 of 2516 added lines)
Parents can record family relationships without filling in missing relatives, use the names a particular person or household uses, and keep social-event memories such as invitations, attendance and gifts. A primary photo helps recognize a person; invitation images and PDFs stay with their event.
People remain the same records when marked deceased or when relationship history changes. Competing accounts stay available for review. This checkpoint implements these local features; later application phases and real-device validation remain.
V5 extends the existing optional, inverse-linked Core Data model and retains V1–V4 migration paths. FamilyRepository reuses short-lived contexts, family/store validation, explicit view-context merging and scoped refresh. Separate facts, assertions and address labels avoid turning a derived kinship path into an entered fact. EventPerson and GiftRecord keep independent participation states and multiple party identities.
Native forms freeze edit baselines. Asset processing runs off the main thread, creates app-owned metadata-free bytes and stores them through the existing Asset mechanism. Cache keys use stable Asset identity plus a content revision. Completeness is limited to local domain/storage behavior and both-platform compilation.
Imports bound source bytes before decoding, use ImageIO thumbnails to bound decoded dimensions, and re-encode without forwarding source properties. Asset replacement preserves prior payload identities, while mutable generic payload replacement issues a new content revision. Local SQLite fixtures exercise shared-store placement, external binary storage, migration, relaunch and exact reviewed-set temporal resolution.
Kinship traversal considers effective dates, validates parent cycles with linear Kahn traversal, suppresses ambiguous derived labels and never overrides entered assertions. Stale edits compare persisted fields and identities, excluding derived party names. Undated legacy Event enrichment preserves nil, and stale endings cannot overwrite an existing end date. Global CloudKit uniqueness, concurrent transport, native Photos/QuickLook behavior and account lifecycle are not inferred from local tests.
Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift
Why it matters. Incomplete relatives and person-specific titles remain useful without invented ancestors.
What to look at. PartialDate, familyFacts, addressLabels, groups
Halo Family/Halo Family/Persistence/EventMemoryRepository.swift
Why it matters. Invitation does not imply attendance; gift editing preserves identity and guards stale references.
What to look at. saveParticipation, saveGift, updateEvent
Halo Family/Halo Family/Persistence/ImageImport.swift
Why it matters. Large image decode and metadata leakage are limited before the payload reaches persistent storage.
What to look at. photo, attachment, bounded image encoding
Halo Family/Halo Family/PhotoAssetViews.swift
Why it matters. Cache hits avoid full payload reads, and cancelled previews clean up even after late writes.
What to look at. PickedPhoto, AssetThumbnail, AttachmentPreview
Halo Family/Halo Family/Persistence/ConnectionStateRepository.swift
Why it matters. Conflicting state is retained and stale review cannot silently discard a later period.
What to look at. resolveCloseness, resolveStatus
Tests/HaloPersistenceTests/MemoryMigrationTests.swift
Why it matters. Owner and participant stores migrate without replacing people, origins or role/history accounts.
What to look at. bothV4StoresMigrateWithoutLosingOriginsRolesAndTemporalHistory
Decision 2 records the user approval with exact transcript message IDs. Source field choices implement those defaults proportionately; approval does not authorize live data operations or deployment.
Photo unlink/replacement retains previous encoded assets. Source records can be archived while origin references remain. Merge/undo and explicit permanent cleanup remain later work.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | Event editor baseline | A refreshed parent could replace the expected state while an older draft remained. | Freeze the initial EventRow in State and reject persisted-field changes. |
| major | Undated legacy Events | Enriching an event with no date could invent today. | Preserve optionality with deliberate known-date entry; regression checks preserve nil and stale guards. |
| major | Relationship end | A stale end action could overwrite an earlier entered end date. | Reject already-ended facts and verify the first end remains. |
| major | Asset memory and lifetime | Photos could allocate before checking limits, cache hits fetched payloads, and late preview writes could outlive cleanup. | Bounded FileRepresentation, metadata-first revisions and tracked cancellation/late cleanup. |
| minor | Derived state and editable memory | Name-based participant guards, add-only labels, future-date kinship and temporal coverage gaps. | Persisted-value guards, explicit label/gift edits, effective-date derivation and reviewed-status assertions. |
Source: local run at 2026-10-07T01:53:44.757952+00:00 · snapshot 3a04a8b4271c95e329c6dde0811bbd2d81f3c7f0 (dirty working tree)
Baseline: none
Execution: passed · JUnit: 1 file · Coverage: 1 file · Baseline: absent
Coverage scope: as the project configures it
Totals: 61 passed · 0 failed · 0 skipped · 0 errored · 0 flaky
Derived by declaration name, from the diff (no baseline run).
Aggregate diff coverage: 94% (2370 of 2516 measurable added lines).
Head 92.3% (3002 of 3253 lines)
20 of 58 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/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/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 candidateThe test run changed these tracked files; they were restored afterwards.
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversionFiles 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.
58 files: 45 code · 13 docs. Click to expand.
--- a/Halo Family/Halo Family/ChildOverviewView.swift+++ 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 }+ }+}
--- a/Halo Family/Halo Family/ConnectionDetailView.swift+++ b/Halo Family/Halo Family/ConnectionDetailView.swift@@ -0,0 +1,221 @@+import Combine+import CoreData+import SwiftUI++struct ConnectionDetailView: View {+ let repository: FamilyRepository+ let familyID: NSManagedObjectID+ let connection: GraphRow+ @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 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)+ }+ }+ }+ }+ } 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)+ }+ 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 }+ }+ }+ 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()) }+ }+ }+ }+ }+ 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)) }+ }+ Button("Add membership") {+ guard let contextID else { return }+ perform {+ _ = try repository.addMembership(connectionID: connection.id, contextID: contextID)+ self.contextID = nil+ }+ }+ .disabled(contextID == nil)+ }+ }+ .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()+ 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 }+ }+}
--- a/Halo Family/Halo Family/ConnectionStateEditor.swift+++ 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 }+ }+}
--- 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 @@ } } .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- }- }-}
--- a/Halo Family/Halo Family/ContextRoleEditor.swift+++ 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+}
--- a/Halo Family/Halo Family/ContextsView.swift+++ 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 }+ }+}
--- a/Halo Family/Halo Family/EventDetailView.swift+++ 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) }+ }))+ }+ }+}
--- a/Halo Family/Halo Family/EventsView.swift+++ 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 }+ }+}
--- a/Halo Family/Halo Family/FamilyKnowledgeViews.swift+++ b/Halo Family/Halo Family/FamilyKnowledgeViews.swift@@ -0,0 +1,363 @@+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 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") {+ 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 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 { 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")+ .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)+ 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 }+ }+}
--- a/Halo Family/Halo Family/FamilyManagerView.swift+++ 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 }+ }+}
--- a/Halo Family/Halo Family/FamilyReviewView.swift+++ b/Halo Family/Halo Family/FamilyReviewView.swift@@ -0,0 +1,69 @@+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 failure: String?+ @State private var loaded = false++ 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 {+ ContentUnavailableView("All caught up", systemImage: "checkmark.circle",+ description: Text("New captures and different relationship accounts appear here."))+ }+ 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) }+ }+ }+ }+ }+ }+ }+ .navigationTitle("Review")+ .task { reload() }+ .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+ .receive(on: DispatchQueue.main)) { _ in reload() }+ }++ private func reload() {+ do {+ let refreshedPeople = try repository.people(in: familyID, needsReview: true)+ let refreshedConnections = try repository.reviewConnections(in: familyID)+ people = refreshedPeople+ connections = refreshedConnections+ loaded = true+ failure = nil+ } catch { failure = error.localizedDescription }+ }+}
--- a/Halo Family/Halo Family/FamilySharingView.swift+++ 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
--- a/Halo Family/Halo Family/FamilyWorkspaceView.swift+++ 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)+ }+ }+}
--- a/Halo Family/Halo Family/FormComponents.swift+++ 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
--- 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()
--- a/Halo Family/Halo Family/PeopleView.swift+++ b/Halo Family/Halo Family/PeopleView.swift@@ -0,0 +1,172 @@+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)+ }+ }+ .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] = []++ var body: some View {+ MemoryForm {+ 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) } }+ }+ }+ }+ 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)+ }+ 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 {+ Button("Sensitive details") { perform { sensitive = try repository.sensitiveDetails(personID); editingSensitive = true } }+ } label: { Image(systemName: "ellipsis") }+ }+ .sheet(isPresented: $editingSensitive, onDismiss: { perform {} }, content: {+ if let sensitive { SensitiveDetailsView(repository: repository, personID: personID, initial: sensitive) }+ })+ .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)+ 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 ?? "") }+ }+}
--- 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,105 @@ } 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 {+ 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 {+ 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)+ guard let family = owner.value(forKey: "familySpace") as? NSManagedObject,+ let store = family.objectID.persistentStore, store == ownerID.persistentStore else { throw GraphError.differentFamily }+ 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 } } }
--- a/Halo Family/Halo Family/Persistence/ConnectionStateRepository.swift+++ 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+ }+}
--- a/Halo Family/Halo Family/Persistence/EventMemoryRepository.swift+++ 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) }+ }+}
--- a/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift+++ b/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift@@ -0,0 +1,293 @@+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+}++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) throws -> [FamilyFactRow] {+ try ["PersonRelationship", "RelationshipAssertion"].flatMap { entity in+ let request = NSFetchRequest<NSManagedObject>(entityName: entity)+ request.predicate = NSPredicate(format: "source == %@ OR target == %@", personID, personID)+ 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)+ }+ }+ }++ 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+ }+ }+}
--- a/Halo Family/Halo Family/Persistence/FamilyRepository.swift+++ b/Halo Family/Halo Family/Persistence/FamilyRepository.swift@@ -12,6 +12,18 @@ 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 @@ 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." } } }@@ -42,8 +66,16 @@ } /// 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"))+ }+ return try rows(entity: "Connection", nameKey: "person.displayName",+ predicate: NSCompoundPredicate(andPredicateWithSubpredicates: predicates)) } func createFamily(name: String) throws -> NSManagedObjectID {@@ -96,16 +128,26 @@ } } - 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 +156,32 @@ } } - 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 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 +201,7 @@ 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
--- a/Halo Family/Halo Family/Persistence/FamilySharing.swift+++ 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+ }+}
--- 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>HaloModelV5.xcdatamodel</string> </dict> </plist>
--- a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contents+++ 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>
--- a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contents+++ 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>
--- a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contents+++ 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>
--- a/Halo Family/Halo Family/Persistence/ImageImport.swift+++ 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)"+ }+}
--- a/Halo Family/Halo Family/Persistence/KinshipQueries.swift+++ b/Halo Family/Halo Family/Persistence/KinshipQueries.swift@@ -0,0 +1,79 @@+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")+ request.predicate = NSPredicate(format: "familySpace == %@ AND (startedAt == nil OR startedAt <= %@) " ++ "AND (endedAt == nil OR endedAt > %@)",+ family, date as NSDate, date as NSDate)+ 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+ }++}
--- a/Halo Family/Halo Family/Persistence/OriginRepository.swift+++ 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: [])+ }++ private 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 ?? "")+ }+ }++ private 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)]+ }++ private 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+ }+}
--- a/Halo Family/Halo Family/Persistence/PersistenceStack.swift+++ b/Halo Family/Halo Family/Persistence/PersistenceStack.swift@@ -148,7 +148,7 @@ container.viewContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType) } - static func loadModel(version: String = "HaloModelV2") throws -> NSManagedObjectModel {+ static func loadModel(version: String = "HaloModelV5") throws -> NSManagedObjectModel { #if SWIFT_PACKAGE let bundle = Bundle.module #else
--- a/Halo Family/Halo Family/Persistence/RelationshipMutations.swift+++ b/Halo Family/Halo Family/Persistence/RelationshipMutations.swift@@ -0,0 +1,180 @@+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)+ 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 }+ }+}
--- a/Halo Family/Halo Family/Persistence/RelationshipQueries.swift+++ b/Halo Family/Halo Family/Persistence/RelationshipQueries.swift@@ -0,0 +1,186 @@+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 {+ predicates.append(NSPredicate(format: "archivedAt == nil AND mergedInto == nil"))+ 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] {+ try rows(entity: "Connection", nameKey: "child.person.displayName", predicate: 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: " › ")+ }+}
--- a/Halo Family/Halo Family/Persistence/ReviewRepository.swift+++ b/Halo Family/Halo Family/Persistence/ReviewRepository.swift@@ -0,0 +1,35 @@+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")+ request.predicate = 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)+ }+ }+}
--- a/Halo Family/Halo Family/Persistence/SyntheticLaunch.swift+++ 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+ }+}
--- a/Halo Family/Halo Family/PhotoAssetViews.swift+++ 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)+ }+}
--- a/Halo Family/Halo Family/ShareInvitations.swift+++ 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
--- a/Halo Family/Halo Family/TemporalConflictReview.swift+++ 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)+ }+}
--- 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>
--- a/Makefile+++ b/Makefile@@ -9,6 +9,7 @@ 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 @@ .PHONY: test test:- swift test --scratch-path "$(DERIVED_DATA)/swift-tests"+ swift test --scratch-path "$(DERIVED_DATA)/swift-tests" $(TEST_FLAGS)
--- a/Tests/HaloPersistenceTests/ApprovedDefaultsTests.swift+++ 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)+ }+ }+}
--- a/Tests/HaloPersistenceTests/DefaultsMigrationHistoryTests.swift+++ 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)+ }+ }+}
--- a/Tests/HaloPersistenceTests/FamilyMemoryTests.swift+++ 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+ }+}
--- a/Tests/HaloPersistenceTests/GraphMigrationHistoryTests.swift+++ 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+ }+}
--- a/Tests/HaloPersistenceTests/MemoryMigrationTests.swift+++ 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)+ }+}
--- a/Tests/HaloPersistenceTests/RelationshipGraphTests.swift+++ 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)+ }+}
--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,33 @@ ## [Unreleased] ### Added++- 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.@@ -22,6 +49,18 @@ ### Changed +- 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.
--- 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 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,46 @@ 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.+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. -This is temporary navigation for exercising the data layer. The app now opens+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. Person merge is still being implemented.++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 +97,34 @@ 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. -Share invitations/acceptance, Contexts, origins and Events remain to implement.+Model V5 preserves V1–V4 for migration. 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.+ See the [acceptance report](docs/halo_family_design_pack/10-initial-implementation-results.md) for current evidence and verification limits.
--- a/docs/halo_family_design_pack/00-design-document.md+++ b/docs/halo_family_design_pack/00-design-document.md@@ -199,7 +199,7 @@ ### 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 @@ 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 @@ 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. ---
--- 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 @@ 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 @@ - 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 @@ 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 @@ - 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.--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).+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. 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 @@ - 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 @@ 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 @@ - 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 @@ 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 @@ - 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 @@ - note: String? ``` -Candidate primitive kinds:+Primitive kinds: ```text parentOf@@ -357,7 +374,7 @@ guardianOf ``` -Possible nature:+Optional nature: ```text biological@@ -375,7 +392,7 @@ ### 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 @@ ### 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 @@ ### 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 @@ ### 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 @@ - id: UUID - event: Event - person: Person-- role: EventRole?+- roles: Set<String> // multiple custom roles - invitationState: InvitationState? - attendanceState: AttendanceState? - note: String?@@ -588,7 +605,7 @@ ```text considering-planned+intendToInvite invited accepted declined@@ -614,7 +631,7 @@ ### 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 @@ 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 @@ ### 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 @@ - 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 @@ ### 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 @@ - 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 @@ 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 @@ ## 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.
--- a/docs/halo_family_design_pack/02-technical-architecture.md+++ b/docs/halo_family_design_pack/02-technical-architecture.md@@ -258,7 +258,7 @@ 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.
--- 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+**Updated:** 2026-10-07 UTC -Only unresolved decisions belong here.+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 -## 1. Production hardening+- 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. -### 1.1 No-iCloud-account lifecycle+## Remaining validation/release gates -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.+- 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.
--- a/docs/halo_family_design_pack/04-build-plan.md+++ b/docs/halo_family_design_pack/04-build-plan.md@@ -1,6 +1,68 @@ # Build Plan — Halo Family -**Status:** Architecture spike complete; persistence foundation implemented in part+**Status:** Full application implementation in progress; release gates remain 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 +171,7 @@ - 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.
--- 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 @@ - 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 @@ - 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 @@ - 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 @@ ## 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.
--- 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 @@ 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 @@ 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 |+| 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 | -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.+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
--- a/docs/halo_family_design_pack/10-initial-implementation-results.md+++ b/docs/halo_family_design_pack/10-initial-implementation-results.md@@ -1,4 +1,171 @@ # Implementation evidence++## 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
--- a/docs/halo_family_design_pack/CHANGELOG.md+++ b/docs/halo_family_design_pack/CHANGELOG.md@@ -1,4 +1,24 @@ # Halo Family — Pack Changes++## 7 October 2026 UTC++- 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
--- 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
--- a/docs/halo_family_design_pack/decision_log.md+++ b/docs/halo_family_design_pack/decision_log.md@@ -0,0 +1,99 @@+# 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. |++## 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.
Merge/undo, likely duplicates, Contacts, backup/import, widget/App Intent UX, seeded editable Context categories, richer search, Person-level Context roles and lifecycle hardening are pending.
Native UI and OS file/photo/sharing flows, real account/share lifecycle, production schema promotion and two-account eventual delivery have not been run. No physical installation, live CloudKit writes, main merge or push occurred.