Halo Family publication head 9445a27 feature commits 15 tests 148 / 17 suites runtime 7.923 seconds lint 0 / 89 focused native 1 pass / exit 0

Pre-push review: Halo Family final branch

Approved source passes 148 synthetic tests, both Debug builds and one focused native case. All source review lenses are clear; draft publication retains broader native/live acceptance gates.

At a glance

  • Application source covers approved phases 1–7 and 9 using SwiftUI/Core Data, with ordinary archive/restore, explicit history and stable identities.

  • Final review retains first membership end dates, batches family-root checks without caching permissions, and bounds file-provider reads.

  • Reachable Git history and the supplied Markdown-only archive contain no detected credential patterns or private-store/export artifacts. Tests use isolated synthetic fixtures.

Verdict

Ready for draft publication

The final separate-header tree passes 148 synthetic tests with zero failures/errors/skips, strict lint 0/89 and sequential iOS Simulator/macOS Debug builds with clean metadata/embedding. Tests/builds ran on recorded dirty 3919848; every tracked file hash matches committed ed6991f. The user published main; verified base 8c5262f. Four full review lenses and scoped follow-ups are clear. Focused native evidence remains bounded as stated below.

Review findings

5 raised · 5 fixed · 0 skipped

Jump to findings →

Tests

Pass rate: 100% (148 of 148)

New tests: 134

Diff coverage: 93% (6588 of 7077 added lines)

Jump to tests →

Commits

Three-level explanation

What changed

Halo Family now provides places to capture and remember children’s people, first meetings, later Contexts, family knowledge and Events. Names can be enriched later; archive/restore retains the record and its history.

Why it matters

The same Person can appear in several children’s relationships without becoming separate identities. A later class membership stays separate from where someone was first met. Explicit merge and undo keep parents’ entered accounts visible.

Key concepts

A FamilySpace owns the records. Account and device-only libraries have separate storage. Optional Contacts links stay on one device; a backup contains Halo records and assets, without those Contacts identifiers.

Implementation

FamilyRepository provides guarded MainActor queries and transactional writes. Core Data V6 retains V1–V5 migration models, private/shared stores, persistent history and externally stored asset payloads. The host mirrors with CloudKit; widget/intent roles read or write local stores through scoped typed references.

Trade-offs

Ordinary removal archives while retaining IDs, origins, roles, membership and assets. Merge previews explicitly choose fields and retained histories; guarded undo validates the current graph. Account/save checks reject locked, denied, ambiguous or stale references.

The final array read helper keeps type, coordinator, deletion and permission checks for each object; its root-uniqueness cache exists only inside a synchronous batch. Native imports read at most the attachment limit plus one byte through a single handle.

Boundaries

Store grants use family UUID plus private/shared qualification. Batched read uniqueness cannot survive a call or replace per-record permission checks. Background mutations retain their original scope and recheck permission at the local save boundary; this process-local serialization does not prove live framework convergence.

Backups bound archive/manifest/record/payload sizes, preserve original identities only when absent, and remap explicit copies. Legacy unsupported Person attributes reject before mutation; deleted rows recover committed ownership during guarded undo. Native intent type IDs and SDK APIs compile/extract at ed6991f, while execution and authentication remain separate evidence.

Completeness assessment

Approved source covers phases 1–7/9. Phase 8 requires representative data; Phase 10 is v2. Phase 11 still requires native/account/storage/schema acceptance; history retention is approved until safe pruning, and permanent deletion remains conditional release scope. The current 148-case tree passes unit/domain tests, strict lint and both Debug builds. Historical 146-case evidence remains separate; native/live acceptance is bounded below.

Important changes — detailed

Relationship workspace retains identities and distinct histories

Halo Family/Halo Family/Persistence/RelationshipMutations.swift

Why it matters. Capture, membership and first-meeting memory remain coherent across children.

What to look at. FamilyRepository mutations and origin/state repositories

Takeaway. Model identity and historical associations independently from current UI membership.
Rationale. Approved design separates Person, ChildProfile, Connection and ConnectionOrigin.

Account access qualifies families by store

Halo Family/Halo Family/Persistence/AccessPermissions.swift

Why it matters. A grant for one store cannot authorize a same-UUID root in another store.

What to look at. StoreAccess.identity; FamilyRepository.readable

Takeaway. Use scoped keys and validate each record even inside a query batch.
Rationale. Approved account/access isolation; final regression includes equal UUIDs, denial, ambiguity and foreign IDs.

Membership closure preserves an earlier end date

Halo Family/Halo Family/Persistence/RelationshipMutations.swift

Why it matters. Stale actions cannot overwrite a recorded historical end.

What to look at. endMembership(_:at:)

Takeaway. Recheck an active-state precondition inside the transaction.
Rationale. Same stale-boundary rule used by group memberships.

Imported files stay bounded as provider contents change

Halo Family/Halo Family/PhotoAssetViews.swift

Why it matters. Mutable size metadata cannot authorize an arbitrarily large read/map.

What to look at. ImportedFile.read

Takeaway. Bound actual bytes through an open handle and retain cleanup/cancellation.
Rationale. Approved attachment limit and native resource hardening.

Native extension capture uses stable scoped types

Halo Family/SharedIntents/CaptureIntents.swift

Why it matters. Widget and Shortcut source preserve authentication and current family permissions.

What to look at. RememberPersonIntent; ChildCaptureConfiguration

Takeaway. Build/extraction evidence and actual native behavior are separate gates.
Rationale. Approved Phase 9 reversible native capture defaults.

Evidence and smallest acceptance plan distinguish safe checks

docs/halo_family_design_pack/10-initial-implementation-results.md

Why it matters. Keep executed current gates separate from historical checkpoints and bounded native/live acceptance.

What to look at. Final publication review corrections; synthetic/native acceptance plan

Takeaway. Bind each test/build claim to its exact source and each native action to its actual isolation.
Rationale. Shared Mac scheduling and no-live-data restrictions.

Key decisions

Preserve existing history

All prior commits remain intact. Initial whole-history review covered the then-empty remote; this publication diff uses verified merge base 8 c 5262 f against user-published origin/main.

Keep native isolation explicit

Use only a fresh signed-out simulator and an owned Debug synthetic-store directory. Do not configure Halo widgets, open production account/group stores, use native Contacts/Photos, or cold-launch URLs without an independently isolated fixture.

Keep library navigation clear

Actual synthetic execution showed the library menu intercepting bottom tabs, then a top inset overlapping collapsed titles. Place libraryControls and the flexible workspace as separate root VStack children. Library actions, account observers and capture guards are retained.

Review findings

SeverityAreaFindingResolution
majorMembership stale writeA stale close action could overwrite a recorded end date.Reject ended memberships inside the write transaction; preserve first date/IDs in a new regression.
minorState-list query repetitionFamily-root duplicate checks repeated for every Connection.Central synchronous array read helper checks root uniqueness once per family/store and permissions for every record.
majorFile-provider resource boundA whole-file read/map could exceed the limit before rejection after metadata changed.One bounded FileHandle reads at most 20 MB plus one byte, with cancellation and cleanup.
minorHistorical README evidenceOne older sentence said current additions remained outside executed gates.Bind historical 146 pass to f7a6afd and current 148 declarations to pending verification.
majoriPhone tab navigationBottom library menu intercepted workspace tab taps during synthetic native execution.Render libraryControls and flexible workspace as separate root VStack children. Native geometry, navigation, editing and archive/restore assertions pass.

Tests

Source: local run at 2026-10-07T07:57:26.767537+00:00 · snapshot 39198482188582bcb0856ee3326939528e6fb56b (dirty working tree)

Baseline: none

Execution: passed · JUnit: 1 file · Coverage: 1 file · Baseline: absent

Coverage scope: as the project configures it

Totals: 148 passed · 0 failed · 0 skipped · 0 errored · 0 flaky

New and removed tests

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

Diff coverage

FileAdded linesCoveredDiff coverage
.swiftlint.yml2—no coverage data
CHANGELOG.md122—no coverage data
Halo Family/Halo Family.xcodeproj/project.pbxproj186—no coverage data
Halo Family/Halo Family/AppleContactsView.swift189—no coverage data
Halo Family/Halo Family/ArchiveControls.swift57—no coverage data
Halo Family/Halo Family/ChildOverviewView.swift162—no coverage data
Halo Family/Halo Family/ConnectionDetailView.swift231—no coverage data
Halo Family/Halo Family/ConnectionStateEditor.swift157—no coverage data
Halo Family/Halo Family/ContentView.swift117—no coverage data
Halo Family/Halo Family/ContextCategoryViews.swift132—no coverage data
Halo Family/Halo Family/ContextRoleEditor.swift90—no coverage data
Halo Family/Halo Family/ContextsView.swift170—no coverage data
Halo Family/Halo Family/EventDetailView.swift355—no coverage data
Halo Family/Halo Family/EventsView.swift63—no coverage data
Halo Family/Halo Family/FamilyBackupView.swift138—no coverage data
Halo Family/Halo Family/FamilyKnowledgeViews.swift385—no coverage data
Halo Family/Halo Family/FamilyManagerView.swift109—no coverage data
Halo Family/Halo Family/FamilyReviewView.swift111—no coverage data
Halo Family/Halo Family/FamilySharingView.swift104—no coverage data
Halo Family/Halo Family/FamilyWorkspaceView.swift141—no coverage data
Halo Family/Halo Family/FormComponents.swift81—no coverage data
Halo Family/Halo Family/Halo Family.entitlements2—no coverage data
Halo Family/Halo Family/MergeConflictReviewView.swift78—no coverage data
Halo Family/Halo Family/MyApp.swift6—no coverage data
Halo Family/Halo Family/NativeContactPicker.swift68—no coverage data
Halo Family/Halo Family/PeopleView.swift257—no coverage data
Halo Family/Halo Family/Persistence/AccessPermissions.swift21011964%
Halo Family/Halo Family/Persistence/AccountScope.swift1538079%
Halo Family/Halo Family/Persistence/ArchiveRepository.swift563489%
Halo Family/Halo Family/Persistence/AssetRepository.swift13012098%
Halo Family/Halo Family/Persistence/BackupArchive.swift22416292%
Halo Family/Halo Family/Persistence/BackupCancellation.swift14686%
Halo Family/Halo Family/Persistence/BackupHistory.swift13111098%
Halo Family/Halo Family/Persistence/BackupRepository.swift29525298%
Halo Family/Halo Family/Persistence/BackupStaging.swift2800%
Halo Family/Halo Family/Persistence/BackupValidation.swift16112187%
Halo Family/Halo Family/Persistence/CaptureReference.swift684295%
Halo Family/Halo Family/Persistence/CaptureRepository.swift876490%
Halo Family/Halo Family/Persistence/CloudAccessFailure.swift1611100%
Halo Family/Halo Family/Persistence/ConnectionStateRepository.swift20514299%
Halo Family/Halo Family/Persistence/ContactIdentity.swift2715100%
Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift885989%
Halo Family/Halo Family/Persistence/EventMemoryRepository.swift24916890%
Halo Family/Halo Family/Persistence/ExtensionAccess.swift3822100%
Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift30222599%
Halo Family/Halo Family/Persistence/FamilyRepository.swift13610990%
Halo Family/Halo Family/Persistence/FamilySharing.swift1051824%
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversion1—no coverage data
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contents100—no coverage data
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contents140—no coverage data
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contents282—no coverage data
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV6.xcdatamodel/contents324—no coverage data
Halo Family/Halo Family/Persistence/HistoryProcessor.swift54100%
Halo Family/Halo Family/Persistence/ImageImport.swift843872%
Halo Family/Halo Family/Persistence/KinshipQueries.swift8268100%
Halo Family/Halo Family/Persistence/LocalContactLinks.swift955487%
Halo Family/Halo Family/Persistence/MergeAccountReview.swift126104100%
Halo Family/Halo Family/Persistence/MergeConflictRecovery.swift184155100%
Halo Family/Halo Family/Persistence/MergeSnapshot.swift18613991%
Halo Family/Halo Family/Persistence/OriginRepository.swift26721799%
Halo Family/Halo Family/Persistence/PeopleSearch.swift887199%
Halo Family/Halo Family/Persistence/PersistenceStack.swift1974827%
Halo Family/Halo Family/Persistence/PersonMergeHistory.swift1048086%
Halo Family/Halo Family/Persistence/PersonMergePreview.swift157145100%
Halo Family/Halo Family/Persistence/PersonMergeRepository.swift19317296%
Halo Family/Halo Family/Persistence/PersonMergeTypes.swift114737%
Halo Family/Halo Family/Persistence/PortableGraph.swift1066897%
Halo Family/Halo Family/Persistence/RelationshipMutations.swift20317298%
Halo Family/Halo Family/Persistence/RelationshipQueries.swift22313196%
Halo Family/Halo Family/Persistence/ReviewRepository.swift3723100%
Halo Family/Halo Family/Persistence/StoreConfiguration.swift900%
Halo Family/Halo Family/Persistence/SyntheticLaunch.swift1500%
Halo Family/Halo Family/PersonMergeHistoryView.swift124—no coverage data
Halo Family/Halo Family/PersonMergeView.swift216—no coverage data
Halo Family/Halo Family/PhotoAssetViews.swift192—no coverage data
Halo Family/Halo Family/ShareInvitations.swift69—no coverage data
Halo Family/Halo Family/TemporalConflictReview.swift41—no coverage data
Halo Family/Halo Family/WidgetCaptureSheet.swift93—no coverage data
Halo Family/Halo-Family-Info.plist13—no coverage data
Halo Family/HaloFamilyWidgets-Info.plist11—no coverage data
Halo Family/HaloFamilyWidgets.entitlements14—no coverage data
Halo Family/HaloWidgets/ChildCaptureWidget.swift96—no coverage data
Halo Family/SharedIntents/CaptureCatalog.swift75—no coverage data
Halo Family/SharedIntents/CaptureIntents.swift99—no coverage data
Makefile2—no coverage data
README.md153—no coverage data
Tests/HaloPersistenceTests/AccountAccessTests.swift311288100%
Tests/HaloPersistenceTests/ApprovedDefaultsTests.swift327301100%
Tests/HaloPersistenceTests/ArchiveTests.swift161146100%
Tests/HaloPersistenceTests/CaptureTests.swift221201100%
Tests/HaloPersistenceTests/ContextCategoryTests.swift9582100%
Tests/HaloPersistenceTests/DefaultsMigrationHistoryTests.swift10799100%
Tests/HaloPersistenceTests/FamilyBackupTests.swift344320100%
Tests/HaloPersistenceTests/FamilyMemoryTests.swift419382100%
Tests/HaloPersistenceTests/GraphMigrationHistoryTests.swift9485100%
Tests/HaloPersistenceTests/LocalContactLinksTests.swift114101100%
Tests/HaloPersistenceTests/MemoryMigrationTests.swift7466100%
Tests/HaloPersistenceTests/PeopleSearchTests.swift167152100%
Tests/HaloPersistenceTests/PersonMergeTests.swift599560100%
Tests/HaloPersistenceTests/RelationshipGraphTests.swift258230100%
docs/halo_family_design_pack/00-design-document.md5—no coverage data
docs/halo_family_design_pack/01-data-model.md66—no coverage data
docs/halo_family_design_pack/02-technical-architecture.md1—no coverage data
docs/halo_family_design_pack/03-open-questions.md28—no coverage data
docs/halo_family_design_pack/04-build-plan.md214—no coverage data
docs/halo_family_design_pack/06-attachment-photo-storage.md16—no coverage data
docs/halo_family_design_pack/09-implementation-handoff.md25—no coverage data
docs/halo_family_design_pack/10-initial-implementation-results.md648—no coverage data
docs/halo_family_design_pack/CHANGELOG.md67—no coverage data
docs/halo_family_design_pack/README.md12—no coverage data
docs/halo_family_design_pack/decision_log.md104—no coverage data

Aggregate diff coverage: 93% (6588 of 7077 measurable added lines).

Overall coverage

Head 92.5% (7207 of 7789 lines)

55 of 111 changed files matched coverage data.

Blast radius

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

Dependents none found Changed Dependencies none found . Halo Family Halo Family/Halo Family … Family/Halo Family.xcodeproj …amily/Halo Family/Persistence …stence/HaloModel.xcdatamodeld …odeld/HaloModelV3.xcdatamodel …odeld/HaloModelV4.xcdatamodel …odeld/HaloModelV5.xcdatamodel …odeld/HaloModelV6.xcdatamodel Halo Family/HaloWidgets Halo Family/SharedIntents Tests/HaloPersistenceTests MakefileMakefile Halo Family/Halo-Family-Info.plist…Family/Halo-Family-Info.plist Halo Family/HaloFamilyWidgets-Info.plist…/HaloFamilyWidgets-Info.plist Halo Family/HaloFamilyWidgets.entitlements…aloFamilyWidgets.entitlements Halo Family/Halo Family/AppleContactsView.swift…amily/AppleContactsView.swift Halo Family/Halo Family/ArchiveControls.swift… Family/ArchiveControls.swift Halo Family/Halo Family/ChildOverviewView.swift…amily/ChildOverviewView.swift Halo Family/Halo Family/ConnectionDetailView.swift…ly/ConnectionDetailView.swift Halo Family/Halo Family/ConnectionStateEditor.swift…y/ConnectionStateEditor.swift Halo Family/Halo Family/ContentView.swift…Halo Family/ContentView.swift Halo Family/Halo Family/ContextCategoryViews.swift…ly/ContextCategoryViews.swift Halo Family/Halo Family/ContextRoleEditor.swift…amily/ContextRoleEditor.swift Halo Family/Halo Family/ContextsView.swift…alo Family/ContextsView.swift Halo Family/Halo Family/EventDetailView.swift… Family/EventDetailView.swift Halo Family/Halo Family/EventsView.swift…/Halo Family/EventsView.swift Halo Family/Halo Family/FamilyBackupView.swift…Family/FamilyBackupView.swift Halo Family/Halo Family/FamilyKnowledgeViews.swift…ly/FamilyKnowledgeViews.swift Halo Family/Halo Family/FamilyManagerView.swift…amily/FamilyManagerView.swift Halo Family/Halo Family/FamilyReviewView.swift…Family/FamilyReviewView.swift Halo Family/Halo Family/FamilySharingView.swift…amily/FamilySharingView.swift Halo Family/Halo Family/FamilyWorkspaceView.swift…ily/FamilyWorkspaceView.swift Halo Family/Halo Family/FormComponents.swift…o Family/FormComponents.swift Halo Family/Halo Family/Halo Family.entitlements…mily/Halo Family.entitlements Halo Family/Halo Family/MergeConflictReviewView.swift…MergeConflictReviewView.swift Halo Family/Halo Family/MyApp.swift…amily/Halo Family/MyApp.swift Halo Family/Halo Family/NativeContactPicker.swift…ily/NativeContactPicker.swift Halo Family/Halo Family/PeopleView.swift…/Halo Family/PeopleView.swift Halo Family/Halo Family/PersonMergeHistoryView.swift…/PersonMergeHistoryView.swift Halo Family/Halo Family/PersonMergeView.swift… Family/PersonMergeView.swift Halo Family/Halo Family/PhotoAssetViews.swift… Family/PhotoAssetViews.swift Halo Family/Halo Family/ShareInvitations.swift…Family/ShareInvitations.swift Halo Family/Halo Family/TemporalConflictReview.swift…/TemporalConflictReview.swift Halo Family/Halo Family/WidgetCaptureSheet.swift…mily/WidgetCaptureSheet.swift Halo Family/Halo Family.xcodeproj/project.pbxproj…ily.xcodeproj/project.pbxproj Halo Family/Halo Family/Persistence/AccessPermissions.swift…tence/AccessPermissions.swift Halo Family/Halo Family/Persistence/AccountScope.swift…ersistence/AccountScope.swift Halo Family/Halo Family/Persistence/ArchiveRepository.swift…tence/ArchiveRepository.swift Halo Family/Halo Family/Persistence/AssetRepository.swift…istence/AssetRepository.swift Halo Family/Halo Family/Persistence/BackupArchive.swift…rsistence/BackupArchive.swift Halo Family/Halo Family/Persistence/BackupCancellation.swift…ence/BackupCancellation.swift Halo Family/Halo Family/Persistence/BackupHistory.swift…rsistence/BackupHistory.swift Halo Family/Halo Family/Persistence/BackupRepository.swift…stence/BackupRepository.swift Halo Family/Halo Family/Persistence/BackupStaging.swift…rsistence/BackupStaging.swift Halo Family/Halo Family/Persistence/BackupValidation.swift…stence/BackupValidation.swift Halo Family/Halo Family/Persistence/CaptureReference.swift…stence/CaptureReference.swift Halo Family/Halo Family/Persistence/CaptureRepository.swift…tence/CaptureRepository.swift Halo Family/Halo Family/Persistence/CloudAccessFailure.swift…ence/CloudAccessFailure.swift Halo Family/Halo Family/Persistence/ConnectionStateRepository.swift…nnectionStateRepository.swift Halo Family/Halo Family/Persistence/ContactIdentity.swift…istence/ContactIdentity.swift Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift…ntextCategoryRepository.swift Halo Family/Halo Family/Persistence/EventMemoryRepository.swift…e/EventMemoryRepository.swift Halo Family/Halo Family/Persistence/ExtensionAccess.swift…istence/ExtensionAccess.swift Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift…/FamilyMemoryRepository.swift Halo Family/Halo Family/Persistence/FamilyRepository.swift…stence/FamilyRepository.swift Halo Family/Halo Family/Persistence/FamilySharing.swift…rsistence/FamilySharing.swift Halo Family/Halo Family/Persistence/HistoryProcessor.swift…stence/HistoryProcessor.swift Halo Family/Halo Family/Persistence/ImageImport.swift…Persistence/ImageImport.swift Halo Family/Halo Family/Persistence/KinshipQueries.swift…sistence/KinshipQueries.swift Halo Family/Halo Family/Persistence/LocalContactLinks.swift…tence/LocalContactLinks.swift Halo Family/Halo Family/Persistence/MergeAccountReview.swift…ence/MergeAccountReview.swift Halo Family/Halo Family/Persistence/MergeConflictRecovery.swift…e/MergeConflictRecovery.swift Halo Family/Halo Family/Persistence/MergeSnapshot.swift…rsistence/MergeSnapshot.swift Halo Family/Halo Family/Persistence/OriginRepository.swift…stence/OriginRepository.swift Halo Family/Halo Family/Persistence/PeopleSearch.swift…ersistence/PeopleSearch.swift Halo Family/Halo Family/Persistence/PersistenceStack.swift…stence/PersistenceStack.swift Halo Family/Halo Family/Persistence/PersonMergeHistory.swift…ence/PersonMergeHistory.swift Halo Family/Halo Family/Persistence/PersonMergePreview.swift…ence/PersonMergePreview.swift Halo Family/Halo Family/Persistence/PersonMergeRepository.swift…e/PersonMergeRepository.swift Halo Family/Halo Family/Persistence/PersonMergeTypes.swift…stence/PersonMergeTypes.swift Halo Family/Halo Family/Persistence/PortableGraph.swift…rsistence/PortableGraph.swift Halo Family/Halo Family/Persistence/RelationshipMutations.swift…e/RelationshipMutations.swift Halo Family/Halo Family/Persistence/RelationshipQueries.swift…nce/RelationshipQueries.swift Halo Family/Halo Family/Persistence/ReviewRepository.swift…stence/ReviewRepository.swift Halo Family/Halo Family/Persistence/StoreConfiguration.swift…ence/StoreConfiguration.swift Halo Family/Halo Family/Persistence/SyntheticLaunch.swift…istence/SyntheticLaunch.swift Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversion…cdatamodeld/.xccurrentversion Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contents…oModelV3.xcdatamodel/contents Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contents…oModelV4.xcdatamodel/contents Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contents…oModelV5.xcdatamodel/contents Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV6.xcdatamodel/contents…oModelV6.xcdatamodel/contents Halo Family/HaloWidgets/ChildCaptureWidget.swift…gets/ChildCaptureWidget.swift Halo Family/SharedIntents/CaptureCatalog.swift…dIntents/CaptureCatalog.swift Halo Family/SharedIntents/CaptureIntents.swift…dIntents/CaptureIntents.swift Tests/HaloPersistenceTests/AccountAccessTests.swift…ests/AccountAccessTests.swift Tests/HaloPersistenceTests/ApprovedDefaultsTests.swift…s/ApprovedDefaultsTests.swift Tests/HaloPersistenceTests/ArchiveTests.swift…tenceTests/ArchiveTests.swift Tests/HaloPersistenceTests/CaptureTests.swift…tenceTests/CaptureTests.swift Tests/HaloPersistenceTests/ContextCategoryTests.swift…ts/ContextCategoryTests.swift Tests/HaloPersistenceTests/DefaultsMigrationHistoryTests.swift…tsMigrationHistoryTests.swift Tests/HaloPersistenceTests/FamilyBackupTests.swift…Tests/FamilyBackupTests.swift Tests/HaloPersistenceTests/FamilyMemoryTests.swift…Tests/FamilyMemoryTests.swift Tests/HaloPersistenceTests/GraphMigrationHistoryTests.swift…phMigrationHistoryTests.swift Tests/HaloPersistenceTests/LocalContactLinksTests.swift…/LocalContactLinksTests.swift Tests/HaloPersistenceTests/MemoryMigrationTests.swift…ts/MemoryMigrationTests.swift Tests/HaloPersistenceTests/PeopleSearchTests.swift…Tests/PeopleSearchTests.swift Tests/HaloPersistenceTests/PersonMergeTests.swift…eTests/PersonMergeTests.swift Tests/HaloPersistenceTests/RelationshipGraphTests.swift…/RelationshipGraphTests.swift
addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

111 files: 98 code · 13 docs. Click to expand.

Code (98)

.swiftlint.yml Modified +2 / -0
diff --git a/.swiftlint.yml b/.swiftlint.ymlindex 895f02d..2746684 100644--- a/.swiftlint.yml+++ b/.swiftlint.yml@@ -3,6 +3,8 @@ # Paths to include included:   - Halo Family/Halo Family+  - Halo Family/SharedIntents+  - Halo Family/HaloWidgets   - Tests  # Paths to exclude
Halo Family/Halo Family.xcodeproj/project.pbxproj Modified +186 / -2
diff --git a/Halo Family/Halo Family.xcodeproj/project.pbxproj b/Halo Family/Halo Family.xcodeproj/project.pbxprojindex 69bdb28..6ad462e 100644--- a/Halo Family/Halo Family.xcodeproj/project.pbxproj	+++ b/Halo Family/Halo Family.xcodeproj/project.pbxproj	@@ -6,8 +6,35 @@ 	objectVersion = 90; 	objects = { +/* Begin PBXBuildFile section */+		A90000000000000000000001 /* HaloFamilyWidgets.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = A90000000000000000000002 /* HaloFamilyWidgets.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };+/* End PBXBuildFile section */++/* Begin PBXContainerItemProxy section */+		A90000000000000000000003 /* PBXContainerItemProxy */ = {+			isa = PBXContainerItemProxy;+			containerPortal = 000000000000000000000000 /* Project object */;+			proxyType = 1;+			remoteGlobalIDString = A90000000000000000000010;+			remoteInfo = HaloFamilyWidgets;+		};+/* End PBXContainerItemProxy section */++/* Begin PBXCopyFilesBuildPhase section */+		A90000000000000000000004 /* Embed App Extensions */ = {+			isa = PBXCopyFilesBuildPhase;+			dstPath = "";+			dstSubfolder = PlugIns;+			files = (+				A90000000000000000000001 /* HaloFamilyWidgets.appex in Embed App Extensions */,+			);+			name = "Embed App Extensions";+		};+/* End PBXCopyFilesBuildPhase section */+ /* Begin PBXFileReference section */ 		000000000000000000000120 /* Halo Family.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Halo Family.app"; sourceTree = BUILT_PRODUCTS_DIR; };+		A90000000000000000000002 /* HaloFamilyWidgets.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = HaloFamilyWidgets.appex; sourceTree = BUILT_PRODUCTS_DIR; }; 		D4E68C5730752C710095AE3C /* Halo-Family-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = "Halo-Family-Info.plist"; sourceTree = "<group>"; }; /* End PBXFileReference section */ @@ -17,6 +44,22 @@ 			path = "Halo Family"; 			sourceTree = "<group>"; 		};+		A90000000000000000000005 /* SharedIntents */ = {+			isa = PBXFileSystemSynchronizedRootGroup;+			path = SharedIntents;+			sourceTree = "<group>";+		};+		A90000000000000000000006 /* HaloWidgets */ = {+			isa = PBXFileSystemSynchronizedRootGroup;+			path = HaloWidgets;+			sourceTree = "<group>";+		};+		A90000000000000000000007 /* Extension Persistence */ = {+			isa = PBXFileSystemSynchronizedRootGroup;+			name = "Extension Persistence";+			path = "Halo Family/Persistence";+			sourceTree = "<group>";+		}; /* End PBXFileSystemSynchronizedRootGroup section */  /* Begin PBXFrameworksBuildPhase section */@@ -25,6 +68,11 @@ 			files = ( 			); 		};+		A90000000000000000000011 /* Frameworks */ = {+			isa = PBXFrameworksBuildPhase;+			files = (+			);+		}; /* End PBXFrameworksBuildPhase section */  /* Begin PBXGroup section */@@ -33,6 +81,9 @@ 			children = ( 				D4E68C5730752C710095AE3C /* Halo-Family-Info.plist */, 				000000000000000000000010 /* Halo Family */,+				A90000000000000000000005 /* SharedIntents */,+				A90000000000000000000006 /* HaloWidgets */,+				A90000000000000000000007 /* Extension Persistence */, 				000000000000000000000020 /* Products */, 			); 			sourceTree = "<group>";@@ -41,6 +92,7 @@ 			isa = PBXGroup; 			children = ( 				000000000000000000000120 /* Halo Family.app */,+				A90000000000000000000002 /* HaloFamilyWidgets.appex */, 			); 			name = Products; 			sourceTree = "<group>";@@ -55,17 +107,42 @@ 				000000000000000120000000 /* Sources */, 				000000000000000130000000 /* Frameworks */, 				000000000000000140000000 /* Resources */,+				A90000000000000000000004 /* Embed App Extensions */, 			); 			buildRules = ( 			);+			dependencies = (+				A90000000000000000000008 /* PBXTargetDependency */,+			); 			fileSystemSynchronizedGroups = ( 				000000000000000000000010 /* Halo Family */,+				A90000000000000000000005 /* SharedIntents */, 			); 			name = "Halo Family"; 			productName = MyApp; 			productReference = 000000000000000000000120 /* Halo Family.app */; 			productType = "com.apple.product-type.application"; 		};+		A90000000000000000000010 /* HaloFamilyWidgets */ = {+			isa = PBXNativeTarget;+			buildConfigurationList = A90000000000000000000014 /* Build configuration list for PBXNativeTarget "HaloFamilyWidgets" */;+			buildPhases = (+				A90000000000000000000012 /* Sources */,+				A90000000000000000000011 /* Frameworks */,+				A90000000000000000000013 /* Resources */,+			);+			buildRules = (+			);+			fileSystemSynchronizedGroups = (+				A90000000000000000000005 /* SharedIntents */,+				A90000000000000000000006 /* HaloWidgets */,+				A90000000000000000000007 /* Extension Persistence */,+			);+			name = HaloFamilyWidgets;+			productName = HaloFamilyWidgets;+			productReference = A90000000000000000000002 /* HaloFamilyWidgets.appex */;+			productType = "com.apple.product-type.app-extension";+		}; /* End PBXNativeTarget section */  /* Begin PBXProject section */@@ -96,6 +173,7 @@ 			projectRoot = ""; 			targets = ( 				000000000000000100000000 /* Halo Family */,+				A90000000000000000000010 /* HaloFamilyWidgets */, 			); 		}; /* End PBXProject section */@@ -106,6 +184,11 @@ 			files = ( 			); 		};+		A90000000000000000000013 /* Resources */ = {+			isa = PBXResourcesBuildPhase;+			files = (+			);+		}; /* End PBXResourcesBuildPhase section */  /* Begin PBXSourcesBuildPhase section */@@ -114,8 +197,21 @@ 			files = ( 			); 		};+		A90000000000000000000012 /* Sources */ = {+			isa = PBXSourcesBuildPhase;+			files = (+			);+		}; /* End PBXSourcesBuildPhase section */ +/* Begin PBXTargetDependency section */+		A90000000000000000000008 /* PBXTargetDependency */ = {+			isa = PBXTargetDependency;+			target = A90000000000000000000010 /* HaloFamilyWidgets */;+			targetProxy = A90000000000000000000003 /* PBXContainerItemProxy */;+		};+/* End PBXTargetDependency section */+ /* Begin XCBuildConfiguration section */ 		000000000000000011000000 /* Debug configuration for PBXProject "Halo Family" */ = { 			isa = XCBuildConfiguration;@@ -260,7 +356,7 @@ 				DEVELOPMENT_TEAM = V24684SCZN; 				ENABLE_APP_SANDBOX = YES; 				ENABLE_PREVIEWS = YES;-				ENABLE_USER_SELECTED_FILES = readonly;+				ENABLE_USER_SELECTED_FILES = readwrite; 				GENERATE_INFOPLIST_FILE = YES; 				INFOPLIST_FILE = "Halo-Family-Info.plist"; 				"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;@@ -301,7 +397,7 @@ 				DEVELOPMENT_TEAM = V24684SCZN; 				ENABLE_APP_SANDBOX = YES; 				ENABLE_PREVIEWS = YES;-				ENABLE_USER_SELECTED_FILES = readonly;+				ENABLE_USER_SELECTED_FILES = readwrite; 				GENERATE_INFOPLIST_FILE = YES; 				INFOPLIST_FILE = "Halo-Family-Info.plist"; 				"INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES;@@ -333,6 +429,86 @@ 			}; 			name = Release; 		};+		A90000000000000000000015 /* Debug configuration for PBXNativeTarget "HaloFamilyWidgets" */ = {+			isa = XCBuildConfiguration;+			buildSettings = {+				APPLICATION_EXTENSION_API_ONLY = YES;+				CODE_SIGN_ENTITLEMENTS = HaloFamilyWidgets.entitlements;+				CODE_SIGN_STYLE = Automatic;+				CURRENT_PROJECT_VERSION = 1;+				DEVELOPMENT_TEAM = V24684SCZN;+				ENABLE_APP_SANDBOX = YES;+				GENERATE_INFOPLIST_FILE = YES;+				INFOPLIST_FILE = "HaloFamilyWidgets-Info.plist";+				INFOPLIST_KEY_CFBundleDisplayName = "Halo Family";+				LD_RUNPATH_SEARCH_PATHS = (+					"$(inherited)",+					"@executable_path/Frameworks",+					"@executable_path/../../Frameworks",+				);+				"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = (+					"$(inherited)",+					"@executable_path/../Frameworks",+					"@executable_path/../../../../Frameworks",+				);+				MARKETING_VERSION = 1.0;+				PRODUCT_BUNDLE_IDENTIFIER = "me.nore.ig.halo-family.widgets";+				PRODUCT_NAME = "$(TARGET_NAME)";+				REGISTER_APP_GROUPS = YES;+				SDKROOT = auto;+				SKIP_INSTALL = YES;+				STRING_CATALOG_GENERATE_SYMBOLS = YES;+				SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx";+				SUPPORTS_MACCATALYST = NO;+				SWIFT_APPROACHABLE_CONCURRENCY = YES;+				SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;+				SWIFT_EMIT_LOC_STRINGS = YES;+				SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+				SWIFT_VERSION = 5.0;+				TARGETED_DEVICE_FAMILY = "1,2";+			};+			name = Debug;+		};+		A90000000000000000000016 /* Release configuration for PBXNativeTarget "HaloFamilyWidgets" */ = {+			isa = XCBuildConfiguration;+			buildSettings = {+				APPLICATION_EXTENSION_API_ONLY = YES;+				CODE_SIGN_ENTITLEMENTS = HaloFamilyWidgets.entitlements;+				CODE_SIGN_STYLE = Automatic;+				CURRENT_PROJECT_VERSION = 1;+				DEVELOPMENT_TEAM = V24684SCZN;+				ENABLE_APP_SANDBOX = YES;+				GENERATE_INFOPLIST_FILE = YES;+				INFOPLIST_FILE = "HaloFamilyWidgets-Info.plist";+				INFOPLIST_KEY_CFBundleDisplayName = "Halo Family";+				LD_RUNPATH_SEARCH_PATHS = (+					"$(inherited)",+					"@executable_path/Frameworks",+					"@executable_path/../../Frameworks",+				);+				"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = (+					"$(inherited)",+					"@executable_path/../Frameworks",+					"@executable_path/../../../../Frameworks",+				);+				MARKETING_VERSION = 1.0;+				PRODUCT_BUNDLE_IDENTIFIER = "me.nore.ig.halo-family.widgets";+				PRODUCT_NAME = "$(TARGET_NAME)";+				REGISTER_APP_GROUPS = YES;+				SDKROOT = auto;+				SKIP_INSTALL = YES;+				STRING_CATALOG_GENERATE_SYMBOLS = YES;+				SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx";+				SUPPORTS_MACCATALYST = NO;+				SWIFT_APPROACHABLE_CONCURRENCY = YES;+				SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor;+				SWIFT_EMIT_LOC_STRINGS = YES;+				SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+				SWIFT_VERSION = 5.0;+				TARGETED_DEVICE_FAMILY = "1,2";+			};+			name = Release;+		}; /* End XCBuildConfiguration section */  /* Begin XCConfigurationList section */@@ -352,6 +528,14 @@ 			); 			defaultConfigurationName = Release; 		};+		A90000000000000000000014 /* Build configuration list for PBXNativeTarget "HaloFamilyWidgets" */ = {+			isa = XCConfigurationList;+			buildConfigurations = (+				A90000000000000000000015 /* Debug configuration for PBXNativeTarget "HaloFamilyWidgets" */,+				A90000000000000000000016 /* Release configuration for PBXNativeTarget "HaloFamilyWidgets" */,+			);+			defaultConfigurationName = Release;+		}; /* End XCConfigurationList section */ 	}; 	rootObject = 000000000000000000000000 /* Project object */;
Halo Family/Halo Family/AppleContactsView.swift Added +189 / -0
diff --git a/Halo Family/Halo Family/AppleContactsView.swift b/Halo Family/Halo Family/AppleContactsView.swiftnew file mode 100644index 0000000..53c2abe--- /dev/null+++ b/Halo Family/Halo Family/AppleContactsView.swift	@@ -0,0 +1,189 @@+import Combine+import Contacts+import CoreData+import SwiftUI++struct AppleContactsView: View {+    let repository: FamilyRepository+    let personID: NSManagedObjectID+    @State private var links: [DeviceContactLink] = []+    @State private var picking = false+    @State private var creating = false+    @State private var name = ""+    @State private var failure: String?+    @State private var pendingContact: ContactSelection?+    @State private var linking = false+    @State private var reloadGeneration = 0++    var body: some View {+        MemoryForm {+            MemorySection("Apple Contacts") {+                Text("Optional links are saved only on this device. They do not change this person's identity " ++                     "or appear in another parent's address book or a family backup.")+                if !repository.stack.nativeContactsEnabled {+                    Text("Apple Contacts is disabled in this synthetic workspace.").foregroundStyle(.secondary)+                }+                if links.isEmpty { Text("No contact linked on this device.").foregroundStyle(.secondary) }+                ForEach(links) { link in+                    VStack(alignment: .leading, spacing: 8) {+                        Text(link.label ?? "Linked Apple Contact").font(.headline)+                        Text(link.createdAt.formatted(date: .abbreviated, time: .omitted)).font(.caption)+                        Button("Unlink on this device") { unlink(link) }.disabled(linking)+                    }+                }+                #if os(macOS)+                MacContactPickerButton { selected in save(selected) }+                    .disabled(linking || !repository.stack.nativeContactsEnabled)+                #else+                Button("Link an existing contact") { picking = true }+                    .disabled(linking || !repository.stack.nativeContactsEnabled)+                #endif+                Button("Create a new contact") { creating = true }+                    .disabled(pendingContact != nil || linking || !repository.stack.nativeContactsEnabled)+                if let pendingContact {+                    Text("The Apple Contact is available, but its Halo link has not been saved. " ++                         "Retry saves only the local link and does not create another contact.")+                    Button("Retry saving the link") { save(pendingContact) }.disabled(linking)+                    Button("Discard the pending link") { self.pendingContact = nil }.disabled(linking)+                }+                Text("Unlinking does not delete or edit an Apple Contact. Links retained during a Person merge " ++                     "can refer to several contacts; Halo does not merge those contacts.")+                    .font(.caption).foregroundStyle(.secondary)+            }+        }+        .navigationTitle("Apple Contacts")+        .task { await reload() }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in Task { await reload() } }+        .onReceive(NotificationCenter.default.publisher(for: .haloContactLinksDidChange)+            .receive(on: DispatchQueue.main)) { _ in Task { await reload() } }+        #if !os(macOS)+        .sheet(isPresented: $picking) {+            NativeContactPicker { selected in+                picking = false+                if let selected { save(selected) }+            }+        }+        #endif+        .sheet(isPresented: $creating) {+            CreateAppleContactView(initialName: name, allowed: repository.stack.nativeContactsEnabled) { selected in+                creating = false+                save(selected)+            }+        }+        .graphFailure($failure)+    }++    private func reload() async {+        reloadGeneration &+= 1+        let generation = reloadGeneration+        do {+            let identity = try repository.contactIdentity(personID)+            let store = try repository.stack.localContactLinks()+            let links = try await store.links(familyID: identity.familyID, personIDs: identity.aliases)+            // The record can merge while the local file operation yields.+            let current = try repository.contactIdentity(personID)+            guard generation == reloadGeneration else { return }+            guard current.personID == identity.personID, current.aliases == identity.aliases else { throw MergeError.changed }+            self.links = links; name = try repository.person(personID).name+        } catch { if generation == reloadGeneration { failure = error.localizedDescription } }+    }++    private func save(_ selected: ContactSelection) {+        guard !linking else { return }+        linking = true+        pendingContact = selected+        Task {+            defer { linking = false }+            do {+                let identity = try repository.contactIdentity(personID)+                try await repository.stack.localContactLinks().link(selected.identifier, label: selected.label,+                    familyID: identity.familyID, personID: identity.personID)+                pendingContact = nil+                await reload()+            } catch { failure = error.localizedDescription }+        }+    }++    private func unlink(_ link: DeviceContactLink) {+        guard !linking else { return }+        linking = true+        Task {+            defer { linking = false }+            do {+                let identity = try repository.contactIdentity(personID)+                guard identity.familyID == link.familyID, identity.aliases.contains(link.personID) else { throw MergeError.changed }+                try await repository.stack.localContactLinks().unlink(link)+                await reload()+            } catch { failure = error.localizedDescription }+        }+    }+}++private struct CreateAppleContactView: View {+    let completed: (ContactSelection) -> Void+    let allowed: Bool+    @State private var givenName = ""+    @State private var familyName = ""+    @State private var nickname: String+    @State private var saving = false+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    init(initialName: String, allowed: Bool, completed: @escaping (ContactSelection) -> Void) {+        self.completed = completed; self.allowed = allowed; _nickname = State(initialValue: initialName)+    }++    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("New Apple Contact") {+                    Text("The names entered here will be saved to Apple Contacts. Family notes, photos and " ++                         "Sensitive Details are not copied. Contacts access is requested only when you save.")+                    MemoryField("Given name") { TextField("Given name", text: $givenName) }+                    MemoryField("Family name") { TextField("Family name", text: $familyName) }+                    MemoryField("Nickname") { TextField("Nickname", text: $nickname) }+                }+            }+            .navigationTitle("Create Apple Contact")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() }.disabled(saving) }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save to Contacts") { save() }.disabled(saving || [givenName, familyName, nickname].allSatisfy {+                        $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+                    })+                }+            }+        }+        .frame(minWidth: 340, minHeight: 360)+        .interactiveDismissDisabled(saving)+        .graphFailure($failure)+    }++    private func save() {+        guard !saving else { return }+        guard allowed else { failure = "Apple Contacts is disabled in this synthetic workspace."; return }+        saving = true+        let values = [givenName, familyName, nickname].map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }+        Task {+            do {+                let identifier = try await Task.detached {+                    let store = CNContactStore()+                    guard try await store.requestAccess(for: .contacts) else { throw ContactAccessError.denied }+                    let contact = CNMutableContact()+                    contact.givenName = values[0]; contact.familyName = values[1]; contact.nickname = values[2]+                    let request = CNSaveRequest(); request.add(contact, toContainerWithIdentifier: nil)+                    try store.execute(request)+                    return contact.identifier+                }.value+                saving = false+                completed(ContactSelection(identifier: identifier, label: values.filter { !$0.isEmpty }.joined(separator: " ")))+            } catch { saving = false; failure = error.localizedDescription }+        }+    }+}++nonisolated private enum ContactAccessError: LocalizedError {+    case denied+    var errorDescription: String? { "Contacts access is unavailable. Allow access in Settings, or keep this person without a Contact." }+}
Halo Family/Halo Family/ArchiveControls.swift Added +57 / -0
diff --git a/Halo Family/Halo Family/ArchiveControls.swift b/Halo Family/Halo Family/ArchiveControls.swiftnew file mode 100644index 0000000..a577bf0--- /dev/null+++ b/Halo Family/Halo Family/ArchiveControls.swift	@@ -0,0 +1,57 @@+import Combine+import CoreData+import SwiftUI++struct ArchiveControls: View {+    let repository: FamilyRepository+    let recordID: NSManagedObjectID+    let subject: String+    @State private var snapshot: ArchiveSnapshot?+    @State private var writable = false+    @State private var confirming = false+    @State private var confirmationSnapshot: ArchiveSnapshot?+    @State private var failure: String?++    var body: some View {+        Group {+            if let snapshot {+                if snapshot.isArchived {+                    Text("Archived. Its records and history are retained.").foregroundStyle(.secondary)+                    Button("Restore \(subject)") { change(snapshot, archived: false) }.disabled(!writable)+                } else {+                    Button("Archive \(subject)", role: .destructive) {+                        confirmationSnapshot = snapshot+                        confirming = true+                    }.disabled(!writable)+                    Text("Archiving removes it from current views and preserves its records, links and history.")+                        .font(.caption).foregroundStyle(.secondary)+                }+            }+        }+        .task(id: recordID) { confirming = false; confirmationSnapshot = nil; reload() }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in reload() }+        .confirmationDialog("Archive \(confirmationSnapshot?.name ?? subject)?", isPresented: $confirming, titleVisibility: .visible) {+            Button("Archive \(subject)", role: .destructive) {+                guard let confirmationSnapshot else { return }+                self.confirmationSnapshot = nil+                change(confirmationSnapshot, archived: true)+            }+        } message: {+            Text("This changes current views for everyone with access to this family. " ++                 "No records or history are deleted. Use Include archived to find and restore it later.")+        }+        .graphFailure($failure)+    }++    private func reload() {+        do {+            snapshot = try repository.archiveSnapshot(recordID)+            writable = snapshot.map(repository.canArchive) ?? false+        } catch { snapshot = nil; writable = false; failure = error.localizedDescription }+    }++    private func change(_ snapshot: ArchiveSnapshot, archived: Bool) {+        do { try repository.setArchived(snapshot, archived: archived); reload() } catch { failure = error.localizedDescription }+    }+}
Halo Family/Halo Family/ChildOverviewView.swift Added +162 / -0
diff --git a/Halo Family/Halo Family/ChildOverviewView.swift b/Halo Family/Halo Family/ChildOverviewView.swiftnew file mode 100644index 0000000..1b3ef12--- /dev/null+++ b/Halo Family/Halo Family/ChildOverviewView.swift	@@ -0,0 +1,162 @@+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 includeArchivedChildren = false+    @State private var captureAvailable = 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 {+                Toggle("Include archived children", isOn: $includeArchivedChildren)+                Picker("Child", selection: $childID) {+                    Text("Choose a child").tag(nil as NSManagedObjectID?)+                    ForEach(children) { Text($0.name + ($0.isArchived ? " (archived)" : "")).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 }+                        .disabled(!captureAvailable)+                        .accessibilityIdentifier("children.capture")+                    Toggle("Include lost contact and historical people", isOn: $showLostContact)+                }+                if let childID {+                    Section("Archive and restore") {+                        ArchiveControls(repository: repository, recordID: childID, subject: "child profile")+                        Text("A child profile archive keeps its Person and relationships. An archived Person is restored from People.")+                            .font(.caption).foregroundStyle(.secondary)+                    }+                }+                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() }+        .onChange(of: includeArchivedChildren) { 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, includeArchived: includeArchivedChildren)+            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))+            captureAvailable = childID.map(repository.canCapture) ?? false+        } 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 }+    }+}
Halo Family/Halo Family/ConnectionDetailView.swift Added +231 / -0
diff --git a/Halo Family/Halo Family/ConnectionDetailView.swift b/Halo Family/Halo Family/ConnectionDetailView.swiftnew file mode 100644index 0000000..1c02954--- /dev/null+++ b/Halo Family/Halo Family/ConnectionDetailView.swift	@@ -0,0 +1,231 @@+import Combine+import CoreData+import SwiftUI++struct ConnectionDetailView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    let connection: GraphRow+    var readOnly = false+    @State private var archived = false+    @State private var personID: NSManagedObjectID?+    @State private var memberships: [MembershipRow] = []+    @State private var contexts: [ContextRow] = []+    @State private var contextID: NSManagedObjectID?+    @State private var origin: OriginRow?+    @State private var originConflicts: [OriginProposalRow] = []+    @State private var originHeads: Set<UUID> = []+    @State private var relationshipState: ConnectionStateSnapshot?+    @State private var editingState = false+    @State private var editingOrigin = false+    @State private var failure: String?++    var body: some View {+        Form {+            if readOnly || archived {+                Section { Text("This earlier relationship is retained as read-only merge history.") }+            }+            if let personID {+                NavigationLink("Person details") {+                    PersonDetailView(repository: repository, familyID: familyID, personID: personID)+                }+            }+            Section("First meeting") {+                if !originConflicts.isEmpty {+                    Label("First meeting needs review", systemImage: "person.2.badge.gearshape")+                    Text("Different accounts have been kept. Choose which to use; the alternatives stay in the history.")+                        .foregroundStyle(.secondary)+                    ForEach(originConflicts) { proposal in+                        VStack(alignment: .leading) {+                            if proposal.isCleared { Text("First meeting not recorded") }+                            if let source = proposal.sourceName { Text(source) }+                            if !proposal.narrative.isEmpty { Text(proposal.narrative) }+                            Button("Use this account") {+                                perform {+                                    try repository.resolveOrigin(connectionID: connection.id,+                                                                 choosing: proposal.id, expectedHeads: originHeads)+                                }+                            }+                            .disabled(readOnly || archived)+                        }+                    }+                } else if let origin {+                    if let source = origin.sourceName { Text(source) }+                    if !origin.narrative.isEmpty { Text(origin.narrative) }+                } else {+                    Text("Not recorded").foregroundStyle(.secondary)+                }+                Button(origin == nil ? "Record first meeting" : "Edit first meeting") { editingOrigin = true }+                    .disabled(!originConflicts.isEmpty || readOnly || archived)+            }+            if let relationshipState {+                Section("Relationship") {+                    Text(relationshipState.statusNeedsReview ? "Status needs review" : relationshipState.state.label)+                    if !relationshipState.note.isEmpty { Text(relationshipState.note) }+                    if relationshipState.closenessNeedsReview {+                        Text("Closeness needs review")+                    } else if let choice = relationshipState.closeness {+                        Text(choice.label)+                    } else if let value = relationshipState.closenessValue {+                        Text("Closeness: \(value) of 10")+                    }+                    Button("Edit relationship") { editingState = true }.disabled(readOnly || archived)+                }+            }+            Section("Contexts") {+                if memberships.isEmpty { Text("No memberships recorded.").foregroundStyle(.secondary) }+                ForEach(memberships) { membership in+                    VStack(alignment: .leading, spacing: 8) {+                        Text(membership.name)+                        if let endedAt = membership.endedAt {+                            Text("Ended \(endedAt.formatted(date: .abbreviated, time: .omitted))")+                                .font(.caption).foregroundStyle(.secondary)+                        } else {+                            if membership.isArchived { Text("Archived context").font(.caption).foregroundStyle(.secondary) }+                            Button("End membership today") {+                                perform { try repository.endMembership(membership.id, at: Date()) }+                            }+                            .disabled(readOnly || archived)+                        }+                    }+                }+                Picker("Add context", selection: $contextID) {+                    Text("Choose a context").tag(nil as NSManagedObjectID?)+                    ForEach(contexts.filter { !$0.isArchived }) { Text($0.path).tag(Optional($0.id)) }+                }+                .disabled(readOnly || archived)+                Button("Add membership") {+                    guard let contextID else { return }+                    perform {+                        _ = try repository.addMembership(connectionID: connection.id, contextID: contextID)+                        self.contextID = nil+                    }+                }+                .disabled(contextID == nil || readOnly || archived)+            }+        }+        .navigationTitle(connection.name)+        .task { perform {} }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in+            perform {}+        }+        .sheet(isPresented: $editingOrigin, onDismiss: { perform {} }, content: {+            OriginEditor(repository: repository, familyID: familyID, connectionID: connection.id,+                         original: origin, headIDs: originHeads)+        })+        .sheet(isPresented: $editingState, onDismiss: { perform {} }, content: {+            if let relationshipState {+                ConnectionStateEditor(repository: repository, connectionID: connection.id, initial: relationshipState)+            }+        })+        .graphFailure($failure)+    }++    private func perform(_ action: () throws -> Void) {+        do {+            try action()+            let current = try repository.readable(connection.id, entity: "Connection")+            archived = current.entity.attributesByName["archivedAt"] != nil && current.value(forKey: "archivedAt") != nil+            personID = try repository.personID(for: connection.id)+            memberships = try repository.memberships(for: connection.id)+            contexts = try repository.contexts(in: familyID)+            let overview = try repository.originOverview(for: connection.id)+            origin = overview.origin+            originConflicts = overview.conflicts+            originHeads = overview.headIDs+            relationshipState = try repository.connectionState(connection.id)+        } catch { failure = error.localizedDescription }+    }+}++private struct OriginEditor: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    let connectionID: NSManagedObjectID+    @State private var baseline: OriginRow?+    @State private var baselineHeads: Set<UUID>+    @State private var kind = "Description"+    @State private var contextID: NSManagedObjectID?+    @State private var eventID: NSManagedObjectID?+    @State private var narrative = ""+    @State private var contexts: [ContextRow] = []+    @State private var events: [EventRow] = []+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    init(repository: FamilyRepository, familyID: NSManagedObjectID, connectionID: NSManagedObjectID,+         original: OriginRow?, headIDs: Set<UUID>) {+        self.repository = repository+        self.familyID = familyID+        self.connectionID = connectionID+        _baseline = State(initialValue: original)+        _baselineHeads = State(initialValue: headIDs)+    }++    var body: some View {+        NavigationStack {+            Form {+                Section("First meeting") {+                    Picker("Source", selection: $kind) {+                        Text("Description").tag("Description")+                        Text("Context").tag("Context")+                        Text("Event").tag("Event")+                    }+                    if kind == "Context" {+                        Picker("Context", selection: $contextID) {+                            Text("Choose a context").tag(nil as NSManagedObjectID?)+                            ForEach(contexts) { Text($0.path).tag(Optional($0.id)) }+                        }+                    }+                    if kind == "Event" {+                        Picker("Event", selection: $eventID) {+                            Text("Choose an event").tag(nil as NSManagedObjectID?)+                            ForEach(events) { Text($0.label).tag(Optional($0.id)) }+                        }+                    }+                    TextField("How they met", text: $narrative, axis: .vertical)+                }+                if let baseline {+                    Button("Clear first meeting", role: .destructive) {+                        perform {+                            try repository.clearOrigin(connectionID: connectionID, expectedOrigin: baseline)+                            dismiss()+                        }+                    }+                }+            }+            .navigationTitle("First meeting")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save") {+                        perform {+                            let input = OriginInput(contextID: kind == "Context" ? contextID : nil,+                                                    eventID: kind == "Event" ? eventID : nil, narrative: narrative)+                            try repository.saveOrigin(connectionID: connectionID, input: input,+                                                      expectedOrigin: baseline, expectedHeads: baselineHeads)+                            dismiss()+                        }+                    }+                }+            }+        }+        .frame(minWidth: 300, minHeight: 350)+        .task {+            perform {+                contexts = try repository.contexts(in: familyID)+                events = try repository.events(in: familyID)+                contextID = baseline?.contextID+                eventID = baseline?.eventID+                narrative = baseline?.narrative ?? ""+                kind = contextID != nil ? "Context" : eventID != nil ? "Event" : "Description"+            }+        }+        .graphFailure($failure)+    }++    private func perform(_ action: () throws -> Void) {+        do { try action() } catch { failure = error.localizedDescription }+    }+}
Halo Family/Halo Family/ConnectionStateEditor.swift Added +157 / -0
diff --git a/Halo Family/Halo Family/ConnectionStateEditor.swift b/Halo Family/Halo Family/ConnectionStateEditor.swiftnew file mode 100644index 0000000..950d099--- /dev/null+++ b/Halo Family/Halo Family/ConnectionStateEditor.swift	@@ -0,0 +1,157 @@+import CoreData+import SwiftUI++struct ConnectionStateEditor: View {+    let repository: FamilyRepository+    let connectionID: NSManagedObjectID+    @State private var initialValue: Int16?+    @State private var choice: ClosenessChoice?+    @State private var state: ConnectionState+    @State private var note: String+    @State private var expectedClosenessID: NSManagedObjectID?+    @State private var expectedStatusID: NSManagedObjectID?+    @State private var closenessConflict: Bool+    @State private var statusConflict: Bool+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    init(repository: FamilyRepository, connectionID: NSManagedObjectID, initial: ConnectionStateSnapshot) {+        self.repository = repository+        self.connectionID = connectionID+        _initialValue = State(initialValue: initial.closenessValue)+        _choice = State(initialValue: initial.closeness)+        _state = State(initialValue: initial.state)+        _note = State(initialValue: initial.note)+        _expectedClosenessID = State(initialValue: initial.closenessID)+        _expectedStatusID = State(initialValue: initial.statusID)+        _closenessConflict = State(initialValue: initial.closenessNeedsReview)+        _statusConflict = State(initialValue: initial.statusNeedsReview)+    }++    var body: some View {+        NavigationStack {+            Group {+                #if os(macOS)+                macForm+                #else+                Form {+                    Section("Closeness") {+                        if closenessConflict { closenessReview }+                        closenessPicker+                        saveCloseness+                    }+                    Section("Contact") {+                        if statusConflict { statusReview }+                        statusPicker+                        noteField+                        saveStatus+                    }+                }+                #endif+            }+            .navigationTitle("Relationship")+            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }+        }+        .frame(minWidth: 300, minHeight: 350)+        .graphFailure($failure)+    }++    private var closenessReview: some View {+        TemporalConflictReview(repository: repository, connectionID: connectionID, closeness: true) {+            let saved = try repository.connectionState(connectionID)+            initialValue = saved.closenessValue+            choice = saved.closeness+            expectedClosenessID = saved.closenessID+            closenessConflict = saved.closenessNeedsReview+        }+    }++    private var statusReview: some View {+        TemporalConflictReview(repository: repository, connectionID: connectionID, closeness: false) {+            let saved = try repository.connectionState(connectionID)+            state = saved.state+            note = saved.note+            expectedStatusID = saved.statusID+            statusConflict = saved.statusNeedsReview+        }+    }++    private var closenessPicker: some View {+        Picker("Closeness", selection: $choice) {+            Text(initialValue.map { "Recorded value: \($0) of 10" } ?? "Not assessed").tag(nil as ClosenessChoice?)+            ForEach(ClosenessChoice.allCases) { Text($0.label).tag(Optional($0)) }+        }+        .disabled(closenessConflict)+        .accessibilityIdentifier("relationship.closeness")+    }++    private var statusPicker: some View {+        Picker("Status", selection: $state) {+            ForEach(ConnectionState.allCases, id: \.self) { Text($0.label).tag($0) }+        }+        .disabled(statusConflict)+        .accessibilityIdentifier("relationship.status")+    }++    private var noteField: some View {+        TextField("Explanation, if useful", text: $note, axis: .vertical)+            .disabled(statusConflict)+            .accessibilityIdentifier("relationship.note")+    }++    private var saveCloseness: some View {+        Button("Save closeness") {+            guard let choice else { return }+            perform {+                try repository.setCloseness(choice, connectionID: connectionID, expectedID: expectedClosenessID)+                expectedClosenessID = try repository.connectionState(connectionID).closenessID+            }+        }+        .disabled(choice == nil || closenessConflict)+        .accessibilityIdentifier("relationship.saveCloseness")+    }++    private var saveStatus: some View {+        Button("Save contact status") {+            perform {+                try repository.setConnectionState(state, note: note, connectionID: connectionID, expectedID: expectedStatusID)+                let saved = try repository.connectionState(connectionID)+                expectedStatusID = saved.statusID+                note = saved.note+            }+        }+        .disabled(statusConflict)+        .accessibilityIdentifier("relationship.saveStatus")+    }++    #if os(macOS)+    private var macForm: some View {+        ScrollView {+            VStack(alignment: .leading, spacing: 24) {+                MacFormSection("Closeness") {+                    if closenessConflict { closenessReview }+                    Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 14) {+                        MacFormRow("Closeness") { closenessPicker.labelsHidden().pickerStyle(.menu).fixedSize() }+                        MacFormRow("") { saveCloseness }+                    }+                }+                MacFormSection("Contact") {+                    if statusConflict { statusReview }+                    Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 14) {+                        MacFormRow("Status") { statusPicker.labelsHidden().pickerStyle(.menu).fixedSize() }+                        MacFormRow("Explanation") { noteField }+                        MacFormRow("") { saveStatus }+                    }+                }+            }+            .padding(24)+            .frame(maxWidth: 650, alignment: .leading)+        }+        .frame(minWidth: 440)+    }+    #endif++    private func perform(_ action: () throws -> Void) {+        do { try action() } catch { failure = error.localizedDescription }+    }+}
Halo Family/Halo Family/ContentView.swift Modified +117 / -125
diff --git a/Halo Family/Halo Family/ContentView.swift b/Halo Family/Halo Family/ContentView.swiftindex a88f14b..7e9b692 100644--- a/Halo Family/Halo Family/ContentView.swift	+++ b/Halo Family/Halo Family/ContentView.swift	@@ -1,152 +1,144 @@-import SwiftUI+import CloudKit import Combine-import CoreData+import SwiftUI+import WidgetKit  struct ContentView: View {     @State private var repository: FamilyRepository?     @State private var failure: String?+    @State private var loadGeneration = UUID()+    @State private var pendingCapture: CaptureRoute?+    @State private var activeCapture: CaptureRoute?+    @AppStorage("deviceOnlyLibrary") private var deviceOnly = false+    private let invitations = ShareInvitations.shared      var body: some View {-        Group {-            if let repository {-                FamilyCaptureView(repository: repository)-            } else if let failure {-                ContentUnavailableView {-                    Label("Unable to open your data", systemImage: "externaldrive.badge.exclamationmark")-                } description: {-                    Text(failure)-                } actions: {-                    Button("Try again") { Task { await load() } }+        VStack(spacing: 0) {+            libraryControls+            Group {+                if let issue = repository?.stack.accessIssue {+                    ContentUnavailableView {+                        Label("Data session locked", systemImage: "lock.shield")+                    } description: {+                        Text(issue)+                    } actions: {+                        Button("Verify and reopen", action: reopen)+                    }+                } else if let repository {+                    FamilyWorkspaceView(repository: repository)+                } else if let failure {+                    ContentUnavailableView {+                        Label("Unable to open your data", systemImage: "externaldrive.badge.exclamationmark")+                    } description: {+                        Text(failure)+                    } actions: {+                        Button("Try again") { Task { await load() } }+                    }+                } else {+                    ProgressView("Opening Halo Family…")                 }-            } else {-                ProgressView("Opening Halo Family…")             }+            .frame(maxWidth: .infinity, maxHeight: .infinity)         }         .task { await load() }+        .onOpenURL(perform: receiveCapture)+        .onChange(of: deviceOnly) { reopen() }+        .onChange(of: repository?.stack.accessIssue) { _, issue in+            if issue != nil { activeCapture = nil; WidgetCenter.shared.reloadTimelines(ofKind: "HaloFamily.ChildCapture") }+        }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh).receive(on: DispatchQueue.main)) { _ in+            WidgetCenter.shared.reloadTimelines(ofKind: "HaloFamily.ChildCapture")+        }+        .onReceive(NotificationCenter.default.publisher(for: .CKAccountChanged).receive(on: DispatchQueue.main)) { _ in+            if !deviceOnly { reopen() }+        }+        .sheet(item: $activeCapture) { route in+            if let repository { WidgetCaptureSheet(repository: repository, route: route) }+        }+    }++    private var libraryControls: some View {+        VStack(spacing: 0) {+            Menu {+                Button("Account library") { selectLibrary(deviceOnly: false) }+                Button("On this device") { selectLibrary(deviceOnly: true) }+                if let stack = repository?.stack, stack.accountScope?.mirrorsCloud == true {+                    Button("Refresh sharing permissions") { Task { await stack.revalidateSharedAccess() } }+                        .disabled(stack.verifyingShares)+                }+            } label: {+                let local = repository.map { $0.stack.accountScope == .local } ?? deviceOnly+                Label(local ? "On this device" : "Account library", systemImage: local ? "internaldrive" : "icloud")+            }+            .padding(.vertical, 8)+            .accessibilityIdentifier("library.select")+            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 }+        let generation = UUID()+        loadGeneration = generation+        let deviceOnly = deviceOnly         do {-            repository = FamilyRepository(stack: try await .production())+            let stack: PersistenceStack+            #if DEBUG+            if let directory = try SyntheticLaunch.directory() {+                stack = try PersistenceStack(directory: directory)+            } else {+                stack = try await openLibrary(deviceOnly: deviceOnly)+            }+            #else+            stack = try await openLibrary(deviceOnly: deviceOnly)+            #endif+            guard loadGeneration == generation else { return }+            repository = FamilyRepository(stack: stack)             failure = nil+            presentCapture()         } catch {+            guard loadGeneration == generation else { return }             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+    private func reopen() {+        loadGeneration = UUID()+        repository = nil+        failure = nil+        activeCapture = nil+        Task { await load() }+    } -    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 receiveCapture(_ url: URL) {+        guard let route = CaptureRoute(url: url) else { return }+        pendingCapture = route+        let local = route.child.namespace == "local"+        if deviceOnly != local { deviceOnly = local } else if repository == nil {+            Task { await load() }+        } else { presentCapture() }     } -    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-        }+    private func presentCapture() {+        guard repository != nil, repository?.stack.accessIssue == nil, let route = pendingCapture else { return }+        pendingCapture = nil+        activeCapture = route+    }++    private func selectLibrary(deviceOnly: Bool) {+        if self.deviceOnly == deviceOnly { reopen() } else { self.deviceOnly = deviceOnly }+    }++    private func openLibrary(deviceOnly: Bool) async throws -> PersistenceStack {+        if deviceOnly { return try await .deviceLibrary() }+        return try await .production()     } }
Halo Family/Halo Family/ContextCategoryViews.swift Added +132 / -0
diff --git a/Halo Family/Halo Family/ContextCategoryViews.swift b/Halo Family/Halo Family/ContextCategoryViews.swiftnew file mode 100644index 0000000..2c44a1a--- /dev/null+++ b/Halo Family/Halo Family/ContextCategoryViews.swift	@@ -0,0 +1,132 @@+import Combine+import CoreData+import SwiftUI++struct ContextCategoriesView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    @State private var categories: [ContextCategoryRow] = []+    @State private var name = ""+    @State private var edited: ContextCategoryRow?+    @State private var failure: String?++    var body: some View {+        MemoryForm {+            MemorySection("Categories") {+                Text("Categories are your own labels. Renaming or archiving a category preserves every linked Context.")+                    .foregroundStyle(.secondary)+                ForEach(categories) { category in+                    Button { edited = category } label: {+                        HStack {+                            Text(category.name)+                            if category.isArchived { Text("Archived").foregroundStyle(.secondary) }+                        }+                    }+                }+            }+            MemorySection("Add category") {+                MemoryField("Name") { TextField("Category name", text: $name) }+                Button("Add category") {+                    perform { _ = try repository.createCategory(name: name, familyID: familyID); name = "" }+                }+                .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+                Button("Add missing starter categories") { perform { try repository.addStarterCategories(familyID: familyID) } }+            }+        }+        .navigationTitle("Context categories")+        .task { perform {} }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in perform {} }+        .sheet(item: $edited) { ContextCategoryEditView(repository: repository, original: $0) }+        .graphFailure($failure)+    }++    private func perform(_ operation: () throws -> Void) {+        do { try operation(); categories = try repository.contextCategories(in: familyID) } catch { failure = error.localizedDescription }+    }+}++private struct ContextCategoryEditView: View {+    let repository: FamilyRepository+    let original: ContextCategoryRow+    @State private var name: String+    @State private var archived: Bool+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    init(repository: FamilyRepository, original: ContextCategoryRow) {+        self.repository = repository; self.original = original+        _name = State(initialValue: original.name); _archived = State(initialValue: original.isArchived)+    }++    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("Category") {+                    MemoryField("Name") { TextField("Category name", text: $name) }+                    Toggle("Archived", isOn: $archived)+                    Text("Archived categories stay attached to existing Contexts and are hidden from new choices.")+                        .foregroundStyle(.secondary)+                }+            }+            .navigationTitle("Edit category")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save") {+                        do { try repository.updateCategory(original, name: name, archived: archived); dismiss() } catch {+                            failure = error.localizedDescription+                        }+                    }+                }+            }+        }+        .frame(minWidth: 320, minHeight: 260)+        .graphFailure($failure)+    }+}++struct ContextCategorySelection: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    let contextID: NSManagedObjectID+    @State private var categories: [ContextCategoryRow] = []+    @State private var initial: NSManagedObjectID?+    @State private var selected: NSManagedObjectID?+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("Category") {+                    Picker("Category", selection: $selected) {+                        Text("No category").tag(nil as NSManagedObjectID?)+                        ForEach(categories.filter { !$0.isArchived || $0.id == initial }) { category in+                            Text(category.name + (category.isArchived ? " (archived)" : "")).tag(Optional(category.id))+                        }+                    }+                }+            }+            .navigationTitle("Context category")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save") {+                        do { try repository.setContextCategory(contextID, categoryID: selected, expectedID: initial); dismiss() } catch {+                            failure = error.localizedDescription+                        }+                    }+                }+            }+        }+        .frame(minWidth: 320, minHeight: 260)+        .task {+            do {+                categories = try repository.contextCategories(in: familyID)+                initial = try repository.contextCategory(contextID); selected = initial+            } catch { failure = error.localizedDescription }+        }+        .graphFailure($failure)+    }+}
Halo Family/Halo Family/ContextRoleEditor.swift Added +90 / -0
diff --git a/Halo Family/Halo Family/ContextRoleEditor.swift b/Halo Family/Halo Family/ContextRoleEditor.swiftnew file mode 100644index 0000000..829cb7c--- /dev/null+++ b/Halo Family/Halo Family/ContextRoleEditor.swift	@@ -0,0 +1,90 @@+import CoreData+import SwiftUI++struct ContextRoleEditor: View {+    let repository: FamilyRepository+    @State private var baseline: ContextPersonRow+    @State private var role: String+    @State private var hasStart: Bool+    @State private var hasEnd: Bool+    @State private var startedAt: Date+    @State private var endedAt: Date+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    init(repository: FamilyRepository, original: ContextPersonRow) {+        self.repository = repository+        _baseline = State(initialValue: original)+        _role = State(initialValue: original.role)+        _hasStart = State(initialValue: original.startedAt != nil)+        _hasEnd = State(initialValue: original.endedAt != nil)+        _startedAt = State(initialValue: original.startedAt ?? original.endedAt ?? Date())+        _endedAt = State(initialValue: original.endedAt ?? Date())+    }++    var body: some View {+        NavigationStack {+            Group {+                #if os(macOS)+                macForm+                #else+                Form {+                    Text(baseline.name)+                    TextField("Role", text: $role)+                    Toggle("Start date known", isOn: $hasStart)+                    if hasStart { DatePicker("From", selection: $startedAt, displayedComponents: .date) }+                    Toggle("End date known", isOn: $hasEnd)+                    if hasEnd { DatePicker("Until", selection: $endedAt, displayedComponents: .date) }+                    if hasStart && hasEnd && endedAt < startedAt {+                        Text("The end date must not be earlier than the start date.").foregroundStyle(.red)+                    }+                }+                #endif+            }+            .navigationTitle("Role and dates")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save") {+                        do {+                            try repository.updateRole(baseline.id, role: role, startedAt: hasStart ? startedAt : nil,+                                                      endedAt: hasEnd ? endedAt : nil, expected: baseline)+                            dismiss()+                        } catch { failure = error.localizedDescription }+                    }+                    .disabled(hasStart && hasEnd && endedAt < startedAt)+                }+            }+        }+        .frame(minWidth: 300, minHeight: 300)+        .graphFailure($failure)+    }++    #if os(macOS)+    private var macForm: some View {+        ScrollView {+            MacFormSection("Role and dates") {+                Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16, verticalSpacing: 14) {+                    MacFormRow("Person") { Text(baseline.name) }+                    MacFormRow("Role") { TextField("Role", text: $role).accessibilityLabel("Role") }+                    MacFormRow("Start known") { Toggle("Start date known", isOn: $hasStart).labelsHidden() }+                    if hasStart {+                        MacFormRow("From") { DatePicker("From", selection: $startedAt, displayedComponents: .date).labelsHidden() }+                    }+                    MacFormRow("End known") { Toggle("End date known", isOn: $hasEnd).labelsHidden() }+                    if hasEnd {+                        MacFormRow("Until") { DatePicker("Until", selection: $endedAt, displayedComponents: .date).labelsHidden() }+                    }+                }+                if hasStart && hasEnd && endedAt < startedAt {+                    Text("The end date must not be earlier than the start date.").foregroundStyle(.red)+                        .padding(.leading, 116)+                }+            }+            .padding(24)+            .frame(maxWidth: 650, alignment: .leading)+        }+        .frame(minWidth: 420)+    }+    #endif+}
Halo Family/Halo Family/ContextsView.swift Added +170 / -0
diff --git a/Halo Family/Halo Family/ContextsView.swift b/Halo Family/Halo Family/ContextsView.swiftnew file mode 100644index 0000000..92c6a13--- /dev/null+++ b/Halo Family/Halo Family/ContextsView.swift	@@ -0,0 +1,170 @@+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") {+                NavigationLink("Manage categories") { ContextCategoriesView(repository: repository, familyID: familyID) }+                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?+    @State private var choosingCategory = false+    @State private var categoryName = "No category"++    var body: some View {+        Form {+            Section {+                Text(context.path)+                Text(categoryName).foregroundStyle(.secondary)+                Button("Choose category") { choosingCategory = true }+                Button(archived ? "Restore context" : "Archive context") {+                    perform { try repository.archiveContext(context.id, archived: !archived) }+                }+            }+            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(isPresented: $choosingCategory, onDismiss: { perform {} }, content: {+            ContextCategorySelection(repository: repository, familyID: familyID, contextID: context.id)+        })+        .sheet(item: $editingAssociation, onDismiss: { perform {} }, content: { association in+            ContextRoleEditor(repository: repository, original: association)+        })+        .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)+            let selected = try repository.contextCategory(context.id)+            categoryName = try repository.contextCategories(in: familyID).first { $0.id == selected }?.name ?? "No category"+            connections = try repository.contextConnections(context.id)+            associations = try repository.contextPeople(context.id)+            people = try repository.people(in: familyID)+        } catch { failure = error.localizedDescription }+    }+}
Halo Family/Halo Family/EventDetailView.swift Added +355 / -0
diff --git a/Halo Family/Halo Family/EventDetailView.swift b/Halo Family/Halo Family/EventDetailView.swiftnew file mode 100644index 0000000..45db971--- /dev/null+++ b/Halo Family/Halo Family/EventDetailView.swift	@@ -0,0 +1,355 @@+import Combine+import CoreData+import SwiftUI+import UniformTypeIdentifiers++struct EventDetailView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    let eventID: NSManagedObjectID+    @State private var event: EventRow?+    @State private var participants: [ParticipantRow] = []+    @State private var gifts: [GiftRow] = []+    @State private var attachments: [AttachmentRow] = []+    @State private var editing = false+    @State private var addingPerson = false+    @State private var selectedPerson: ParticipantRow?+    @State private var addingGift = false+    @State private var selectedGift: GiftRow?+    @State private var importing = false+    @State private var working = false+    @State private var importTask: Task<Void, Never>?+    @State private var failure: String?++    var body: some View {+        MemoryForm {+            if let event {+                MemorySection("Social event") {+                    Text(event.title).font(.headline)+                    if let date = event.date { Text(date, format: .dateTime.day().month().year()) }+                    if !event.type.isEmpty { Text(event.type).foregroundStyle(.secondary) }+                    if !event.notes.isEmpty { Text(event.notes) }+                    Button("Edit event") { editing = true }+                    Button(event.isArchived ? "Restore event" : "Archive event") {+                        perform { try repository.archiveEvent(eventID, archived: !event.isArchived) }+                    }+                }+                MemorySection("People") {+                    ForEach(participants) { participant in+                        Button { selectedPerson = participant } label: {+                            VStack(alignment: .leading, spacing: 4) {+                                Text(participant.name)+                                if !participant.roles.isEmpty { Text(participant.roles.sorted().joined(separator: ", ")).font(.caption) }+                                Text("Invitation: \(participant.invitation.label) · Attendance: \(participant.attendance.label)")+                                    .font(.caption).foregroundStyle(.secondary)+                            }+                        }+                    }+                    Button("Add person to event") { addingPerson = true }+                    Text("Participation records invitations and attendance separately. " ++                         "It does not create a friendship or first-meeting record.")+                        .font(.caption).foregroundStyle(.secondary)+                }+                MemorySection("Gifts") {+                    ForEach(gifts) { gift in+                        VStack(alignment: .leading, spacing: 4) {+                            Text(gift.description)+                            if !gift.givers.isEmpty { Text("From: \(gift.givers.joined(separator: ", "))").font(.caption) }+                            if !gift.recipients.isEmpty { Text("To: \(gift.recipients.joined(separator: ", "))").font(.caption) }+                            if !gift.note.isEmpty { Text(gift.note) }+                            Button("Edit gift") { selectedGift = gift }+                            ForEach(attachments.filter { gift.attachmentIDs.contains($0.id) }) { attachment in+                                AttachmentPreview(assets: AssetRepository(stack: repository.stack), attachment: attachment)+                            }+                        }+                    }+                    Button("Record a gift") { addingGift = true }+                }+                MemorySection("Invitations and attachments") {+                    ForEach(attachments) { attachment in+                        AttachmentPreview(assets: AssetRepository(stack: repository.stack), attachment: attachment)+                    }+                    Button("Import image or PDF") { importing = true }.disabled(working)+                    if working { ProgressView("Saving attachment…") }+                    Text("App-owned JPEG, PNG or PDF copies, up to 20 MB. Image location metadata is removed.")+                        .font(.caption).foregroundStyle(.secondary)+                }+            } else { ProgressView() }+        }+        .navigationTitle(event?.title ?? "Social event")+        .task { perform {} }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in perform {} }+        .sheet(isPresented: $editing, onDismiss: { perform {} }, content: {+            if let event { EventEditor(repository: repository, familyID: familyID, initial: event) }+        })+        .sheet(isPresented: $addingPerson, onDismiss: { perform {} }, content: {+            ParticipantEditor(repository: repository, familyID: familyID, eventID: eventID, initial: nil)+        })+        .sheet(item: $selectedPerson, onDismiss: { perform {} }, content: { initial in+            ParticipantEditor(repository: repository, familyID: familyID, eventID: eventID, initial: initial)+        })+        .sheet(isPresented: $addingGift, onDismiss: { perform {} }, content: {+            GiftEditor(repository: repository, familyID: familyID, eventID: eventID, attachments: attachments)+        })+        .sheet(item: $selectedGift, onDismiss: { perform {} }, content: { initial in+            GiftEditor(repository: repository, familyID: familyID, eventID: eventID, attachments: attachments, initial: initial)+        })+        .fileImporter(isPresented: $importing, allowedContentTypes: [.jpeg, .png, .pdf]) { result in+            do {+                let url = try result.get()+                guard !working else { return }+                working = true+                importTask = Task {+                    defer { working = false; importTask = nil }+                    do {+                        let data = try await Task.detached { try ImportedFile.read(url) }.value+                        _ = try await AssetRepository(stack: repository.stack)+                            .importAttachment(data, filename: url.lastPathComponent, eventID: eventID)+                        perform {}+                    } catch { if !Task.isCancelled { failure = error.localizedDescription } }+                }+            } catch { failure = error.localizedDescription }+        }+        .onDisappear { importTask?.cancel() }+        .graphFailure($failure)+    }++    private func perform(_ action: () throws -> Void) {+        do {+            try action()+            let fresh = try repository.event(eventID)+            let people = try repository.participants(eventID)+            let gifts = try repository.gifts(eventID)+            let attachments = try repository.attachments(eventID)+            event = fresh; participants = people; self.gifts = gifts; self.attachments = attachments+        } catch { failure = error.localizedDescription }+    }+}++private struct EventEditor: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    @State private var initial: EventRow+    @State private var title: String+    @State private var date: Date+    @State private var dateKnown: Bool+    @State private var type: String+    @State private var notes: String+    @State private var subjectID: NSManagedObjectID?+    @State private var contextID: NSManagedObjectID?+    @State private var people: [GraphRow] = []+    @State private var contexts: [ContextRow] = []+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    init(repository: FamilyRepository, familyID: NSManagedObjectID, initial: EventRow) {+        self.repository = repository; self.familyID = familyID; _initial = State(initialValue: initial)+        _title = State(initialValue: initial.title); _date = State(initialValue: initial.date ?? Date())+        _dateKnown = State(initialValue: initial.date != nil)+        _type = State(initialValue: initial.type); _notes = State(initialValue: initial.notes)+        _subjectID = State(initialValue: initial.subjectID); _contextID = State(initialValue: initial.contextID)+    }+    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("Social memory") {+                    MemoryField("Title") { TextField("Title", text: $title) }+                    if initial.date == nil {+                        MemoryField("Known date") { Toggle("Record a known date", isOn: $dateKnown) }+                    }+                    if dateKnown {+                        MemoryField("Date") { DatePicker("Date", selection: $date, displayedComponents: .date) }+                    }+                    MemoryField("Type") { TextField("Type, such as birthday (optional)", text: $type) }+                    MemoryField("Subject") {+                        Picker("Subject", selection: $subjectID) {+                            Text("Not recorded").tag(nil as NSManagedObjectID?)+                            ForEach(people) { Text($0.name).tag(Optional($0.id)) }+                        }+                    }+                    MemoryField("Context") {+                        Picker("Context", selection: $contextID) {+                            Text("Not recorded").tag(nil as NSManagedObjectID?)+                            ForEach(contexts) { Text($0.path).tag(Optional($0.id)) }+                        }+                    }+                    MemoryField("Notes") { TextField("Notes", text: $notes, axis: .vertical) }+                }+            }+            .navigationTitle("Edit event")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save") {+                        do {+                            try repository.updateEvent(initial.id, title: title, date: dateKnown ? date : nil, type: type, notes: notes,+                                                       links: (subjectID, contextID), expected: initial)+                            dismiss()+                        } catch { failure = error.localizedDescription }+                    }.disabled(title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+                }+            }+        }+        .frame(minWidth: 320, minHeight: 420)+        .task {+            do {+                people = try repository.people(in: familyID)+                contexts = try repository.contexts(in: familyID)+            } catch { failure = error.localizedDescription }+        }+        .graphFailure($failure)+    }+}++private struct ParticipantEditor: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    let eventID: NSManagedObjectID+    let initial: ParticipantRow?+    @State private var people: [GraphRow] = []+    @State private var personID: NSManagedObjectID?+    @State private var roles: String+    @State private var invitation: InvitationState+    @State private var attendance: AttendanceState+    @State private var note: String+    @State private var includeHistorical = false+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    init(repository: FamilyRepository, familyID: NSManagedObjectID, eventID: NSManagedObjectID, initial: ParticipantRow?) {+        self.repository = repository; self.familyID = familyID; self.eventID = eventID; self.initial = initial+        _personID = State(initialValue: initial?.personID)+        _roles = State(initialValue: initial?.roles.sorted().joined(separator: ", ") ?? "")+        _invitation = State(initialValue: initial?.invitation ?? .unknown)+        _attendance = State(initialValue: initial?.attendance ?? .unknown); _note = State(initialValue: initial?.note ?? "")+    }+    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("Participation") {+                    if let initial { Text(initial.name).font(.headline) } else {+                        Toggle("Include historical people", isOn: $includeHistorical)+                        MemoryField("Person") {+                            Picker("Person", selection: $personID) {+                                Text("Choose a person").tag(nil as NSManagedObjectID?)+                                ForEach(people) { Text($0.name).tag(Optional($0.id)) }+                            }+                        }+                    }+                    MemoryField("Roles") { TextField("Roles, separated by commas", text: $roles) }+                    MemoryField("Invitation") {+                        Picker("Invitation", selection: $invitation) {+                            ForEach(InvitationState.allCases, id: \.self) { Text($0.label).tag($0) }+                        }+                    }+                    MemoryField("Attendance") {+                        Picker("Attendance", selection: $attendance) {+                            ForEach(AttendanceState.allCases, id: \.self) { Text($0.label).tag($0) }+                        }+                    }+                    MemoryField("Note") { TextField("Note", text: $note, axis: .vertical) }+                }+            }+            .navigationTitle("Event person")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save") {+                        guard let personID else { return }+                        do {+                            try repository.saveParticipant(eventID: eventID, personID: personID,+                                                           roles: Set(roles.components(separatedBy: ",")), invitation: invitation,+                                                           attendance: attendance, note: note, expected: initial)+                            dismiss()+                        } catch { failure = error.localizedDescription }+                    }.disabled(personID == nil)+                }+            }+        }+        .frame(minWidth: 320, minHeight: 420)+        .task { reload() }+        .onChange(of: includeHistorical) { reload() }+        .graphFailure($failure)+    }+    private func reload() {+        do {+            let existing = Set(try repository.participants(eventID).map(\.personID))+            people = try repository.people(in: familyID, includeDeceased: includeHistorical).filter { !existing.contains($0.id) }+        } catch { failure = error.localizedDescription }+    }+}++private struct GiftEditor: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    let eventID: NSManagedObjectID+    let attachments: [AttachmentRow]+    @State private var people: [GraphRow] = []+    @State private var groups: [GraphRow] = []+    @State private var input = GiftInput(description: "")+    @State private var initial: GiftRow?+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss+    init(repository: FamilyRepository, familyID: NSManagedObjectID, eventID: NSManagedObjectID,+         attachments: [AttachmentRow], initial: GiftRow? = nil) {+        self.repository = repository; self.familyID = familyID; self.eventID = eventID; self.attachments = attachments+        _initial = State(initialValue: initial)+        if let initial {+            _input = State(initialValue: GiftInput(description: initial.description, givers: initial.giverIDs, groups: initial.groupIDs,+                                                  recipients: initial.recipientIDs, attachments: initial.attachmentIDs, note: initial.note))+        }+    }+    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("Gift") {+                    MemoryField("Description") { TextField("What was given?", text: $input.description) }+                    MemoryField("Note") { TextField("Note", text: $input.note, axis: .vertical) }+                }+                MemorySection("From") {+                    PersonSelection(rows: people, selection: $input.givers)+                    PersonSelection(rows: groups, selection: $input.groups)+                }+                MemorySection("To") { PersonSelection(rows: people, selection: $input.recipients) }+                if !attachments.isEmpty {+                    MemorySection("Event attachments") {+                        PersonSelection(rows: attachments.map { GraphRow(id: $0.id, name: $0.title) }, selection: $input.attachments)+                    }+                }+            }+            .navigationTitle("Record gift")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save") {+                        do {+                            try repository.saveGift(eventID: eventID, input: input, expected: initial)+                            dismiss()+                        } catch { failure = error.localizedDescription }+                    }.disabled(input.description.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+                }+            }+        }+        .frame(minWidth: 320, minHeight: 440)+        .task {+            do {+                people = try repository.people(in: familyID)+                groups = try repository.groups(in: familyID)+            } catch { failure = error.localizedDescription }+        }+        .graphFailure($failure)+    }+}++struct PersonSelection: View {+    let rows: [GraphRow]+    @Binding var selection: Set<NSManagedObjectID>+    var body: some View {+        ForEach(rows) { row in+            Toggle(row.name, isOn: Binding(get: { selection.contains(row.id) }, set: { chosen in+                if chosen { selection.insert(row.id) } else { selection.remove(row.id) }+            }))+        }+    }+}
Halo Family/Halo Family/EventsView.swift Added +63 / -0
diff --git a/Halo Family/Halo Family/EventsView.swift b/Halo Family/Halo Family/EventsView.swiftnew file mode 100644index 0000000..804dcdc--- /dev/null+++ b/Halo Family/Halo Family/EventsView.swift	@@ -0,0 +1,63 @@+import Combine+import CoreData+import SwiftUI++struct EventsView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    @State private var events: [EventRow] = []+    @State private var title = ""+    @State private var notes = ""+    @State private var date = Date()+    @State private var dateKnown = false+    @State private var failure: String?+    @State private var includeArchived = false++    var body: some View {+        MemoryForm {+            MemorySection("Social memories") {+                Toggle("Include archived events", isOn: $includeArchived)+                ForEach(events) { event in+                    NavigationLink(event.label) {+                        EventDetailView(repository: repository, familyID: familyID, eventID: event.id)+                    }+                }+                if events.isEmpty { Text("No events recorded.").foregroundStyle(.secondary) }+            }+            MemorySection("Record an event") {+                TextField("Title, such as a birthday or playdate", text: $title)+                Toggle("I know the date", isOn: $dateKnown)+                if dateKnown { DatePicker("Date", selection: $date, displayedComponents: .date) }+                TextField("Notes", text: $notes, axis: .vertical)+                Button("Save event") {+                    perform {+                        _ = try repository.createEvent(title: title, date: date, notes: notes, familyID: familyID)+                        title = ""+                        notes = ""+                        dateKnown = false+                    }+                }+                .disabled(!dateKnown || title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+                if !dateKnown {+                    Text("When the meeting date is unknown, record a description on the connection instead.")+                        .foregroundStyle(.secondary)+                }+            }+        }+        .navigationTitle("Events")+        .task { perform {} }+        .onChange(of: includeArchived) { perform {} }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in+            perform {}+        }+        .graphFailure($failure)+    }++    private func perform(_ action: () throws -> Void) {+        do {+            try action()+            events = try repository.events(in: familyID, includeArchived: includeArchived)+        } catch { failure = error.localizedDescription }+    }+}
Halo Family/Halo Family/FamilyBackupView.swift Added +138 / -0
diff --git a/Halo Family/Halo Family/FamilyBackupView.swift b/Halo Family/Halo Family/FamilyBackupView.swiftnew file mode 100644index 0000000..f9bf130--- /dev/null+++ b/Halo Family/Halo Family/FamilyBackupView.swift	@@ -0,0 +1,138 @@+import CoreData+import SwiftUI+import UniformTypeIdentifiers++struct FamilyBackupView: View {+    let repository: BackupRepository+    let familyID: NSManagedObjectID?+    var imported: (NSManagedObjectID) -> Void+    @State private var readable = true+    @State private var working = false+    @State private var picking = false+    @State private var moving = false+    @State private var exportURL: URL?+    @State private var selectedURL: URL?+    @State private var preview: BackupPreview?+    @State private var asNewCopy = true+    @State private var failure: String?+    @State private var outcome: String?+    @State private var operation: Task<Void, Never>?+    @State private var visible = false++    var body: some View {+        MemoryForm {+            MemorySection("Export family") {+                Text("The ZIP contains the whole selected family, including shared notes, Sensitive Details, photos and attachments. " ++                     "Anyone with the file can read them. Apple Contacts links stay on this device.")+                    .font(.callout).foregroundStyle(.secondary)+                Toggle("Include a readable Markdown summary", isOn: $readable)+                Button("Create ZIP backup") { export() }.disabled(familyID == nil || working || moving || picking)+            }+            MemorySection("Import backup") {+                Text("Select a Halo Family ZIP to preview it before importing. Existing records are never overwritten.")+                    .foregroundStyle(.secondary)+                Button("Choose backup…") { clearPreview(); picking = true }.disabled(working || moving || picking)+                if let preview {+                    Text(preview.familyName).font(.headline)+                    Text("\(preview.peopleCount) people · \(preview.eventCount) events · " ++                         ByteCountFormatter.string(fromByteCount: Int64(preview.payloadBytes), countStyle: .file) ++                         " in attachments/history")+                    Text("Created \(preview.backup.createdAt.formatted(date: .abbreviated, time: .shortened))")+                        .font(.caption).foregroundStyle(.secondary)+                    Picker("Import as", selection: $asNewCopy) {+                        Text("A new family copy").tag(true)+                        Text("Restore original identities if absent").tag(false)+                    }+                    Text(asNewCopy ? "Creates a separate family with new identities. Merge history is retained; " ++                         "old merges cannot be undone in the copy." :+                         "Preserves original identities. The import stops if any identity already exists on this device.")+                        .font(.caption).foregroundStyle(.secondary)+                    Text("The imported family is saved in your own space and may sync to your iCloud account. " ++                         "It is not shared automatically.")+                        .font(.caption).foregroundStyle(.secondary)+                    Button(asNewCopy ? "Import new copy" : "Restore absent family") { restore(preview) }.disabled(working)+                    Button("Cancel preview", role: .cancel) { clearPreview() }.disabled(working)+                }+            }+            if working { ProgressView("Working…") }+            if let outcome { Text(outcome).foregroundStyle(.secondary) }+        }+        .disabled(working)+        .navigationTitle("Backup and import")+        .fileImporter(isPresented: $picking, allowedContentTypes: [.zip]) { result in select(result) }+        .fileMover(isPresented: $moving, file: exportURL) { result in+            switch result {+            case .success: outcome = "Backup saved."+            case .failure(let error): failure = error.localizedDescription+            }+            clearExport()+        } onCancellation: { clearExport() }+        .graphFailure($failure)+        .onAppear { visible = true }+        .onDisappear { visible = false; operation?.cancel(); if !working { clearExport(); clearPreview() } }+    }++    private func export() {+        guard let familyID, !working else { return }+        working = true; outcome = nil+        operation = Task {+            defer { drained() }+            do {+                let url = try await repository.export(familyID: familyID, readable: readable)+                if Task.isCancelled { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()); return }+                exportURL = url; moving = true+            } catch { if !Task.isCancelled { failure = error.localizedDescription } }+        }+    }++    private func select(_ result: Result<URL, Error>) {+        guard !working else { return }+        working = true; outcome = nil+        operation = Task {+            defer { drained() }+            do {+                let selected = try result.get()+                let staging = Task.detached { try BackupStaging.copy(selected) }+                let archive = try await withTaskCancellationHandler { try await staging.value } onCancel: { staging.cancel() }+                selectedURL = archive+                try Task.checkCancellation()+                preview = try await repository.preview(archive)+                try Task.checkCancellation()+                asNewCopy = true+            } catch {+                clearPreview()+                if !Task.isCancelled { failure = error.localizedDescription }+            }+        }+    }++    private func restore(_ preview: BackupPreview) {+        guard !working else { return }+        working = true; outcome = nil+        operation = Task {+            defer { drained() }+            do {+                let family = try await repository.restore(preview, asNewCopy: asNewCopy)+                imported(family)+                outcome = "Family imported."+                clearPreview()+            } catch { if !Task.isCancelled { failure = error.localizedDescription } }+        }+    }++    private func clearPreview() {+        preview = nil+        if let selectedURL { try? FileManager.default.removeItem(at: selectedURL.deletingLastPathComponent()) }+        selectedURL = nil+    }++    private func drained() {+        if Task.isCancelled || !visible { clearExport(); clearPreview() }+        working = false; operation = nil+    }++    private func clearExport() {+        if let exportURL { try? FileManager.default.removeItem(at: exportURL.deletingLastPathComponent()) }+        exportURL = nil+    }+}
Halo Family/Halo Family/FamilyKnowledgeViews.swift Added +385 / -0
diff --git a/Halo Family/Halo Family/FamilyKnowledgeViews.swift b/Halo Family/Halo Family/FamilyKnowledgeViews.swiftnew file mode 100644index 0000000..3456809--- /dev/null+++ b/Halo Family/Halo Family/FamilyKnowledgeViews.swift	@@ -0,0 +1,385 @@+import Combine+import CoreData+import SwiftUI++struct SensitiveDetailsView: View {+    let repository: FamilyRepository+    let personID: NSManagedObjectID+    @State private var initial: SensitiveSnapshot+    @State private var deceased: Bool+    @State private var year: String+    @State private var month: String+    @State private var day: String+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    init(repository: FamilyRepository, personID: NSManagedObjectID, initial: SensitiveSnapshot) {+        self.repository = repository; self.personID = personID; _initial = State(initialValue: initial)+        _deceased = State(initialValue: initial.isDeceased)+        _year = State(initialValue: initial.date.year.map(String.init) ?? "")+        _month = State(initialValue: initial.date.month.map(String.init) ?? "")+        _day = State(initialValue: initial.date.day.map(String.init) ?? "")+    }++    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("Sensitive details") {+                    Toggle("This person has died", isOn: $deceased).accessibilityIdentifier("sensitive.deceased")+                    if deceased {+                        Text("Record only what is known. The date is optional; year and month can stand alone.")+                            .foregroundStyle(.secondary)+                        MemoryField("Year") { TextField("Year", text: $year) }+                        MemoryField("Month") { TextField("Month (1–12)", text: $month) }+                        MemoryField("Day") { TextField("Day", text: $day) }+                    }+                    Text("Existing relationships and social memories are preserved. These details are shared with invited co-parents.")+                        .font(.caption).foregroundStyle(.secondary)+                }+            }+            .navigationTitle("Sensitive details")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) { Button("Save") { save() } }+            }+        }+        .frame(minWidth: 320, minHeight: 350)+        .graphFailure($failure)+    }++    private func save() {+        do {+            func number(_ input: String) throws -> Int? {+                let value = input.trimmingCharacters(in: .whitespacesAndNewlines)+                if value.isEmpty { return nil }+                guard let number = Int(value) else { throw MemoryError.invalidDate }+                return number+            }+            let date = try deceased ? PartialDate(year: number(year), month: number(month), day: number(day)) : PartialDate()+            try repository.setSensitiveDetails(personID, deceased: deceased, date: date, expected: initial)+            dismiss()+        } catch { failure = error.localizedDescription }+    }+}++struct FamilyKnowledgeView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    let personID: NSManagedObjectID+    @State private var people: [GraphRow] = []+    @State private var facts: [FamilyFactRow] = []+    @State private var includeArchived = false+    @State private var derived: [DerivedKinshipRow] = []+    @State private var labels: [AddressLabelRow] = []+    @State private var editingLabel: AddressLabelRow?+    @State private var groups: [GraphRow] = []+    @State private var targetID: NSManagedObjectID?+    @State private var kind: StructuralKind? = .parentOf+    @State private var customLabel = ""+    @State private var nature = ""+    @State private var note = ""+    @State private var started = false+    @State private var ended = false+    @State private var startDate = Date()+    @State private var endDate = Date()+    @State private var address = ""+    @State private var language = ""+    @State private var script = ""+    @State private var usedByPerson: NSManagedObjectID?+    @State private var usedByGroup: NSManagedObjectID?+    @State private var failure: String?++    var body: some View {+        MemoryForm {+            MemorySection("Family knowledge") {+                Toggle("Include facts archived by a merge", isOn: $includeArchived)+                ForEach(facts) { fact in+                    VStack(alignment: .leading, spacing: 6) {+                        Text("\(fact.source) → \(fact.target): \(fact.label)")+                        if !fact.nature.isEmpty { Text(fact.nature).font(.caption).foregroundStyle(.secondary) }+                        if !fact.note.isEmpty { Text(fact.note) }+                        if fact.isArchived { Text("Archived during merge").font(.caption).foregroundStyle(.secondary) }+                        if let start = fact.startedAt { Text("From \(start.formatted(date: .abbreviated, time: .omitted))").font(.caption) }+                        if let end = fact.endedAt {+                            Text("Until \(end.formatted(date: .abbreviated, time: .omitted))").font(.caption)+                        } else if !fact.isArchived {+                            Button("End this relationship today") { perform { try repository.endFamilyFact(fact.id, at: Date()) } }+                        }+                    }+                }+                if facts.isEmpty {+                    Text("Record the family knowledge you have. A complete family tree is optional.").foregroundStyle(.secondary)+                }+            }+            if !derived.isEmpty {+                MemorySection("Derived from known family facts") {+                    ForEach(derived) { relative in+                        Text("\(relative.name): \(relative.label)")+                    }+                    Text("These paths do not change entered relationships or family address labels.")+                        .font(.caption).foregroundStyle(.secondary)+                }+            }+            MemorySection("Add a relationship from this person") {+                MemoryField("To") {+                    Picker("To", selection: $targetID) {+                        Text("Choose a person").tag(nil as NSManagedObjectID?)+                        ForEach(people.filter { $0.id != personID }) { Text($0.name).tag(Optional($0.id)) }+                    }+                }+                MemoryField("Relationship") {+                    Picker("Relationship", selection: $kind) {+                        Text("Entered description").tag(nil as StructuralKind?)+                        ForEach(StructuralKind.allCases, id: \.self) { Text($0.label).tag(Optional($0)) }+                    }+                }+                if kind == nil {+                    MemoryField("Description") { TextField("Such as grandmother or second cousin", text: $customLabel) }+                } else {+                    MemoryField("Nature") {+                        Picker("Nature", selection: $nature) {+                            Text("Not recorded").tag("")+                            ForEach(["biological", "adoptive", "step", "foster", "unknown"], id: \.self) { Text($0.capitalized).tag($0) }+                        }+                    }+                }+                OptionalDates(knownStart: $started, knownEnd: $ended, start: $startDate, end: $endDate)+                MemoryField("Note") { TextField("Note", text: $note, axis: .vertical) }+                Button("Save relationship") {+                    guard let targetID else { return }+                    perform {+                        try repository.addFamilyFact(sourceID: personID, targetID: targetID, kind: kind, label: customLabel,+                                                     nature: nature, dates: (started ? startDate : nil, ended ? endDate : nil), note: note)+                        self.targetID = nil; customLabel = ""; note = ""+                    }+                }+                .disabled(targetID == nil || (kind == nil && customLabel.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty))+            }+            MemorySection("What people call them") {+                ForEach(labels) { label in+                    VStack(alignment: .leading) {+                        Text("\(label.usedBy): \(label.label)")+                        if !label.language.isEmpty || !label.script.isEmpty {+                            Text([label.language, label.script].filter { !$0.isEmpty }.joined(separator: " · ")).font(.caption)+                        }+                        Button("Edit label") { editingLabel = label }+                    }+                }+                MemoryField("Label") { TextField("Family title or name", text: $address) }+                MemoryField("Used by") {+                    Picker("Used by person", selection: $usedByPerson) {+                        Text("General or group").tag(nil as NSManagedObjectID?)+                        ForEach(people) { Text($0.name).tag(Optional($0.id)) }+                    }+                }+                if usedByPerson == nil {+                    MemoryField("Group") {+                        Picker("Used by group", selection: $usedByGroup) {+                            Text("General").tag(nil as NSManagedObjectID?)+                            ForEach(groups) { Text($0.name).tag(Optional($0.id)) }+                        }+                    }+                }+                MemoryField("Language") { TextField("Language (optional)", text: $language) }+                MemoryField("Script") { TextField("Script (optional)", text: $script) }+                Button("Add address label") {+                    perform {+                        try repository.addAddressLabel(targetID: personID, label: address, usedByPerson: usedByPerson,+                                                       usedByGroup: usedByPerson == nil ? usedByGroup : nil, language: language,+                                                           script: script)+                        address = ""+                    }+                }+                .disabled(address.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+            }+            NavigationLink("Groups and households") { GroupsView(repository: repository, familyID: familyID) }+        }+        .navigationTitle("Family")+        .onChange(of: includeArchived) { perform {} }+        .sheet(item: $editingLabel, content: { initial in+            AddressLabelEditor(repository: repository, initial: initial)+        })+        .task { perform {} }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in perform {} }+        .graphFailure($failure)+    }++    private func perform(_ action: () throws -> Void) {+        do {+            try action()+            people = try repository.people(in: familyID)+            facts = try repository.familyFacts(for: personID, includeArchived: includeArchived)+            derived = try repository.derivedKinship(for: personID)+            labels = try repository.addressLabels(for: personID)+            groups = try repository.groups(in: familyID)+        } catch { failure = error.localizedDescription }+    }+}++private struct AddressLabelEditor: View {+    let repository: FamilyRepository+    @State private var initial: AddressLabelRow+    @State private var label: String+    @State private var language: String+    @State private var script: String+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss+    init(repository: FamilyRepository, initial: AddressLabelRow) {+        self.repository = repository+        _initial = State(initialValue: initial)+        _label = State(initialValue: initial.label)+        _language = State(initialValue: initial.language)+        _script = State(initialValue: initial.script)+    }+    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("Address label") {+                    Text("Used by: \(initial.usedBy)").foregroundStyle(.secondary)+                    MemoryField("Label") { TextField("Label", text: $label) }+                    MemoryField("Language") { TextField("Language", text: $language) }+                    MemoryField("Script") { TextField("Script", text: $script) }+                }+            }+            .navigationTitle("Edit label")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save") {+                        do {+                            try repository.updateAddressLabel(initial.id, label: label, language: language, script: script,+                                expected: initial)+                            dismiss()+                        } catch { failure = error.localizedDescription }+                    }.disabled(label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+                }+            }+        }+        .frame(minWidth: 320, minHeight: 300)+        .graphFailure($failure)+    }+}++struct OptionalDates: View {+    @Binding var knownStart: Bool+    @Binding var knownEnd: Bool+    @Binding var start: Date+    @Binding var end: Date+    var body: some View {+        Toggle("Start date known", isOn: $knownStart)+        if knownStart { MemoryField("From") { DatePicker("From", selection: $start, displayedComponents: .date) } }+        Toggle("End date known", isOn: $knownEnd)+        if knownEnd { MemoryField("Until") { DatePicker("Until", selection: $end, displayedComponents: .date) } }+    }+}++struct GroupsView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    @State private var groups: [GraphRow] = []+    @State private var name = ""+    @State private var failure: String?+    @State private var includeArchived = false+    var body: some View {+        MemoryForm {+            MemorySection("Groups and households") {+                Toggle("Include archived groups", isOn: $includeArchived)+                ForEach(groups) { group in+                    NavigationLink(group.name + (group.isArchived ? " (archived)" : "")) {+                        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 {} }+        .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(); groups = try repository.groups(in: familyID, includeArchived: includeArchived) } 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?+    @State private var isArchived = false+    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()) }+                        }+                        .disabled(isArchived)+                    }+                }+            }+            MemorySection("Archive and restore") {+                ArchiveControls(repository: repository, recordID: group.id, subject: "group")+            }+            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)+            }+            .disabled(isArchived)+        }+        .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)+            isArchived = try repository.archiveSnapshot(group.id).isArchived+        } catch { failure = error.localizedDescription }+    }+}
Halo Family/Halo Family/FamilyManagerView.swift Added +109 / -0
diff --git a/Halo Family/Halo Family/FamilyManagerView.swift b/Halo Family/Halo Family/FamilyManagerView.swiftnew file mode 100644index 0000000..5af25f6--- /dev/null+++ b/Halo Family/Halo Family/FamilyManagerView.swift	@@ -0,0 +1,109 @@+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")+                }+                Section("Keep a backup") {+                    NavigationLink("Backup and import") {+                        FamilyBackupView(repository: BackupRepository(stack: repository.stack), familyID: selectedFamilyID) {+                            selectedFamilyID = $0+                            reload()+                        }+                    }+                    .disabled(preparingShare)+                }+                if let selectedFamilyID, selectedFamilyID.persistentStore == repository.stack.privateStore {+                    Section("Share with a co-parent") {+                        Text("Everyone you invite can see and edit the whole family space, " ++                             "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 }+    }+}
Halo Family/Halo Family/FamilyReviewView.swift Added +111 / -0
diff --git a/Halo Family/Halo Family/FamilyReviewView.swift b/Halo Family/Halo Family/FamilyReviewView.swiftnew file mode 100644index 0000000..ec0bc97--- /dev/null+++ b/Halo Family/Halo Family/FamilyReviewView.swift	@@ -0,0 +1,111 @@+import Combine+import CoreData+import SwiftUI++struct FamilyReviewView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    @State private var people: [GraphRow] = []+    @State private var connections: [ConnectionReviewRow] = []+    @State private var duplicates: [DuplicatePersonPair] = []+    @State private var selectedDuplicate: DuplicatePersonPair?+    @State private var mergeIssues = false+    @AppStorage("halo.duplicateSuggestions.hidden") private var hiddenDuplicates = "[]"+    @State private var failure: String?+    @State private var loaded = false+    private var visibleDuplicates: [DuplicatePersonPair] {+        let hidden = Set((try? JSONDecoder().decode([String].self, from: Data(hiddenDuplicates.utf8))) ?? [])+        return duplicates.filter { !hidden.contains($0.id) }+    }++    var body: some View {+        List {+            if let failure {+                Section("Review could not be refreshed") {+                    Text(failure)+                    Button("Retry review", action: reload)+                }+            }+            if !loaded && failure == nil { ProgressView("Loading review…") }+            if loaded && failure == nil && people.isEmpty && connections.isEmpty && visibleDuplicates.isEmpty && !mergeIssues {+                ContentUnavailableView("All caught up", systemImage: "checkmark.circle",+                                       description: Text("New captures and different relationship accounts appear here."))+            }+            if mergeIssues {+                Section("Merge accounts need review") {+                    NavigationLink("Review competing merges and late relationship accounts") {+                        MergeConflictReviewView(repository: repository, familyID: familyID)+                    }+                }+            }+            if !people.isEmpty {+                Section("Details to fill in") {+                    ForEach(people) { person in+                        NavigationLink(person.name) {+                            PersonDetailView(repository: repository, familyID: familyID, personID: person.id)+                        }+                    }+                }+            }+            if !connections.isEmpty {+                Section("Different accounts") {+                    ForEach(connections) { connection in+                        NavigationLink {+                            ConnectionDetailView(repository: repository, familyID: familyID,+                                                 connection: GraphRow(id: connection.id, name: connection.name))+                        } label: {+                            VStack(alignment: .leading, spacing: 4) {+                                Text(connection.name)+                                Text("Known by \(connection.childName)").font(.caption).foregroundStyle(.secondary)+                                if connection.originNeedsReview { Text("First meeting needs review").font(.caption) }+                                if connection.relationshipNeedsReview { Text("Relationship needs review").font(.caption) }+                            }+                        }+                    }+                }+            }+            if !visibleDuplicates.isEmpty {+                Section("Similar names") {+                    Text("These may be separate people. Review the records before choosing to merge.")+                        .font(.caption).foregroundStyle(.secondary)+                    ForEach(visibleDuplicates) { pair in+                        VStack(alignment: .leading) {+                            Button("Review \(pair.source.name) and \(pair.survivor.name)") { selectedDuplicate = pair }+                            Button("Hide this suggestion on this device") {+                                var ids = Set((try? JSONDecoder().decode([String].self, from: Data(hiddenDuplicates.utf8))) ?? [])+                                ids.insert(pair.id)+                                if let data = try? JSONEncoder().encode(ids.sorted()), let text = String(data: data, encoding: .utf8) {+                                    hiddenDuplicates = text+                                }+                            }.font(.caption)+                        }+                    }+                }+            }+            Section("History") {+                NavigationLink("Merge history") { PersonMergeHistoryView(repository: repository, familyID: familyID) }+            }+        }+        .navigationTitle("Review")+        .task { reload() }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in reload() }+        .sheet(item: $selectedDuplicate, onDismiss: reload) { pair in+            PersonMergeView(repository: repository, familyID: familyID, sourceID: pair.source.id, preferredSurvivor: pair.survivor.id)+        }+    }++    private func reload() {+        do {+            let refreshedPeople = try repository.people(in: familyID, needsReview: true)+            let refreshedConnections = try repository.reviewConnections(in: familyID)+            let refreshedDuplicates = try repository.likelyDuplicates(in: familyID)+            mergeIssues = try !repository.mergeConflicts(in: familyID).isEmpty || !repository.lateMergeAccounts(in: familyID).isEmpty+            people = refreshedPeople+            connections = refreshedConnections+            duplicates = refreshedDuplicates+            loaded = true+            failure = nil+        } catch { failure = error.localizedDescription }+    }+}
Halo Family/Halo Family/FamilySharingView.swift Added +104 / -0
diff --git a/Halo Family/Halo Family/FamilySharingView.swift b/Halo Family/Halo Family/FamilySharingView.swiftnew file mode 100644index 0000000..0bd1fc5--- /dev/null+++ b/Halo Family/Halo Family/FamilySharingView.swift	@@ -0,0 +1,104 @@+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) {+            Task { await parent.sharing.stack.revalidateSharedAccess() }+            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) {+            Task { await parent.sharing.stack.revalidateSharedAccess() }+            parent.onFailure("Sharing has stopped. The family’s access has changed.")+        }+    }+}+#endif
Halo Family/Halo Family/FamilyWorkspaceView.swift Added +141 / -0
diff --git a/Halo Family/Halo Family/FamilyWorkspaceView.swift b/Halo Family/Halo Family/FamilyWorkspaceView.swiftnew file mode 100644index 0000000..1122fa9--- /dev/null+++ b/Halo Family/Halo Family/FamilyWorkspaceView.swift	@@ -0,0 +1,141 @@+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 notice = repository.stack.storageNotice { Text(notice).padding().background(.regularMaterial) }+            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 {+                VStack {+                    Label(issue, systemImage: "icloud.slash")+                    Button("Verify shared access") { Task { await repository.stack.revalidateSharedAccess() } }+                }.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.verifyAccount(); 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)+        }+    }+}
Halo Family/Halo Family/FormComponents.swift Added +81 / -0
diff --git a/Halo Family/Halo Family/FormComponents.swift b/Halo Family/Halo Family/FormComponents.swiftnew file mode 100644index 0000000..aa22aea--- /dev/null+++ b/Halo Family/Halo Family/FormComponents.swift	@@ -0,0 +1,81 @@+import SwiftUI++struct MemoryForm<Content: View>: View {+    @ViewBuilder var content: () -> Content+    var body: some View {+        #if os(macOS)+        ScrollView { VStack(alignment: .leading, spacing: 24, content: content).padding(24).frame(maxWidth: 750) }+        #else+        Form(content: content)+        #endif+    }+}++struct MemorySection<Content: View>: View {+    let title: String+    @ViewBuilder var content: () -> Content+    init(_ title: String, @ViewBuilder content: @escaping () -> Content) { self.title = title; self.content = content }+    var body: some View {+        #if os(macOS)+        MacFormSection(title, content: content)+        #else+        Section(title, content: content)+        #endif+    }+}++struct MemoryField<Content: View>: View {+    let title: String+    @ViewBuilder var content: () -> Content+    init(_ title: String, @ViewBuilder content: @escaping () -> Content) { self.title = title; self.content = content }+    var body: some View {+        #if os(macOS)+        Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 16) {+            MacFormRow(title) { content().labelsHidden() }+        }+        #else+        content()+        #endif+    }+}++#if os(macOS)+struct MacFormRow<Content: View>: View {+    let label: String+    @ViewBuilder var content: () -> Content++    init(_ label: String, @ViewBuilder content: @escaping () -> Content) {+        self.label = label+        self.content = content+    }++    var body: some View {+        GridRow {+            Text(label).foregroundStyle(.secondary).frame(width: 100, alignment: .trailing)+            content().frame(maxWidth: .infinity, alignment: .leading)+        }+    }+}++struct MacFormSection<Content: View>: View {+    let title: String+    @ViewBuilder var content: () -> Content++    init(_ title: String, @ViewBuilder content: @escaping () -> Content) {+        self.title = title+        self.content = content+    }++    var body: some View {+        VStack(alignment: .leading, spacing: 12) {+            Text(title).font(.headline)+            VStack(alignment: .leading, spacing: 14, content: content)+                .padding(18)+                .background {+                    RoundedRectangle(cornerRadius: 16).fill(.clear)+                        .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 16))+                }+        }+    }+}+#endif
Halo Family/Halo Family/Halo Family.entitlements Modified +2 / -0
diff --git a/Halo Family/Halo Family/Halo Family.entitlements b/Halo Family/Halo Family/Halo Family.entitlementsindex 9883539..edc3231 100644--- a/Halo Family/Halo Family/Halo Family.entitlements	+++ b/Halo Family/Halo Family/Halo Family.entitlements	@@ -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>com.apple.security.personal-information.addressbook</key>+    <true/> 	<key>com.apple.security.network.client</key> 	<true/> 	<key>aps-environment</key>
Halo Family/Halo Family/MergeConflictReviewView.swift Added +78 / -0
diff --git a/Halo Family/Halo Family/MergeConflictReviewView.swift b/Halo Family/Halo Family/MergeConflictReviewView.swiftnew file mode 100644index 0000000..021a25a--- /dev/null+++ b/Halo Family/Halo Family/MergeConflictReviewView.swift	@@ -0,0 +1,78 @@+import Combine+import CoreData+import SwiftUI++struct MergeConflictReviewView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    @State private var conflicts: [PersonMergeConflict] = []+    @State private var lateAccounts: [LateMergeAccounts] = []+    @State private var confirming: PersonMergeConflict?+    @State private var showingConfirmation = false+    @State private var failure: String?++    var body: some View {+        MemoryForm {+            ForEach(conflicts) { conflict in+                MemorySection("Competing merge accounts") {+                    ForEach(conflict.people) { person in+                        NavigationLink(person.name) {+                            PersonDetailView(repository: repository, familyID: familyID, personID: person.id)+                        }+                    }+                    Text("These merges disagree or form a circular alias. Both identities and all merge accounts are retained.")+                    Text("Recovery shows the separate people again and marks their details for review. " ++                         "It keeps the currently saved notes, photos and references. Earlier values remain in merge history; " ++                         "this recovery does not undo or overwrite intervening edits.")+                    Button("Show separate people for review") { confirming = conflict; showingConfirmation = true }+                }+            }+            ForEach(lateAccounts) { account in+                MemorySection("Earlier relationship changed: \(account.name)") {+                    Text("Additional or changed accounts arrived after the merge. The original records remain in history.")+                    NavigationLink("Read earlier relationship accounts") {+                        ConnectionDetailView(repository: repository, familyID: familyID,+                            connection: GraphRow(id: account.id, name: account.name), readOnly: true)+                    }+                    if account.targetID != nil {+                        Text("Bring these accounts into the kept relationship as alternatives, then choose values in Review.")+                        Button("Bring accounts into the kept relationship for review") { review(account) }+                    } else {+                        Text("This relationship was archived because it would describe the child knowing themselves. " ++                             "The additional accounts can stay in history without creating a current self-relationship.")+                        Button("Keep these accounts in history") { review(account) }+                    }+                }+            }+            if conflicts.isEmpty && lateAccounts.isEmpty { Text("No competing merges or late relationship accounts need review.") }+            MemorySection("History") {+                NavigationLink("Read all merge history") { PersonMergeHistoryView(repository: repository, familyID: familyID) }+            }+        }+        .navigationTitle("Review merges")+        .task { reload() }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in reload() }+        .confirmationDialog("Show separate identities and keep current references?", isPresented: $showingConfirmation) {+            Button("Recover separate people") {+                guard let preview = confirming else { return }+                do { try repository.recoverCompetingMerges(preview); confirming = nil; reload() } catch {+                    failure = error.localizedDescription+                }+            }+        }+        .graphFailure($failure)+    }++    private func review(_ account: LateMergeAccounts) {+        do { try repository.reviewLateMergeAccounts(account); reload() } catch { failure = error.localizedDescription }+    }++    private func reload() {+        do {+            let conflicts = try repository.mergeConflicts(in: familyID)+            let accounts = try repository.lateMergeAccounts(in: familyID)+            self.conflicts = conflicts; lateAccounts = accounts+        } catch { failure = error.localizedDescription }+    }+}
Halo Family/Halo Family/MyApp.swift Modified +6 / -0
diff --git a/Halo Family/Halo Family/MyApp.swift b/Halo Family/Halo Family/MyApp.swiftindex e047ba3..27ff629 100644--- a/Halo Family/Halo Family/MyApp.swift	+++ b/Halo Family/Halo Family/MyApp.swift	@@ -1,6 +1,12 @@ import SwiftUI  @main struct MyApp: App {+    #if os(iOS)+    @UIApplicationDelegateAdaptor(HaloApplicationDelegate.self) private var delegate+    #elseif os(macOS)+    @NSApplicationDelegateAdaptor(HaloApplicationDelegate.self) private var delegate+    #endif+     var body: some Scene {         WindowGroup {             ContentView()
Halo Family/Halo Family/NativeContactPicker.swift Added +68 / -0
diff --git a/Halo Family/Halo Family/NativeContactPicker.swift b/Halo Family/Halo Family/NativeContactPicker.swiftnew file mode 100644index 0000000..7963cf5--- /dev/null+++ b/Halo Family/Halo Family/NativeContactPicker.swift	@@ -0,0 +1,68 @@+import Contacts+import ContactsUI+import SwiftUI++struct ContactSelection {+    let identifier: String+    let label: String+    init(identifier: String, label: String) { self.identifier = identifier; self.label = label }+    init(_ contact: CNContact) {+        identifier = contact.identifier+        let given = contact.isKeyAvailable(CNContactGivenNameKey) ? contact.givenName : ""+        let family = contact.isKeyAvailable(CNContactFamilyNameKey) ? contact.familyName : ""+        let nickname = contact.isKeyAvailable(CNContactNicknameKey) ? contact.nickname : ""+        let names = [given, family].filter { !$0.isEmpty }.joined(separator: " ")+        label = names.isEmpty ? (nickname.isEmpty ? "Linked Apple Contact" : nickname) : names+    }+}++#if os(macOS)+import AppKit++struct MacContactPickerButton: NSViewRepresentable {+    let selected: (ContactSelection) -> Void+    func makeCoordinator() -> Coordinator { Coordinator(selected: selected) }+    func makeNSView(context: Context) -> NSButton {+        let button = NSButton(title: "Link an existing contact", target: context.coordinator, action: #selector(Coordinator.pick(_:)))+        button.bezelStyle = .rounded+        return button+    }+    func updateNSView(_ view: NSButton, context: Context) {+        context.coordinator.selected = selected; view.isEnabled = context.environment.isEnabled+    }+    static func dismantleNSView(_ view: NSButton, coordinator: Coordinator) { coordinator.picker?.close() }++    @MainActor final class Coordinator: NSObject, CNContactPickerDelegate {+        var selected: (ContactSelection) -> Void+        var picker: CNContactPicker?+        init(selected: @escaping (ContactSelection) -> Void) { self.selected = selected }+        @objc func pick(_ sender: NSButton) {+            guard picker == nil else { return }+            let picker = CNContactPicker(); picker.delegate = self+            self.picker = picker+            picker.showRelative(to: sender.bounds, of: sender, preferredEdge: .maxY)+        }+        func contactPicker(_ picker: CNContactPicker, didSelect contact: CNContact) { selected(ContactSelection(contact)) }+        func contactPickerDidClose(_ picker: CNContactPicker) { self.picker = nil }+    }+}+#else+struct NativeContactPicker: UIViewControllerRepresentable {+    let completed: (ContactSelection?) -> Void+    func makeCoordinator() -> Coordinator { Coordinator(completed: completed) }+    func makeUIViewController(context: Context) -> CNContactPickerViewController {+        let picker = CNContactPickerViewController()+        picker.delegate = context.coordinator+        picker.predicateForSelectionOfContact = NSPredicate(value: true)+        return picker+    }+    func updateUIViewController(_ controller: CNContactPickerViewController, context: Context) {}++    @MainActor final class Coordinator: NSObject, CNContactPickerDelegate {+        let completed: (ContactSelection?) -> Void+        init(completed: @escaping (ContactSelection?) -> Void) { self.completed = completed }+        func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) { completed(ContactSelection(contact)) }+        func contactPickerDidCancel(_ picker: CNContactPickerViewController) { completed(nil) }+    }+}+#endif
Halo Family/Halo Family/PeopleView.swift Added +257 / -0
diff --git a/Halo Family/Halo Family/PeopleView.swift b/Halo Family/Halo Family/PeopleView.swiftnew file mode 100644index 0000000..a79fa8c--- /dev/null+++ b/Halo Family/Halo Family/PeopleView.swift	@@ -0,0 +1,257 @@+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 includeArchived = false+    @State private var name = ""+    @State private var failure: String?++    var body: some View {+        Form {+            Section {+                Toggle("Needs review only", isOn: $reviewOnly)+                Toggle("Include archived people", isOn: $includeArchived)+                ForEach(people) { person in+                    NavigationLink {+                        PersonDetailView(repository: repository, familyID: familyID, personID: person.id)+                    } label: {+                        VStack(alignment: .leading) {+                            Text(person.name)+                            if person.isArchived { Text("Archived").font(.caption).foregroundStyle(.secondary) }+                        }+                    }+                }+                if people.isEmpty { Text("No people match this view.").foregroundStyle(.secondary) }+            }+            Section("Add a person") {+                TextField("Name or description", text: $name)+                Button("Add person") {+                    perform {+                        _ = try repository.addPerson(name: name, familyID: familyID)+                        name = ""+                    }+                }+                .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+            }+            Section("History") {+                NavigationLink("Merge history") { PersonMergeHistoryView(repository: repository, familyID: familyID) }+            }+        }+        .navigationTitle("People")+        .searchable(text: $search, prompt: "Names, titles, roles or Contexts")+        .task { perform {} }+        .onChange(of: search) { perform {} }+        .onChange(of: reviewOnly) { 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()+            people = try repository.people(in: familyID, search: search, needsReview: reviewOnly, includeArchived: includeArchived)+        } 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 givenName = ""+    @State private var familyName = ""+    @State private var needsReview = false+    @State private var children: [GraphRow] = []+    @State private var connections: [GraphRow] = []+    @State private var childID: NSManagedObjectID?+    @State private var failure: String?+    @State private var loaded = false+    @State private var baseline: PersonDetail?+    @State private var photoID: NSManagedObjectID?+    @State private var sensitive: SensitiveSnapshot?+    @State private var editingSensitive = false+    @State private var events: [EventRow] = []+    @State private var merging = false+    @State private var mergedIntoID: NSManagedObjectID?+    @State private var isArchived = false+    @State private var mergeConflict = false+    @State private var contextRoles: [PersonContextRoleRow] = []+    @State private var editingRole: ContextPersonRow?++    var body: some View {+        MemoryForm {+            if mergeConflict {+                MemorySection("Competing merges") {+                    Text("Different merge accounts involve this person. Review them before making further changes.")+                    NavigationLink("Review merges") { MergeConflictReviewView(repository: repository, familyID: familyID) }+                }+            }+            if let mergedIntoID {+                MemorySection("Merged record") {+                    Text("This earlier record is retained in merge history.")+                    NavigationLink("Open the kept person") {+                        PersonDetailView(repository: repository, familyID: familyID, personID: mergedIntoID)+                    }+                }+            }+            MemorySection("Person") {+                if let photoID { AssetThumbnail(assets: AssetRepository(stack: repository.stack), assetID: photoID).id(photoID) }+                TextField("Name or description", text: $name)+                DisclosureGroup("Structured name (optional)") {+                    MemoryField("Given name") { TextField("Given name", text: $givenName) }+                    MemoryField("Family name") { TextField("Family name", text: $familyName) }+                    Text("These names help search. Your display name or description remains independent.")+                        .font(.caption).foregroundStyle(.secondary)+                }+                TextField("Notes", text: $notes, axis: .vertical)+                Toggle("Needs review", isOn: $needsReview)+                Button("Save details") {+                    guard let baseline else { return }+                    perform {+                        try repository.updatePerson(personID,+                            input: PersonInput(name: name, notes: notes, needsReview: needsReview,+                                               givenName: givenName, familyName: familyName),+                            expected: baseline)+                        let saved = try repository.person(personID)+                        self.baseline = saved+                        name = saved.name+                        notes = saved.notes+                        givenName = saved.givenName+                        familyName = saved.familyName+                        needsReview = saved.needsReview+                    }+                }+                .disabled(!loaded || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+                DisclosureGroup("Photo") {+                    PhotoImportControls(repository: repository, personID: personID)+                    if photoID != nil {+                        Button("Remove primary photo") { perform { try repository.removePhoto(personID) } }+                    }+                }+            }+            .disabled(isArchived || mergedIntoID != nil || mergeConflict)+            if mergedIntoID == nil && !mergeConflict {+                MemorySection("Archive and restore") {+                    ArchiveControls(repository: repository, recordID: personID, subject: "person")+                }+            }+            MemorySection("Relationships") {+                NavigationLink("Apple Contacts") { AppleContactsView(repository: repository, personID: personID) }+                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(isArchived || childID == nil)+            }+            .disabled(mergedIntoID != nil || mergeConflict)+            if !contextRoles.isEmpty {+                MemorySection("Context roles") {+                    ForEach(contextRoles) { role in+                        VStack(alignment: .leading) {+                            Text(role.contextPath)+                            Text(role.association.role.isEmpty ? "Role not recorded" : role.association.role)+                            if role.isArchived { Text("Archived Context").foregroundStyle(.secondary) }+                            if let start = role.association.startedAt { Text("From \(start.formatted(date: .abbreviated, time: .omitted))") }+                            if let end = role.association.endedAt { Text("Until \(end.formatted(date: .abbreviated, time: .omitted))") }+                            Button("Edit role or dates") { editingRole = role.association }+                                .disabled(isArchived || mergedIntoID != nil || mergeConflict)+                        }+                    }+                }+            }+            if !events.isEmpty {+                MemorySection("Social event history") {+                    ForEach(events) { event in+                        NavigationLink(event.label) { EventDetailView(repository: repository, familyID: familyID, eventID: event.id) }+                    }+                }+            }+        }+        .navigationTitle(name.isEmpty ? "Person" : name)+        .toolbar {+            Menu {+                if !isArchived && mergedIntoID == nil && !mergeConflict {+                    Button("Sensitive details") {+                        perform { sensitive = try repository.sensitiveDetails(personID); editingSensitive = true }+                    }+                    Button("Merge with another person") { merging = true }+                }+            } label: { Image(systemName: "ellipsis") }+        }+        .sheet(isPresented: $editingSensitive, onDismiss: { perform {} }, content: {+            if let sensitive { SensitiveDetailsView(repository: repository, personID: personID, initial: sensitive) }+        })+        .sheet(isPresented: $merging, onDismiss: { perform {} }, content: {+            PersonMergeView(repository: repository, familyID: familyID, sourceID: personID)+        })+        .sheet(item: $editingRole, onDismiss: { perform {} }, content: {+            ContextRoleEditor(repository: repository, original: $0)+        })+        .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)+            isArchived = current.isArchived+            if baseline == nil || (name == baseline?.name && notes == baseline?.notes && needsReview == baseline?.needsReview &&+                                   givenName == baseline?.givenName && familyName == baseline?.familyName) {+                name = current.name+                notes = current.notes+                givenName = current.givenName+                familyName = current.familyName+                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)+            contextRoles = try repository.personContextRoles(personID)+            mergeConflict = try repository.mergeConflicts(in: familyID).contains { $0.people.contains { $0.id == personID } }+            mergedIntoID = mergeConflict ? nil : try repository.mergedPersonTarget(personID)+            loaded = true+        } 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 ?? "") }+    }+}
Halo Family/Halo Family/Persistence/AccessPermissions.swift Added +210 / -0
diff --git a/Halo Family/Halo Family/Persistence/AccessPermissions.swift b/Halo Family/Halo Family/Persistence/AccessPermissions.swiftnew file mode 100644index 0000000..ced7e98--- /dev/null+++ b/Halo Family/Halo Family/Persistence/AccessPermissions.swift	@@ -0,0 +1,210 @@+import CloudKit+import CoreData+import Foundation++nonisolated extension StoreAccess {+    static func ambiguousFamilies(in context: NSManagedObjectContext) throws -> Set<FamilyAccessID> {+        var seen = Set<FamilyAccessID>(), repeated = Set<FamilyAccessID>()+        for root in try context.fetch(NSFetchRequest<NSManagedObject>(entityName: "FamilySpace")) {+            guard let id = root.value(forKey: "id") as? UUID,+                  let filename = root.objectID.persistentStore?.url?.lastPathComponent else { continue }+            let key = FamilyAccessID(family: id, shared: filename == "Shared.sqlite")+            if !seen.insert(key).inserted { repeated.insert(key) }+        }+        return repeated+    }++    static func identity(_ object: NSManagedObject, checkingDuplicates: Bool = true) throws -> FamilyAccessID {+        let committedFamily = object.isDeleted && object.entity.name != "FamilySpace" ?+            object.committedValues(forKeys: ["familySpace"])["familySpace"] as? NSManagedObject : nil+        let family = object.entity.name == "FamilySpace" ? object :+            (object.value(forKey: "familySpace") as? NSManagedObject ?? committedFamily)+        guard let family, let id = family.value(forKey: "id") as? UUID,+              let filename = family.objectID.persistentStore?.url?.lastPathComponent,+              ["Private.sqlite", "Shared.sqlite"].contains(filename) else { throw GraphError.invalidReference }+        if checkingDuplicates {+            guard let context = family.managedObjectContext else { throw GraphError.invalidReference }+            let request = NSFetchRequest<NSManagedObject>(entityName: "FamilySpace")+            request.predicate = NSPredicate(format: "id == %@", id as NSUUID)+            request.affectedStores = family.objectID.persistentStore.map { [$0] }+            guard try context.count(for: request) == 1 else { throw AccessError.familyUnavailable }+        }+        return FamilyAccessID(family: id, shared: filename == "Shared.sqlite")+    }++    func check(_ object: NSManagedObject, writing: Bool = false) throws {+        try check()+        let id = try Self.identity(object)+        try check(family: id.family, shared: id.shared, writing: writing)+    }+}++/// Records a revoked share separately from Core Data, where a framework import may remove its rows.+/// Only an explicit successful invitation for that share can remove this denial.+nonisolated struct ShareDenials: Codable {+    var shares: Set<String> = []+    var permissions: [String: Bool] = [:]++    static func key(_ id: CKRecord.ID) -> String {+        [id.recordName, id.zoneID.zoneName, id.zoneID.ownerName].joined(separator: "\n")+    }++    static func read(in directory: URL) throws -> ShareDenials {+        let file = directory.appendingPathComponent("ShareDenials.json")+        let handle: FileHandle+        do { handle = try FileHandle(forReadingFrom: file) } catch let error as CocoaError+            where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile {+            return ShareDenials()+        }+        defer { try? handle.close() }+        var data = Data()+        while let chunk = try handle.read(upToCount: 65_536), !chunk.isEmpty {+            data.append(chunk)+            guard data.count <= 1_000_000 else { throw AccessError.familyUnavailable }+        }+        return try JSONDecoder().decode(Self.self, from: data)+    }++    func save(in directory: URL) throws {+        let data = try JSONEncoder().encode(self)+        guard data.count <= 1_000_000 else { throw AccessError.familyUnavailable }+        try data.write(to: directory.appendingPathComponent("ShareDenials.json"), options: .atomic)+    }+}++@MainActor+extension PersistenceStack {+    func fetch(_ request: NSFetchRequest<NSManagedObject>) throws -> [NSManagedObject] {+        guard let permissions = try access.readableFamilies() else { return try container.viewContext.fetch(request) }+        let allowed = try permissions.subtracting(StoreAccess.ambiguousFamilies(in: container.viewContext))+        var rows: [NSManagedObject] = []+        for (store, shared) in [(privateStore, false), (sharedStore, true)] {+            guard request.affectedStores == nil || request.affectedStores?.contains(store) == true else { continue }+            let ids = allowed.filter { $0.shared == shared }.map(\.family)+            guard !ids.isEmpty else { continue }+            guard let scoped = request.copy() as? NSFetchRequest<NSManagedObject> else { throw GraphError.invalidReference }+            let path = request.entityName == "FamilySpace" ? "id" : "familySpace.id"+            let permission = NSPredicate(format: "%K IN %@", path, ids)+            scoped.predicate = request.predicate.map { NSCompoundPredicate(andPredicateWithSubpredicates: [$0, permission]) } ?? permission+            scoped.affectedStores = [store]+            scoped.fetchOffset = 0; scoped.fetchLimit = 0+            rows += try container.viewContext.fetch(scoped)+        }+        rows.sort { left, right in+            for descriptor in request.sortDescriptors ?? [] {+                let order = descriptor.compare(left, to: right)+                if order != .orderedSame { return order == .orderedAscending }+            }+            return false+        }+        let result = Array(rows.dropFirst(request.fetchOffset))+        return request.fetchLimit == 0 ? result : Array(result.prefix(request.fetchLimit))+    }++    func refreshAccess() throws {+        try access.check()+        guard let accountScope, let directory = privateStore.url?.deletingLastPathComponent(), role == .host else { return }+        let request = NSFetchRequest<NSManagedObject>(entityName: "FamilySpace")+        let families = try container.viewContext.fetch(request)+        let ambiguous = try StoreAccess.ambiguousFamilies(in: container.viewContext)+        var readable = Set<FamilyAccessID>()+        var writable = Set<FamilyAccessID>()+        let denials = try ShareDenials.read(in: directory)+        let verificationNeeded = FileManager.default.fileExists(atPath: directory.appendingPathComponent("SharedVerificationRequired").path)+        let cloud = container as? NSPersistentCloudKitContainer+        let sharedIDs = families.filter { $0.objectID.persistentStore == sharedStore }.map(\.objectID)+        let shares = sharedIDs.isEmpty ? [:] : try cloud?.fetchShares(matching: sharedIDs) ?? [:]+        for family in families {+            guard let uuid = family.value(forKey: "id") as? UUID else { continue }+            let key = FamilyAccessID(family: uuid, shared: family.objectID.persistentStore == sharedStore)+            guard !ambiguous.contains(key) else { continue }+            let id = key+            if family.objectID.persistentStore == privateStore {+                readable.insert(id); writable.insert(id)+            } else if !verificationNeeded, let share = shares[family.objectID], let participant = share.currentUserParticipant {+                let key = ShareDenials.key(share.recordID)+                guard participant.acceptanceStatus == .accepted, participant.permission != .none,+                      !denials.shares.contains(key) else { continue }+                readable.insert(id)+                if participant.permission == .readWrite, denials.permissions[key] != false,+                   cloud?.canUpdateRecord(forManagedObjectWith: family.objectID) == true {+                    writable.insert(id)+                }+            }+        }+        let value = ExtensionAccess(version: 1, namespace: accountScope.namespace,+                                    readable: readable, writable: writable, locked: false)+        try value.save(in: directory)+        access.update(readable: readable, writable: writable)+    }++    func didAcceptInvitation(_ shareID: CKRecord.ID) throws {+        try access.check()+        shareVerificationGeneration = UUID()+        guard let directory = privateStore.url?.deletingLastPathComponent() else { throw PersistenceError.storesUnavailable }+        var denials = try ShareDenials.read(in: directory)+        denials.shares.remove(ShareDenials.key(shareID))+        denials.permissions.removeValue(forKey: ShareDenials.key(shareID))+        try denials.save(in: directory)+        try refreshAccess()+    }++    func revalidateSharedAccess(ifRequired: Bool = false) async {+        guard role == .host, accountScope?.mirrorsCloud == true, let directory = privateStore.url?.deletingLastPathComponent(),+              let cloud = container as? NSPersistentCloudKitContainer else { return }+        let marker = directory.appendingPathComponent("SharedVerificationRequired")+        if ifRequired && !FileManager.default.fileExists(atPath: marker.path) { return }+        do {+            try access.check()+            if !ifRequired {+                shareVerificationGeneration = UUID()+                try Data().write(to: marker, options: .atomic)+                try refreshAccess()+                NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: container)+            }+            guard !verifyingShares else { verifySharesAgain = true; return }+            verifyingShares = true+            defer {+                verifyingShares = false+                if verifySharesAgain {+                    verifySharesAgain = false+                    Task { @MainActor [weak self] in await self?.revalidateSharedAccess(ifRequired: true) }+                }+            }+            let generation = shareVerificationGeneration+            let request = NSFetchRequest<NSManagedObject>(entityName: "FamilySpace")+            request.affectedStores = [sharedStore]+            let ids = try container.viewContext.fetch(request).map(\.objectID)+            var denials = try ShareDenials.read(in: directory)+            let cached = ids.isEmpty ? [:] : try cloud.fetchShares(matching: ids)+            let shares = Set(cached.values.map(\.recordID))+            let database = CKContainer(identifier: StoreConfiguration.cloudContainer).sharedCloudDatabase+            for shareID in shares {+                let key = ShareDenials.key(shareID)+                do {+                    let record = try await database.record(for: shareID)+                    try access.check()+                    guard let share = record as? CKShare, let participant = share.currentUserParticipant,+                          participant.acceptanceStatus == .accepted, participant.permission != .none else {+                        denials.shares.insert(key)+                        continue+                    }+                    denials.permissions[key] = participant.permission == .readWrite+                    // A previous confirmed removal stays denied until explicit successful reinvitation.+                } catch {+                    try access.check()+                    if CloudAccessFailure.removesAccess(error) || (error as? CKError)?.code == .unknownItem {+                        denials.shares.insert(key)+                    } else { throw error }+                }+            }+            try access.check()+            guard generation == shareVerificationGeneration else { throw AccessError.familyUnavailable }+            try denials.save(in: directory)+            if FileManager.default.fileExists(atPath: marker.path) { try FileManager.default.removeItem(at: marker) }+            try refreshAccess()+            shareVerificationSucceeded()+            NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: container)+        } catch { shareVerificationFailed(error) }+    }+}
Halo Family/Halo Family/Persistence/AccountScope.swift Added +153 / -0
diff --git a/Halo Family/Halo Family/Persistence/AccountScope.swift b/Halo Family/Halo Family/Persistence/AccountScope.swiftnew file mode 100644index 0000000..f4c97e7--- /dev/null+++ b/Halo Family/Halo Family/Persistence/AccountScope.swift	@@ -0,0 +1,153 @@+import CloudKit+import CryptoKit+import Foundation++nonisolated enum AccountScope: Equatable, Sendable {+    case local+    case cloud(String)++    var namespace: String {+        switch self {+        case .local: "local"+        case .cloud(let hash): "account-" + hash+        }+    }++    var mirrorsCloud: Bool { if case .cloud = self { return true }; return false }++    static func verifiedCloud(userRecordName: String, environment: String = environment) throws -> AccountScope {+        guard !userRecordName.isEmpty else { throw AccessError.unverifiedAccount }+        let input = [StoreConfiguration.cloudContainer, environment, userRecordName].joined(separator: "\n")+        return .cloud(SHA256.hash(data: Data(input.utf8)).map { String(format: "%02x", $0) }.joined())+    }++    static var environment: String {+        #if DEBUG+        "development"+        #else+        "production"+        #endif+    }++    func directory(in root: URL) -> URL { root.appendingPathComponent("Accounts/" + namespace, isDirectory: true) }++    static func current(container: CKContainer = CKContainer(identifier: StoreConfiguration.cloudContainer)) async throws -> AccountScope {+        switch try await container.accountStatus() {+        case .noAccount: return .local+        case .available:+            let user = try await container.userRecordID()+            return try verifiedCloud(userRecordName: user.recordName)+        case .restricted, .couldNotDetermine, .temporarilyUnavailable: throw AccessError.unverifiedAccount+        @unknown default: throw AccessError.unverifiedAccount+        }+    }+}++nonisolated enum AccessError: LocalizedError {+    case unverifiedAccount+    case accountChanged+    case familyUnavailable+    case readOnlyFamily++    var errorDescription: String? {+        switch self {+        case .unverifiedAccount:+            "Your iCloud account could not be verified. Saved account data stays locked. Try again when verification is available."+        case .accountChanged: "Account access changed. Reopen Halo Family to verify the current account."+        case .familyUnavailable:+            "Access to this family is unavailable. Its saved cache stays locked; ask the owner for a new invitation."+        case .readOnlyFamily: "This family is currently read-only."+        }+    }+}++/// This signal can lock a session directly from an arbitrary account-notification queue.+/// It is checked again by background writers at their save boundary.+nonisolated final class StoreAccess: @unchecked Sendable {+    private let lock = NSLock()+    private let saveLock = NSLock()+    private var locked = false+    private var readable: Set<FamilyAccessID>?+    private var writable: Set<FamilyAccessID>?+    private var extensionSource: (directory: URL, namespace: String)?++    @discardableResult+    func invalidate() -> Bool {+        saveLock.withLock {+            lock.withLock {+                guard !locked else { return false }+                locked = true+                return true+            }+        }+    }+    func update(readable: Set<FamilyAccessID>, writable: Set<FamilyAccessID>) {+        saveLock.withLock {+            lock.withLock { self.readable = readable; self.writable = writable }+        }+    }++    func watchExtensionAccess(directory: URL, namespace: String) {+        lock.withLock { extensionSource = (directory, namespace) }+    }++    /// Called while holding the lock so an older read cannot overwrite a newer permission snapshot.+    private func refreshExtensionAccess() throws {+        guard let source = extensionSource else { return }+        let value = try ExtensionAccess.read(in: source.directory, namespace: source.namespace)+        readable = value.readable+        writable = value.writable+    }++    func check(family: UUID? = nil, shared: Bool = false, writing: Bool = false) throws {+        try lock.withLock {+            try refreshExtensionAccess()+            guard !locked else { throw AccessError.accountChanged }+            guard let family else { return }+            let identity = FamilyAccessID(family: family, shared: shared)+            if let readable, !readable.contains(identity) { throw AccessError.familyUnavailable }+            if writing, let writable, !writable.contains(identity) { throw AccessError.readOnlyFamily }+        }+    }++    func readableFamilies() throws -> Set<FamilyAccessID>? {+        try lock.withLock {+            try refreshExtensionAccess()+            guard !locked else { throw AccessError.accountChanged }+            return readable+        }+    }++    /// Linearizes permission validation and the SQLite save against this process's invalidation signal.+    /// Other processes and framework mirroring still require the account/device release gate.+    func save(families: Set<FamilyAccessID>, _ operation: () throws -> Void) throws {+        try saveLock.withLock {+            try lock.withLock {+                try refreshExtensionAccess()+                guard !locked else { throw AccessError.accountChanged }+                for family in families {+                    if let readable, !readable.contains(family) { throw AccessError.familyUnavailable }+                    if let writable, !writable.contains(family) { throw AccessError.readOnlyFamily }+                }+            }+            try operation()+        }+    }+}++/// Arm the signal before the first asynchronous identity lookup or store attachment.+nonisolated final class AccountOpeningGuard: @unchecked Sendable {+    let container = CKContainer(identifier: StoreConfiguration.cloudContainer)+    let access: StoreAccess+    private let token: NSObjectProtocol++    init() {+        let access = StoreAccess()+        self.access = access+        token = NotificationCenter.default.addObserver(forName: .CKAccountChanged, object: nil, queue: nil) { _ in+            access.invalidate()+        }+    }++    deinit { NotificationCenter.default.removeObserver(token) }+}
Halo Family/Halo Family/Persistence/ArchiveRepository.swift Added +56 / -0
diff --git a/Halo Family/Halo Family/Persistence/ArchiveRepository.swift b/Halo Family/Halo Family/Persistence/ArchiveRepository.swiftnew file mode 100644index 0000000..3a71a6c--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ArchiveRepository.swift	@@ -0,0 +1,56 @@+import CoreData+import Foundation++struct ArchiveSnapshot: Equatable {+    let id: NSManagedObjectID+    let entity: String+    let name: String+    let archivedAt: Date?+    let modifiedAt: Date?+    var isArchived: Bool { archivedAt != nil }+}++@MainActor+extension FamilyRepository {+    func archiveSnapshot(_ id: NSManagedObjectID) throws -> ArchiveSnapshot {+        guard let entity = id.entity.name, ["Person", "ChildProfile", "PersonGroup"].contains(entity) else {+            throw GraphError.invalidReference+        }+        return try archiveSnapshot(readable(id, entity: entity))+    }++    func setArchived(_ expected: ArchiveSnapshot, archived: Bool) throws {+        guard ["Person", "ChildProfile", "PersonGroup"].contains(expected.entity) else { throw GraphError.invalidReference }+        _ = try write { context in+            let object = try record(expected.id, entity: expected.entity, in: context, allowArchived: true)+            guard try archiveSnapshot(object) == expected else { throw MemoryError.changed }+            object.setValue(archived ? expected.archivedAt ?? Date() : nil, forKey: "archivedAt")+            if object.entity.attributesByName["modifiedAt"] != nil { object.setValue(Date(), forKey: "modifiedAt") }+            return object+        }+    }++    func canCapture(_ childID: NSManagedObjectID) -> Bool {+        do { try validateCaptureChild(readable(childID, entity: "ChildProfile")); return true } catch { return false }+    }++    func canArchive(_ snapshot: ArchiveSnapshot) -> Bool {+        guard stack.role != .widget else { return false }+        do {+            let object = try readable(snapshot.id, entity: snapshot.entity)+            try stack.access.check(object, writing: true)+            if object.entity.relationshipsByName["mergedInto"] != nil, object.value(forKey: "mergedInto") != nil { return false }+            return true+        } catch { return false }+    }++    private func archiveSnapshot(_ object: NSManagedObject) throws -> ArchiveSnapshot {+        guard let entity = object.entity.name, object.entity.attributesByName["archivedAt"] != nil else {+            throw GraphError.modelUnavailable+        }+        let nameKey = entity == "Person" ? "displayName" : (entity == "ChildProfile" ? "person.displayName" : "name")+        return ArchiveSnapshot(id: object.objectID, entity: entity, name: object.value(forKeyPath: nameKey) as? String ?? "Unnamed",+            archivedAt: object.value(forKey: "archivedAt") as? Date,+            modifiedAt: object.entity.attributesByName["modifiedAt"] != nil ? object.value(forKey: "modifiedAt") as? Date : nil)+    }+}
Halo Family/Halo Family/Persistence/AssetRepository.swift Modified +130 / -5
diff --git a/Halo Family/Halo Family/Persistence/AssetRepository.swift b/Halo Family/Halo Family/Persistence/AssetRepository.swiftindex 93540c2..6ad13f5 100644--- a/Halo Family/Halo Family/Persistence/AssetRepository.swift	+++ b/Halo Family/Halo Family/Persistence/AssetRepository.swift	@@ -1,24 +1,32 @@ 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 {+        try stack.access.check()+        let access = stack.access+        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)+            try access.check(family, writing: true)             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,18 +38,135 @@ final class AssetRepository {             }             asset.setValue(data, forKey: "data")             asset.setValue(Date(), forKey: "modifiedAt")-            try context.save()-            return asset.objectID+            if asset.entity.attributesByName["contentRevision"] != nil { asset.setValue(UUID(), forKey: "contentRevision") }+            let inserted = Array(context.insertedObjects)+            let updated = Array(context.updatedObjects)+            let identity = try StoreAccess.identity(family)+            try access.save(families: [identity]) { try context.save() }+            return (asset.objectID, inserted.map(\.objectID), updated.map(\.objectID))+        }+        try publish(inserted: result.1, updated: result.2)+        return result.0+    }++    func importPhoto(_ data: Data, filename: String, personID: NSManagedObjectID) async throws -> NSManagedObjectID {+        guard stack.role != .widget else { throw GraphError.readOnly }+        let prepared = try await Task.detached(priority: .userInitiated) {+            try ImageImport.prepare(data, filename: filename, photo: true)+        }.value+        return try await importAsset(prepared, ownerID: personID, photo: true)+    }++    func importAttachment(_ data: Data, filename: String, eventID: NSManagedObjectID) async throws -> NSManagedObjectID {+        guard stack.role != .widget else { throw GraphError.readOnly }+        let prepared = try await Task.detached(priority: .userInitiated) {+            try ImageImport.prepare(data, filename: filename, photo: false)+        }.value+        return try await importAsset(prepared, ownerID: eventID, photo: false)+    }++    private func importAsset(_ prepared: PreparedAsset, ownerID: NSManagedObjectID, photo: Bool) async throws -> NSManagedObjectID {+        try stack.access.check()+        let access = stack.access+        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 access.check(owner, writing: true)+            try Self.requireEditable(owner, cloud: cloud)+            if photo, owner.value(forKey: "mergedInto") != nil || owner.value(forKey: "archivedAt") != nil { throw MergeError.changed }+            guard let family = owner.value(forKey: "familySpace") as? NSManagedObject,+                  let store = family.objectID.persistentStore, store == ownerID.persistentStore else { throw GraphError.differentFamily }+            try Self.requireEditable(family, cloud: cloud)+            let asset = NSEntityDescription.insertNewObject(forEntityName: "Asset", into: context)+            context.assign(asset, to: store)+            asset.setValue(UUID(), forKey: "id")+            asset.setValue(family, forKey: "familySpace")+            asset.setValue(prepared.data, forKey: "data")+            asset.setValue(prepared.filename, forKey: "filename")+            asset.setValue(prepared.contentType, forKey: "contentType")+            asset.setValue(prepared.data.count, forKey: "byteCount")+            asset.setValue(prepared.width, forKey: "pixelWidth")+            asset.setValue(prepared.height, forKey: "pixelHeight")+            asset.setValue(photo ? "personPhoto" : "eventAttachment", forKey: "kind")+            asset.setValue(Date(), forKey: "createdAt")+            asset.setValue(Date(), forKey: "modifiedAt")+            asset.setValue(UUID(), forKey: "contentRevision")+            if photo {+                owner.setValue(asset, forKey: "primaryPhoto")+                owner.setValue(Date(), forKey: "modifiedAt")+            } else {+                let attachment = NSEntityDescription.insertNewObject(forEntityName: "EventAttachment", into: context)+                context.assign(attachment, to: store)+                attachment.setValue(UUID(), forKey: "id")+                attachment.setValue(family, forKey: "familySpace")+                attachment.setValue(owner, forKey: "event")+                attachment.setValue(asset, forKey: "asset")+                attachment.setValue(prepared.filename, forKey: "title")+                attachment.setValue("document", forKey: "kind")+                attachment.setValue(Date(), forKey: "createdAt")+            }+            let inserted = Array(context.insertedObjects)+            let updated = Array(context.updatedObjects)+            try Task.checkCancellation()+            let identity = try StoreAccess.identity(family)+            try access.save(families: [identity]) { try context.save() }+            return (asset.objectID, inserted.map(\.objectID), updated.map(\.objectID))+        }+        try publish(inserted: result.1, updated: result.2)+        return result.0+    }++    private func publish(inserted: [NSManagedObjectID], updated: [NSManagedObjectID]) throws {+        try stack.access.check()+        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 {+        try stack.access.check()+        let access = stack.access+        let context = stack.container.newBackgroundContext()+        let value = try await context.perform {+            guard assetID.entity.name == "Asset", !assetID.isTemporaryID else { throw GraphError.invalidReference }+            try access.check(context.existingObject(with: assetID))+            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"] ?? "")"+        }+        _ = try FamilyRepository(stack: stack).readable(assetID, entity: "Asset")+        return value+    }++    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 }         }     }      func data(for assetID: NSManagedObjectID) async throws -> Data {+        try stack.access.check()+        let access = stack.access         let context = stack.container.newBackgroundContext()-        return try await context.perform {+        let value = try await context.perform {             guard assetID.entity.name == "Asset", !assetID.isTemporaryID else { throw GraphError.invalidReference }             let asset = try context.existingObject(with: assetID)+            try access.check(asset)             guard let data = asset.value(forKey: "data") as? Data else { throw GraphError.invalidReference }             return data         }+        _ = try FamilyRepository(stack: stack).readable(assetID, entity: "Asset")+        return value     } }
Halo Family/Halo Family/Persistence/BackupArchive.swift Added +224 / -0
diff --git a/Halo Family/Halo Family/Persistence/BackupArchive.swift b/Halo Family/Halo Family/Persistence/BackupArchive.swiftnew file mode 100644index 0000000..8dc7650--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupArchive.swift	@@ -0,0 +1,224 @@+import Foundation++nonisolated enum BackupError: LocalizedError {+    case invalidArchive+    case unsupportedVersion+    case missingIdentity+    case familyExists+    case changed+    case tooLarge+    case importing++    var errorDescription: String? {+        switch self {+        case .invalidArchive: "This is not a valid Halo Family backup. No family data was changed."+        case .unsupportedVersion: "This backup uses an unsupported format or model version."+        case .missingIdentity: "A saved record has no stable identity. The backup was not created."+        case .familyExists: "This family already exists. Restore into an absent family or explicitly import a new copy."+        case .changed: "The backup or family changed. Preview it again before importing."+        case .tooLarge: "This backup exceeds the supported archive limits."+        case .importing: "Another family import is in progress. Wait for it to finish."+        }+    }+}++nonisolated struct BackupFile: Sendable {+    let name: String+    let url: URL+}++nonisolated struct ArchiveMember: Sendable {+    let name: String+    let size: UInt32+    let checksum: UInt32+    let offset: UInt32+}++/// A streaming, uncompressed ZIP32 codec for Halo's own versioned backup files.+/// No subprocess, external service, path extraction, encryption or executable content.+nonisolated enum BackupArchive {+    static let maximumBytes: UInt64 = 1_000_000_000+    private static let chunkSize = 65_536++    static func write(_ files: [BackupFile], to destination: URL,+                      check: () throws -> Void = { try Task.checkCancellation() }) throws {+        guard files.count <= 10_000, Set(files.map(\.name)).count == files.count else { throw BackupError.tooLarge }+        let partial = destination.deletingLastPathComponent().appendingPathComponent(UUID().uuidString + ".partial")+        guard FileManager.default.createFile(atPath: partial.path, contents: nil) else { throw BackupError.invalidArchive }+        defer { try? FileManager.default.removeItem(at: partial) }+        let handle = try FileHandle(forWritingTo: partial)+        defer { try? handle.close() }+        var directory: [ArchiveMember] = []+        for file in files {+            try check()+            try validName(file.name)+            let (size, checksum) = try measured(file.url, check: check)+            let position = try handle.offset()+            guard position + UInt64(size) < maximumBytes else { throw BackupError.tooLarge }+            let member = ArchiveMember(name: file.name, size: size, checksum: checksum, offset: UInt32(position))+            try handle.write(contentsOf: localHeader(member))+            let input = try FileHandle(forReadingFrom: file.url)+            defer { try? input.close() }+            var actual: UInt64 = 0+            var crc: UInt32 = .max+            while let bytes = try input.read(upToCount: chunkSize), !bytes.isEmpty {+                try check()+                actual += UInt64(bytes.count)+                guard actual <= UInt64(size) else { throw BackupError.changed }+                crc = CRC32.update(crc, bytes)+                try handle.write(contentsOf: bytes)+            }+            guard actual == UInt64(size), ~crc == checksum else { throw BackupError.changed }+            directory.append(member)+        }+        let start = try handle.offset()+        for member in directory { try handle.write(contentsOf: centralHeader(member)) }+        let end = try handle.offset()+        guard end + 22 <= maximumBytes else { throw BackupError.tooLarge }+        var footer = Data()+        footer.le32(0x06054b50); footer.le16(0); footer.le16(0)+        footer.le16(UInt16(directory.count)); footer.le16(UInt16(directory.count))+        footer.le32(UInt32(end - start)); footer.le32(UInt32(start)); footer.le16(0)+        try handle.write(contentsOf: footer)+        try handle.synchronize()+        try FileManager.default.moveItem(at: partial, to: destination)+    }++    static func members(in archive: URL) throws -> [ArchiveMember] {+        let handle = try FileHandle(forReadingFrom: archive)+        defer { try? handle.close() }+        let size = try handle.seekToEnd()+        guard size >= 22, size <= maximumBytes else { throw BackupError.tooLarge }+        try handle.seek(toOffset: size - 22)+        let footer = try exact(handle, count: 22)+        guard footer.u32(0) == 0x06054b50, footer.u16(4) == 0, footer.u16(6) == 0,+              footer.u16(8) == footer.u16(10), footer.u16(20) == 0 else { throw BackupError.invalidArchive }+        let count = Int(footer.u16(10))+        let length = UInt64(footer.u32(12)), offset = UInt64(footer.u32(16))+        guard offset + length == size - 22, count <= 10_000 else { throw BackupError.invalidArchive }+        try handle.seek(toOffset: offset)+        var members: [ArchiveMember] = []+        for _ in 0..<count {+            let header = try exact(handle, count: 46)+            guard header.u32(0) == 0x02014b50, header.u16(8) == 0x0800, header.u16(10) == 0,+                  header.u32(20) == header.u32(24), header.u16(34) == 0,+                  header.u16(30) == 0, header.u16(32) == 0 else { throw BackupError.unsupportedVersion }+            let nameBytes = try exact(handle, count: Int(header.u16(28)))+            guard let name = String(data: nameBytes, encoding: .utf8) else { throw BackupError.invalidArchive }+            try validName(name)+            _ = try exact(handle, count: Int(header.u16(30)) + Int(header.u16(32)))+            let member = ArchiveMember(name: name, size: header.u32(24), checksum: header.u32(16), offset: header.u32(42))+            guard UInt64(member.offset) < offset else { throw BackupError.invalidArchive }+            members.append(member)+        }+        guard try handle.offset() == offset + length, Set(members.map(\.name)).count == members.count else {+            throw BackupError.invalidArchive+        }+        try validateRanges(members, handle: handle, directoryOffset: offset)+        return members+    }++    private static func validateRanges(_ members: [ArchiveMember], handle: FileHandle, directoryOffset: UInt64) throws {+        var previousEnd: UInt64 = 0+        for member in members.sorted(by: { $0.offset < $1.offset }) {+            guard UInt64(member.offset) == previousEnd else { throw BackupError.invalidArchive }+            try handle.seek(toOffset: UInt64(member.offset))+            let local = try exact(handle, count: 30)+            guard local.u32(0) == 0x04034b50, local.u16(6) == 0x0800, local.u16(8) == 0,+                  local.u32(14) == member.checksum, local.u32(18) == member.size, local.u32(22) == member.size,+                  local.u16(28) == 0,+                  String(data: try exact(handle, count: Int(local.u16(26))), encoding: .utf8) == member.name else {+                throw BackupError.invalidArchive+            }+            previousEnd = try handle.offset() + UInt64(member.size)+            guard previousEnd <= directoryOffset else { throw BackupError.invalidArchive }+        }+        guard previousEnd == directoryOffset else { throw BackupError.invalidArchive }+    }++    static func read(_ member: ArchiveMember, from archive: URL, limit: Int) throws -> Data {+        guard UInt64(member.size) <= UInt64(limit) else { throw BackupError.tooLarge }+        let handle = try FileHandle(forReadingFrom: archive)+        defer { try? handle.close() }+        try handle.seek(toOffset: UInt64(member.offset))+        let header = try exact(handle, count: 30)+        guard header.u32(0) == 0x04034b50, header.u16(6) == 0x0800, header.u16(8) == 0,+              header.u32(14) == member.checksum, header.u32(18) == member.size, header.u32(22) == member.size else {+            throw BackupError.invalidArchive+        }+        let name = try exact(handle, count: Int(header.u16(26)))+        guard String(data: name, encoding: .utf8) == member.name else { throw BackupError.invalidArchive }+        _ = try exact(handle, count: Int(header.u16(28)))+        let data = try exact(handle, count: Int(member.size))+        guard ~CRC32.update(.max, data) == member.checksum else { throw BackupError.invalidArchive }+        return data+    }++    private static func measured(_ url: URL, check: () throws -> Void) throws -> (UInt32, UInt32) {+        let handle = try FileHandle(forReadingFrom: url)+        defer { try? handle.close() }+        var size: UInt64 = 0+        var checksum: UInt32 = .max+        while let bytes = try handle.read(upToCount: chunkSize), !bytes.isEmpty {+            try check()+            size += UInt64(bytes.count)+            guard size < maximumBytes else { throw BackupError.tooLarge }+            checksum = CRC32.update(checksum, bytes)+        }+        return (UInt32(size), ~checksum)+    }++    private static func validName(_ name: String) throws {+        let parts = name.split(separator: "/", omittingEmptySubsequences: false)+        guard !name.isEmpty, name.utf8.count <= 256, !name.contains("\\"), !name.contains("\0"),+              parts.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." }) else { throw BackupError.invalidArchive }+    }++    private static func exact(_ handle: FileHandle, count: Int) throws -> Data {+        var result = Data()+        while result.count < count {+            try Task.checkCancellation()+            guard let data = try handle.read(upToCount: min(chunkSize, count - result.count)), !data.isEmpty else {+                throw BackupError.invalidArchive+            }+            result.append(data)+        }+        return result+    }++    private static func localHeader(_ member: ArchiveMember) -> Data {+        var header = Data()+        header.le32(0x04034b50); header.le16(20); header.le16(0x0800); header.le16(0)+        header.le16(0); header.le16(33); header.le32(member.checksum)+        header.le32(member.size); header.le32(member.size); header.le16(UInt16(member.name.utf8.count)); header.le16(0)+        header.append(Data(member.name.utf8))+        return header+    }++    private static func centralHeader(_ member: ArchiveMember) -> Data {+        var header = Data()+        header.le32(0x02014b50); header.le16(20); header.le16(20); header.le16(0x0800); header.le16(0)+        header.le16(0); header.le16(33); header.le32(member.checksum); header.le32(member.size); header.le32(member.size)+        header.le16(UInt16(member.name.utf8.count)); header.le16(0); header.le16(0); header.le16(0); header.le16(0)+        header.le32(0); header.le32(member.offset); header.append(Data(member.name.utf8))+        return header+    }+}++nonisolated private enum CRC32 {+    static let table: [UInt32] = (0..<256).map { index in+        var value = UInt32(index)+        for _ in 0..<8 { value = value & 1 == 0 ? value >> 1 : (value >> 1) ^ 0xedb88320 }+        return value+    }+    static func update(_ initial: UInt32, _ data: Data) -> UInt32 {+        data.reduce(initial) { ($0 >> 8) ^ table[Int(($0 ^ UInt32($1)) & 0xff)] }+    }+}++nonisolated private extension Data {+    mutating func le16(_ value: UInt16) { var number = value.littleEndian; Swift.withUnsafeBytes(of: &number) { append(contentsOf: $0) } }+    mutating func le32(_ value: UInt32) { var number = value.littleEndian; Swift.withUnsafeBytes(of: &number) { append(contentsOf: $0) } }+    func u16(_ offset: Int) -> UInt16 { UInt16(self[offset]) | UInt16(self[offset + 1]) << 8 }+    func u32(_ offset: Int) -> UInt32 { UInt32(u16(offset)) | UInt32(u16(offset + 2)) << 16 }+}
Halo Family/Halo Family/Persistence/BackupCancellation.swift Added +14 / -0
diff --git a/Halo Family/Halo Family/Persistence/BackupCancellation.swift b/Halo Family/Halo Family/Persistence/BackupCancellation.swiftnew file mode 100644index 0000000..e066789--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupCancellation.swift	@@ -0,0 +1,14 @@+import Foundation++/// Core Data executes perform blocks on its own queue. Carry caller cancellation+/// explicitly to that queue, including the last check before the atomic save.+nonisolated final class BackupCancellation: @unchecked Sendable {+    private let lock = NSLock()+    private var cancelled = false++    func cancel() { lock.withLock { cancelled = true } }+    func check() throws {+        try Task.checkCancellation()+        if lock.withLock({ cancelled }) { throw CancellationError() }+    }+}
Halo Family/Halo Family/Persistence/BackupHistory.swift Added +131 / -0
diff --git a/Halo Family/Halo Family/Persistence/BackupHistory.swift b/Halo Family/Halo Family/Persistence/BackupHistory.swiftnew file mode 100644index 0000000..a16158d--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupHistory.swift	@@ -0,0 +1,131 @@+import CoreData+import Foundation++/// Historical snapshots can refer to rows that undo has since removed. Copy their identity+/// namespace too, without guessing current relationships or dropping the original accounts.+nonisolated struct BackupHistory {+    private static let fields: [String: [String]] = [+        "PersonMerge": ["beforeData", "afterData", "archivedData"],+        "MergeConnectionReview": ["reviewedData"],+        "PersonMergeRecovery": ["beforeData", "afterData"],+    ]+    private var snapshotPaths: [String] = []+    private var arrays: [UUID: [String: [UUID]]] = [:]++    init(backup: FamilyBackup, model: NSManagedObjectModel,+         check: () throws -> Void = { try Task.checkCancellation() }, payload: (String) throws -> Data) throws {+        var types = Dictionary(uniqueKeysWithValues: backup.records.map { ($0.id, $0.entity) })+        for record in backup.records {+            try check()+            for field in Self.fields[record.entity] ?? [] {+                try check()+                guard case .binary(let path) = record.attributes[field] else { throw BackupError.invalidArchive }+                let rows = try MergeSnapshot.decode(payload(path))+                snapshotPaths.append(path)+                for row in rows {+                    try check()+                    guard types[row.id] == nil || types[row.id] == row.entity else { throw BackupError.invalidArchive }+                    types[row.id] = row.entity+                }+            }+            for field in ["recoveryIDs", "mergeIDs"] {+                guard case .text(let text) = record.attributes[field] else { continue }+                guard let values = try? JSONDecoder().decode([UUID].self, from: Data(text.utf8)),+                      Set(values).count == values.count else { throw BackupError.invalidArchive }+                arrays[record.id, default: [:]][field] = values+            }+        }+        for path in snapshotPaths {+            try check()+            let rows = try MergeSnapshot.decode(payload(path))+            for row in rows { try check(); try Self.validate(row, familyID: backup.familyID, model: model, types: types) }+        }+    }++    func copied(_ backup: FamilyBackup, check: () throws -> Void = { try Task.checkCancellation() },+                payload: (String) throws -> Data) throws -> (FamilyBackup, [String: Data]) {+        let map = Dictionary(uniqueKeysWithValues: try identities(in: backup, check: check, payload: payload).map { ($0, UUID()) })+        func mapped(_ id: UUID) throws -> UUID {+            guard let result = map[id] else { throw BackupError.invalidArchive }+            return result+        }+        var payloads: [String: Data] = [:]+        for path in snapshotPaths {+            try check()+            let rows = try MergeSnapshot.decode(payload(path))+            payloads[path] = try MergeSnapshot.encode(rows.map { row in+                try check()+                return MergeRecord(id: try mapped(row.id), entity: row.entity,+                            attributes: try row.attributes.mapValues { value in+                                if case .uuid(let id) = value { return .uuid(try mapped(id)) }+                                return value+                            }, links: try row.links.mapValues { try $0.map(mapped).sorted { $0.uuidString < $1.uuidString } })+            }.sorted { $0.id.uuidString < $1.id.uuidString })+        }+        let records = try backup.records.map { record in+            try check()+            var attributes = try record.attributes.mapValues { value in+                if case .uuid(let id) = value { return PortableValue.uuid(try mapped(id)) }+                return value+            }+            for (field, ids) in arrays[record.id] ?? [:] {+                let data = try JSONEncoder().encode(ids.map(mapped))+                guard let text = String(data: data, encoding: .utf8) else { throw BackupError.invalidArchive }+                attributes[field] = .text(text)+            }+            if record.entity == "PersonMerge" { attributes["undoUnavailableAt"] = .date(Date()) }+            return PortableRecord(id: try mapped(record.id), entity: record.entity, attributes: attributes,+                                  relationships: try record.relationships.mapValues { try $0.map(mapped) })+        }+        return (FamilyBackup(formatVersion: backup.formatVersion, modelVersion: backup.modelVersion,+                             familyID: try mapped(backup.familyID), createdAt: backup.createdAt, records: records), payloads)+    }++    private func identities(in backup: FamilyBackup, check: () throws -> Void, payload: (String) throws -> Data) throws -> Set<UUID> {+        var identities = Set(backup.records.map(\.id))+        for record in backup.records {+            try check()+            for value in record.attributes.values { if case .uuid(let id) = value { identities.insert(id) } }+        }+        for path in snapshotPaths {+            try check()+            let rows = try MergeSnapshot.decode(payload(path))+            for row in rows {+                try check()+                identities.insert(row.id)+                for value in row.attributes.values { if case .uuid(let id) = value { identities.insert(id) } }+                for links in row.links.values { identities.formUnion(links) }+            }+        }+        for values in arrays.values { for ids in values.values { identities.formUnion(ids) } }+        return identities+    }++    private static func validate(_ row: MergeRecord, familyID: UUID, model: NSManagedObjectModel,+                                 types: [UUID: String]) throws {+        guard let entity = model.entitiesByName[row.entity], fields[row.entity] == nil, row.entity != "FamilySpace",+              row.attributes["id"] == .uuid(row.id), row.links["familySpace"] == [familyID],+              Set(row.links.keys) == Set(entity.relationshipsByName.keys) else { throw BackupError.invalidArchive }+        for (key, value) in row.attributes {+            guard let attribute = entity.attributesByName[key], PortableGraph.accepts(portable(value), attribute: attribute) else {+                throw BackupError.invalidArchive+            }+        }+        for (key, links) in row.links {+            guard let relationship = entity.relationshipsByName[key], relationship.isToMany || links.count <= 1,+                  Set(links).count == links.count,+                  links.allSatisfy({ types[$0] == relationship.destinationEntity?.name }) else { throw BackupError.invalidArchive }+        }+    }++    private static func portable(_ value: SnapshotValue) -> PortableValue {+        switch value {+        case .text(let value): .text(value)+        case .integer(let value): .number(value)+        case .decimal(let value): .decimal(value)+        case .flag(let value): .flag(value)+        case .date(let value): .date(value)+        case .uuid(let value): .uuid(value)+        }+    }+}
Halo Family/Halo Family/Persistence/BackupRepository.swift Added +295 / -0
diff --git a/Halo Family/Halo Family/Persistence/BackupRepository.swift b/Halo Family/Halo Family/Persistence/BackupRepository.swiftnew file mode 100644index 0000000..539f78d--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupRepository.swift	@@ -0,0 +1,295 @@+import CoreData+import CryptoKit+import Foundation++nonisolated struct BackupPreview: Sendable {+    let archive: URL+    let backup: FamilyBackup+    let members: [ArchiveMember]+    let familyName: String+    let peopleCount: Int+    let eventCount: Int+    let payloadBytes: UInt64+    let fingerprint: Data+}++@MainActor+final class BackupRepository {+    #if os(iOS)+    nonisolated private static let payloadLimit: UInt64 = 128_000_000+    #else+    nonisolated private static let payloadLimit: UInt64 = 512_000_000+    #endif+    private let stack: PersistenceStack+    init(stack: PersistenceStack) { self.stack = stack }++    func export(familyID: NSManagedObjectID, readable: Bool = true) async throws -> URL {+        try stack.access.check()+        let access = stack.access+        guard stack.role == .host else { throw GraphError.readOnly }+        let context = stack.container.newBackgroundContext()+        let cancellation = BackupCancellation()+        let archive = try await withTaskCancellationHandler { try await context.perform {+            guard let model = context.persistentStoreCoordinator?.managedObjectModel else { throw GraphError.modelUnavailable }+            try cancellation.check()+            try context.setQueryGenerationFrom(.current)+            guard familyID.entity.name == "FamilySpace", !familyID.isTemporaryID else { throw GraphError.invalidReference }+            let family = try context.existingObject(with: familyID)+            let identity = try StoreAccess.identity(family)+            try access.check(family: identity.family, shared: identity.shared)+            guard let uuid = family.value(forKey: "id") as? UUID else { throw BackupError.missingIdentity }+            let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)+            try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+            var delivered = false+            defer { if !delivered { try? FileManager.default.removeItem(at: folder) } }+            var files: [BackupFile] = []+            var records: [PortableRecord] = []+            for entity in model.entities.sorted(by: { ($0.name ?? "") < ($1.name ?? "") }) {+                guard let name = entity.name else { continue }+                let request = NSFetchRequest<NSManagedObject>(entityName: name)+                if name == "FamilySpace" { request.predicate = NSPredicate(format: "SELF == %@", familyID) } else if+                    entity.relationshipsByName["familySpace"] != nil {+                    request.predicate = NSPredicate(format: "familySpace == %@", familyID)+                } else { continue }+                for object in try context.fetch(request) {+                    try access.check(family: identity.family, shared: identity.shared)+                    try cancellation.check()+                    guard let id = object.value(forKey: "id") as? UUID else { throw BackupError.missingIdentity }+                    let record = try PortableGraph.record(object) { key, data in+                        let path = "payloads/\(id.uuidString)/\(key).bin"+                        let url = folder.appendingPathComponent(path)+                        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+                        try data.write(to: url, options: .atomic)+                        files.append(BackupFile(name: path, url: url))+                        return path+                    }+                    records.append(record)+                    context.refresh(object, mergeChanges: false)+                }+            }+            let backup = FamilyBackup(formatVersion: 1, modelVersion: 6, familyID: uuid, createdAt: Date(),+                                      records: records.sorted { $0.id.uuidString < $1.id.uuidString })+            try BackupValidation.validate(backup, model: model, check: cancellation.check)+            let manifest = folder.appendingPathComponent("family.json")+            let manifestData = try PortableGraph.encode(backup)+            guard manifestData.count <= 32_000_000 else { throw BackupError.tooLarge }+            try manifestData.write(to: manifest, options: .atomic)+            files.append(BackupFile(name: "family.json", url: manifest))+            if readable {+                let markdown = folder.appendingPathComponent("Family.md")+                try Self.markdown(backup).write(to: markdown, atomically: true, encoding: .utf8)+                files.append(BackupFile(name: "Family.md", url: markdown))+            }+            let archive = folder.appendingPathComponent("Halo Family Backup.zip")+            try cancellation.check()+            try BackupArchive.write(files, to: archive, check: cancellation.check)+            try access.check(family)+            try cancellation.check()+            for file in files { try? FileManager.default.removeItem(at: file.url) }+            delivered = true+            return archive+        }+        } onCancel: { cancellation.cancel() }+        do {+            try Task.checkCancellation()+            _ = try FamilyRepository(stack: stack).readable(familyID, entity: "FamilySpace")+            return archive+        } catch {+            try? FileManager.default.removeItem(at: archive.deletingLastPathComponent())+            throw error+        }+    }++    func preview(_ archive: URL) async throws -> BackupPreview {+        let container = stack.container+        let task = Task.detached {+            let model = container.managedObjectModel+            let fingerprint = try Self.fingerprint(archive)+            let members = try BackupArchive.members(in: archive)+            let indexed = Dictionary(uniqueKeysWithValues: members.map { ($0.name, $0) })+            guard let manifest = indexed["family.json"] else { throw BackupError.invalidArchive }+            let data = try BackupArchive.read(manifest, from: archive, limit: 32_000_000)+            let backup = try PortableGraph.decode(FamilyBackup.self, data: data)+            try BackupValidation.validate(backup, model: model)+            let bytes = try Self.validatePayloads(backup, archive: archive, members: indexed)+            guard bytes <= Self.payloadLimit else { throw BackupError.tooLarge }+            _ = try BackupHistory(backup: backup, model: model) { path in+                try Self.payload(path, archive: archive, members: indexed)+            }+            let root = backup.records.first { $0.id == backup.familyID }+            let name: String+            if case .text(let value) = root?.attributes["name"] { name = value } else { name = "Family" }+            guard try Self.fingerprint(archive) == fingerprint else { throw BackupError.changed }+            return BackupPreview(archive: archive, backup: backup, members: members, familyName: name,+                                 peopleCount: backup.records.filter { $0.entity == "Person" }.count,+                                 eventCount: backup.records.filter { $0.entity == "Event" }.count, payloadBytes: bytes,+                                 fingerprint: fingerprint)+        }+        return try await withTaskCancellationHandler { try await task.value } onCancel: { task.cancel() }+    }++    func restore(_ preview: BackupPreview, asNewCopy: Bool) async throws -> NSManagedObjectID {+        try stack.access.check()+        let access = stack.access+        guard stack.role == .host else { throw GraphError.readOnly }+        guard !stack.importingBackup else { throw BackupError.importing }+        // A single atomic context save avoids exposing a partially imported family. Bound its payload memory.+        guard preview.payloadBytes <= Self.payloadLimit else { throw BackupError.tooLarge }+        stack.importingBackup = true+        defer { stack.importingBackup = false }+        let container = stack.container+        let context = container.newBackgroundContext()+        context.transactionAuthor = stack.role.rawValue+        let cancellation = BackupCancellation()+        let result = try await withTaskCancellationHandler { try await context.perform {+            guard try Self.fingerprint(preview.archive, cancellation: cancellation) == preview.fingerprint else {+                throw BackupError.changed+            }+            let members = try BackupArchive.members(in: preview.archive)+            guard members.count == preview.members.count,+                  zip(members, preview.members).allSatisfy({ pair in+                      pair.0.name == pair.1.name && pair.0.size == pair.1.size && pair.0.checksum == pair.1.checksum+                  }) else {+                throw BackupError.changed+            }+            let model = container.managedObjectModel+            try BackupValidation.validate(preview.backup, model: model, check: cancellation.check)+            let indexed = Dictionary(uniqueKeysWithValues: members.map { ($0.name, $0) })+            let history = try BackupHistory(backup: preview.backup, model: model, check: cancellation.check) { path in+                try Self.payload(path, archive: preview.archive, members: indexed)+            }+            let prepared: (FamilyBackup, [String: Data])+            if asNewCopy {+                prepared = try history.copied(preview.backup, check: cancellation.check) { path in+                    try Self.payload(path, archive: preview.archive, members: indexed)+                }+            } else { prepared = (preview.backup, [:]) }+            let (backup, overrides) = prepared+            try Self.requireAbsent(backup.records.map(\.id), in: context, model: model, cancellation: cancellation)+            guard let store = container.persistentStoreCoordinator.persistentStores.first(where: {+                $0.url?.lastPathComponent == "Private.sqlite"+            }) else { throw GraphError.invalidReference }+            try cancellation.check()+            let objects = try Self.insert(backup.records, context: context, store: store, cancellation: cancellation) { path in+                if let data = overrides[path] { return data }+                return try Self.payload(path, archive: preview.archive, members: indexed)+            }+            try Self.link(backup.records, objects: objects)+            guard let root = objects[backup.familyID] else { throw BackupError.invalidArchive }+            if asNewCopy { root.setValue(preview.familyName + " (copy)", forKey: "name") }+            let inserted = Array(context.insertedObjects)+            guard try Self.fingerprint(preview.archive, cancellation: cancellation) == preview.fingerprint else {+                throw BackupError.changed+            }+            try cancellation.check()+            try access.save(families: []) { try context.save() }+            return (root.objectID, inserted.map(\.objectID))+        }+        } onCancel: { cancellation.cancel() }+        try access.check()+        NSManagedObjectContext.mergeChanges(fromRemoteContextSave: [NSInsertedObjectsKey: result.1], into: [container.viewContext])+        do { try stack.refreshAccess() } catch { stack.lockSession() }+        NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: container)+        return result.0+    }++    nonisolated private static func requireAbsent(_ ids: [UUID], in context: NSManagedObjectContext,+                                                  model: NSManagedObjectModel, cancellation: BackupCancellation) throws {+        // Bound SQL bind variables even for large archives. Existing rows are never overwritten.+        for entity in model.entities {+            guard let name = entity.name else { continue }+            for start in stride(from: 0, to: ids.count, by: 400) {+                try cancellation.check()+                let request = NSFetchRequest<NSManagedObject>(entityName: name)+                request.predicate = NSPredicate(format: "id IN %@", Array(ids[start..<min(start + 400, ids.count)]) as NSArray)+                request.fetchLimit = 1+                guard try context.count(for: request) == 0 else { throw BackupError.familyExists }+            }+        }+    }++    nonisolated private static func insert(_ records: [PortableRecord], context: NSManagedObjectContext,+                                           store: NSPersistentStore, cancellation: BackupCancellation,+                                           payload: (String) throws -> Data) throws -> [UUID: NSManagedObject] {+        var objects: [UUID: NSManagedObject] = [:]+        for record in records {+            try cancellation.check()+            let object = NSEntityDescription.insertNewObject(forEntityName: record.entity, into: context)+            context.assign(object, to: store)+            for (key, value) in record.attributes { object.setValue(try PortableGraph.value(value, binary: payload), forKey: key) }+            objects[record.id] = object+        }+        return objects+    }++    nonisolated private static func link(_ records: [PortableRecord], objects: [UUID: NSManagedObject]) throws {+        for record in records {+            guard let object = objects[record.id] else { throw BackupError.invalidArchive }+            for (key, links) in record.relationships {+                let targets = try links.map { id in+                    guard let target = objects[id] else { throw BackupError.invalidArchive }+                    return target+                }+                if object.entity.relationshipsByName[key]?.isToMany == true { object.setValue(NSSet(array: targets), forKey: key) } else {+                    object.setValue(targets.first, forKey: key)+                }+            }+        }+    }++    nonisolated private static func payload(_ path: String, archive: URL, members: [String: ArchiveMember]) throws -> Data {+        guard let member = members[path] else { throw BackupError.invalidArchive }+        return try BackupArchive.read(member, from: archive, limit: 32_000_000)+    }++    nonisolated private static func validatePayloads(_ backup: FamilyBackup, archive: URL,+                                                     members: [String: ArchiveMember]) throws -> UInt64 {+        var expected: Set<String> = ["family.json"]+        if members["Family.md"] != nil {+            expected.insert("Family.md")+            _ = try payload("Family.md", archive: archive, members: members)+        }+        var bytes: UInt64 = 0+        for record in backup.records {+            for (key, value) in record.attributes {+                guard case .binary(let path) = value else { continue }+                guard path == "payloads/\(record.id.uuidString)/\(key).bin", expected.insert(path).inserted,+                      let member = members[path] else { throw BackupError.invalidArchive }+                let data = try payload(path, archive: archive, members: members)+                try BackupValidation.payload(data, key: key, record: record)+                bytes += UInt64(member.size)+            }+        }+        guard expected == Set(members.keys) else { throw BackupError.invalidArchive }+        return bytes+    }++    nonisolated private static func fingerprint(_ archive: URL, cancellation: BackupCancellation? = nil) throws -> Data {+        let handle = try FileHandle(forReadingFrom: archive)+        defer { try? handle.close() }+        var hash = SHA256()+        var count: UInt64 = 0+        while let data = try handle.read(upToCount: 65_536), !data.isEmpty {+            try Task.checkCancellation()+            try cancellation?.check()+            count += UInt64(data.count)+            guard count <= BackupArchive.maximumBytes else { throw BackupError.tooLarge }+            hash.update(data: data)+        }+        return Data(hash.finalize())+    }++    nonisolated private static func markdown(_ backup: FamilyBackup) -> String {+        var lines = ["# Halo Family backup", "", "Created: \(backup.createdAt.formatted())", ""]+        let readable = ["Person", "Event", "Context", "PersonGroup", "RelationshipAssertion", "GiftRecord"]+        for record in backup.records where readable.contains(record.entity) {+            let title = ["displayName", "title", "name", "customLabel", "descriptionText"].compactMap { key -> String? in+                if case .text(let value) = record.attributes[key] { return value }+                return nil+            }.first ?? record.entity+            lines += ["## \(title.replacingOccurrences(of: "\n", with: " "))", "", "Type: \(record.entity)", ""]+            if case .text(let notes) = record.attributes["notes"] ?? record.attributes["note"], !notes.isEmpty { lines += [notes, ""] }+        }+        return lines.joined(separator: "\n")+    }+}
Halo Family/Halo Family/Persistence/BackupStaging.swift Added +28 / -0
diff --git a/Halo Family/Halo Family/Persistence/BackupStaging.swift b/Halo Family/Halo Family/Persistence/BackupStaging.swiftnew file mode 100644index 0000000..443cba1--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupStaging.swift	@@ -0,0 +1,28 @@+import Foundation++nonisolated enum BackupStaging {+    /// Own a bounded copy of the selected document. Later provider edits cannot change this preview.+    static func copy(_ selected: URL) throws -> URL {+        let access = selected.startAccessingSecurityScopedResource()+        defer { if access { selected.stopAccessingSecurityScopedResource() } }+        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)+        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)+        do {+            let archive = folder.appendingPathComponent("Selected Backup.zip")+            guard FileManager.default.createFile(atPath: archive.path, contents: nil) else { throw BackupError.invalidArchive }+            let source = try FileHandle(forReadingFrom: selected), output = try FileHandle(forWritingTo: archive)+            defer { try? source.close(); try? output.close() }+            var bytes: UInt64 = 0+            while let data = try source.read(upToCount: 65_536), !data.isEmpty {+                try Task.checkCancellation()+                bytes += UInt64(data.count)+                guard bytes <= BackupArchive.maximumBytes else { throw BackupError.tooLarge }+                try output.write(contentsOf: data)+            }+            return archive+        } catch {+            try? FileManager.default.removeItem(at: folder)+            throw error+        }+    }+}
Halo Family/Halo Family/Persistence/BackupValidation.swift Added +161 / -0
diff --git a/Halo Family/Halo Family/Persistence/BackupValidation.swift b/Halo Family/Halo Family/Persistence/BackupValidation.swiftnew file mode 100644index 0000000..6f62c8b--- /dev/null+++ b/Halo Family/Halo Family/Persistence/BackupValidation.swift	@@ -0,0 +1,161 @@+import CoreData+import Foundation++nonisolated enum BackupValidation {+    private static let requiredLinks: [String: [String]] = [+        "ChildProfile": ["person"], "Connection": ["child", "person"],+        "ConnectionContext": ["connection", "context"], "ConnectionOrigin": ["connection"],+        "OriginProposal": ["connection"], "ContextPerson": ["context", "person"],+        "ConnectionClosenessPeriod": ["connection"], "ConnectionStatusPeriod": ["connection"],+        "PersonRelationship": ["source", "target"], "RelationshipAssertion": ["source", "target"],+        "AddressLabel": ["target"], "GroupMembership": ["group", "person"],+        "EventPerson": ["event", "person"], "GiftRecord": ["event"], "EventAttachment": ["event", "asset"],+    ]++    static func validate(_ backup: FamilyBackup, model: NSManagedObjectModel,+                         check: () throws -> Void = { try Task.checkCancellation() }) throws {+        guard backup.formatVersion == 1, (1...6).contains(backup.modelVersion), backup.records.count <= 100_000 else {+            throw BackupError.unsupportedVersion+        }+        let indexed = try index(backup.records, check: check)+        let linkSets = Dictionary(uniqueKeysWithValues: backup.records.map { ($0.id, $0.relationships.mapValues { Set($0) }) })+        guard indexed[backup.familyID]?.entity == "FamilySpace",+              backup.records.filter({ $0.entity == "FamilySpace" }).count == 1 else { throw BackupError.invalidArchive }+        for record in backup.records {+            try check()+            guard let entity = model.entitiesByName[record.entity], record.attributes["id"] == .uuid(record.id) else {+                throw BackupError.invalidArchive+            }+            for (key, value) in record.attributes {+                guard let attribute = entity.attributesByName[key], PortableGraph.accepts(value, attribute: attribute) else {+                    throw BackupError.invalidArchive+                }+            }+            if record.id != backup.familyID, record.relationships["familySpace"] != [backup.familyID] {+                throw BackupError.invalidArchive+            }+            for (key, targets) in record.relationships {+                guard let relationship = entity.relationshipsByName[key], !relationship.isOrdered,+                      Set(targets).count == targets.count, relationship.isToMany || targets.count <= 1 else {+                    throw BackupError.invalidArchive+                }+                for target in targets {+                    guard let other = indexed[target], other.entity == relationship.destinationEntity?.name,+                          let inverse = relationship.inverseRelationship?.name,+                          linkSets[target]?[inverse]?.contains(record.id) == true else { throw BackupError.invalidArchive }+                }+            }+            try domain(record, indexed: indexed)+        }+        try acyclic(backup.records.filter { $0.entity == "Context" }, edge: "parent", check: check)+        try acyclic(backup.records.filter { $0.entity == "OriginProposal" }, edge: "predecessors", check: check)+    }++    static func index(_ records: [PortableRecord],+                      check: () throws -> Void = { try Task.checkCancellation() }) throws -> [UUID: PortableRecord] {+        var indexed: [UUID: PortableRecord] = [:]+        for record in records {+            try check()+            guard indexed.updateValue(record, forKey: record.id) == nil else { throw BackupError.invalidArchive }+        }+        return indexed+    }++    private static func domain(_ record: PortableRecord, indexed: [UUID: PortableRecord]) throws {+        let values = record.attributes+        func integer(_ key: String) -> Int? { if case .number(let value) = values[key] { return Int(exactly: value) }; return nil }+        func text(_ key: String) -> String? { if case .text(let value) = values[key] { return value }; return nil }+        for link in requiredLinks[record.entity] ?? [] {+            guard record.relationships[link]?.count == 1 else { throw BackupError.invalidArchive }+        }+        if case .date(let start) = values["startedAt"], case .date(let end) = values["endedAt"], end < start {+            throw BackupError.invalidArchive+        }+        switch record.entity {+        case "Person":+            let date = try PartialDate(year: integer("deathYear"), month: integer("deathMonth"), day: integer("deathDay"))+            guard date.year == nil && date.month == nil && date.day == nil || values["isDeceased"] == .flag(true) else {+                throw BackupError.invalidArchive+            }+        case "Event":+            if case .date(let start) = values["date"], case .date(let end) = values["endDate"], end < start {+                throw BackupError.invalidArchive+            }+        case "Asset": try asset(record)+        case "ConnectionOrigin", "OriginProposal":+            let context = record.relationships["context"] ?? [], event = record.relationships["event"] ?? []+            let narrative = text(record.entity == "ConnectionOrigin" ? "originDescription" : "narrative") ?? ""+            let cleared = values["isCleared"] == .flag(true)+            guard context.isEmpty || event.isEmpty,+                  cleared ? (context.isEmpty && event.isEmpty && narrative.isEmpty) :+                    (!context.isEmpty || !event.isEmpty || !narrative.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) else {+                throw BackupError.invalidArchive+            }+            for predecessor in record.relationships["predecessors"] ?? [] {+                guard indexed[predecessor]?.relationships["connection"] == record.relationships["connection"] else {+                    throw BackupError.invalidArchive+                }+            }+        case "ConnectionClosenessPeriod":+            guard let value = integer("value"), (1...10).contains(value) else { throw BackupError.invalidArchive }+        case "ConnectionStatusPeriod":+            guard ConnectionState(rawValue: text("state") ?? "") != nil else { throw BackupError.invalidArchive }+        case "EventPerson":+            guard InvitationState(rawValue: text("invitationState") ?? "unknown") != nil,+                  AttendanceState(rawValue: text("attendanceState") ?? "unknown") != nil else { throw BackupError.invalidArchive }+            if let roles = text("roles"), (try? JSONDecoder().decode([String].self, from: Data(roles.utf8))) == nil {+                throw BackupError.invalidArchive+            }+        case "GiftRecord":+            for attachment in record.relationships["attachments"] ?? [] {+                guard indexed[attachment]?.relationships["event"] == record.relationships["event"] else {+                    throw BackupError.invalidArchive+                }+            }+        default: break+        }+    }++    private static func asset(_ record: PortableRecord) throws {+        let photo = !(record.relationships["photoPerson"] ?? []).isEmpty+        let attachment = !(record.relationships["eventAttachment"] ?? []).isEmpty+        guard !photo || !attachment else { throw BackupError.invalidArchive }+        if photo || attachment {+            guard case .binary = record.attributes["data"] else { throw BackupError.invalidArchive }+        }+    }++    static func payload(_ data: Data, key: String, record: PortableRecord) throws {+        guard record.entity == "Asset", key == "data" else { return }+        let photo = !(record.relationships["photoPerson"] ?? []).isEmpty+        let attachment = !(record.relationships["eventAttachment"] ?? []).isEmpty+        let limit = photo ? ImageImport.photoLimit : attachment ? ImageImport.attachmentLimit : 32_000_000+        guard data.count <= limit, (!photo && !attachment) || !data.isEmpty else { throw BackupError.tooLarge }+        if case .number(let size) = record.attributes["byteCount"], size != Int64(data.count) {+            throw BackupError.invalidArchive+        }+    }++    private static func acyclic(_ records: [PortableRecord], edge: String, check: () throws -> Void) throws {+        var incoming = Dictionary(uniqueKeysWithValues: records.map { ($0.id, 0) })+        let indexed = Dictionary(uniqueKeysWithValues: records.map { ($0.id, $0) })+        for record in records {+            try check()+            for target in record.relationships[edge] ?? [] {+                guard indexed[target] != nil else { throw BackupError.invalidArchive }+                incoming[target, default: 0] += 1+            }+        }+        var ready = Set(incoming.filter { $0.value == 0 }.map(\.key))+        var processed = 0+        while let id = ready.popFirst() {+            try check()+            processed += 1+            for target in indexed[id]?.relationships[edge] ?? [] {+                incoming[target, default: 0] -= 1+                if incoming[target] == 0 { ready.insert(target) }+            }+        }+        guard processed == records.count else { throw BackupError.invalidArchive }+    }+}
Halo Family/Halo Family/Persistence/CaptureReference.swift Added +68 / -0
diff --git a/Halo Family/Halo Family/Persistence/CaptureReference.swift b/Halo Family/Halo Family/Persistence/CaptureReference.swiftnew file mode 100644index 0000000..5f3ee99--- /dev/null+++ b/Halo Family/Halo Family/Persistence/CaptureReference.swift	@@ -0,0 +1,68 @@+import Foundation++nonisolated struct CaptureReference: Hashable, Sendable {+    let namespace: String+    let family: FamilyAccessID+    let record: UUID++    var identifier: String {+        [namespace, family.shared ? "shared" : "private", family.family.uuidString, record.uuidString].joined(separator: ":")+    }++    init(namespace: String, family: FamilyAccessID, record: UUID) {+        self.namespace = namespace; self.family = family; self.record = record+    }++    init?(identifier: String) {+        guard identifier.utf8.count <= 256 else { return nil }+        let parts = identifier.split(separator: ":", omittingEmptySubsequences: false)+        guard parts.count == 4, !parts[0].isEmpty, parts[0].count <= 128,+              parts[0].allSatisfy({ $0.asciiValue != nil && ($0.isLetter || $0.isNumber || $0 == "-") }),+              parts[1] == "private" || parts[1] == "shared",+              let family = UUID(uuidString: String(parts[2])), let record = UUID(uuidString: String(parts[3])) else { return nil }+        self.init(namespace: String(parts[0]), family: FamilyAccessID(family: family, shared: parts[1] == "shared"), record: record)+    }+}++nonisolated struct CaptureRoute: Identifiable, Sendable {+    let child: CaptureReference+    let context: CaptureReference?+    var id: String { child.identifier + "|" + (context?.identifier ?? "") }++    var url: URL? {+        var value = URLComponents()+        value.scheme = "halo-family"; value.host = "capture"+        value.queryItems = [URLQueryItem(name: "child", value: child.identifier)]+        if let context { value.queryItems?.append(URLQueryItem(name: "context", value: context.identifier)) }+        return value.url+    }++    init(child: CaptureReference, context: CaptureReference? = nil) {+        self.child = child; self.context = context+    }++    init?(url: URL) {+        guard url.absoluteString.utf8.count <= 2_048, let value = URLComponents(url: url, resolvingAgainstBaseURL: false),+              value.scheme?.lowercased() == "halo-family", value.host?.lowercased() == "capture", value.path.isEmpty,+              value.user == nil, value.password == nil, value.port == nil, value.fragment == nil,+              let items = value.queryItems, items.count <= 2,+              items.allSatisfy({ ["child", "context"].contains($0.name) }),+              Set(items.map(\.name)).count == items.count,+              let childID = items.first(where: { $0.name == "child" })?.value,+              let child = CaptureReference(identifier: childID) else { return nil }+        let context: CaptureReference?+        if let item = items.first(where: { $0.name == "context" }) {+            guard let id = item.value, let reference = CaptureReference(identifier: id),+                  reference.namespace == child.namespace, reference.family == child.family else { return nil }+            context = reference+        } else { context = nil }+        self.init(child: child, context: context)+    }+}++nonisolated struct CaptureChoice: Identifiable, Equatable, Sendable {+    let reference: CaptureReference+    let name: String+    let familyName: String+    var id: String { reference.identifier }+}
Halo Family/Halo Family/Persistence/CaptureRepository.swift Added +87 / -0
diff --git a/Halo Family/Halo Family/Persistence/CaptureRepository.swift b/Halo Family/Halo Family/Persistence/CaptureRepository.swiftnew file mode 100644index 0000000..b2c5cff--- /dev/null+++ b/Halo Family/Halo Family/Persistence/CaptureRepository.swift	@@ -0,0 +1,87 @@+import CoreData+import CryptoKit+import Foundation++/// The intent and widget pass scoped identities, then resolve current authorized rows before using them.+@MainActor+struct CaptureRepository {+    let graph: FamilyRepository+    var namespace: String {+        if let scope = graph.stack.accountScope { return scope.namespace }+        let path = graph.stack.privateStore.url?.deletingLastPathComponent().path ?? "unavailable"+        return "synthetic-" + SHA256.hash(data: Data(path.utf8)).map { String(format: "%02x", $0) }.joined()+    }++    func children() throws -> [CaptureChoice] {+        let request = NSFetchRequest<NSManagedObject>(entityName: "ChildProfile")+        request.predicate = NSPredicate(format: "archivedAt == nil AND mergedInto == nil AND person != nil " ++            "AND person.archivedAt == nil AND person.mergedInto == nil AND (person.isDeceased == NO OR person.isDeceased == nil)")+        request.sortDescriptors = [NSSortDescriptor(key: "person.displayName", ascending: true)]+        let ambiguous = try StoreAccess.ambiguousFamilies(in: graph.stack.container.viewContext)+        return try graph.stack.fetch(request).compactMap { child in+            let identity = try StoreAccess.identity(child, checkingDuplicates: false)+            guard !ambiguous.contains(identity) else { return nil }+            do {+                try graph.stack.access.check(family: identity.family, shared: identity.shared, writing: true)+            } catch AccessError.readOnlyFamily {+                return nil+            }+            return try choice(child, name: child.value(forKeyPath: "person.displayName") as? String ?? "Unnamed", identity: identity)+        }+    }++    func child(_ reference: CaptureReference) throws -> CaptureChoice {+        let object = try resolve(reference, entity: "ChildProfile")+        try graph.validateCaptureChild(object)+        return try choice(object, name: object.value(forKeyPath: "person.displayName") as? String ?? "Unnamed", identity: reference.family)+    }++    func contexts(for child: CaptureReference) throws -> [CaptureChoice] {+        let object = try resolve(child, entity: "ChildProfile")+        try graph.validateCaptureChild(object)+        let family = try graph.family(of: object)+        let request = NSFetchRequest<NSManagedObject>(entityName: "Context")+        request.predicate = NSPredicate(format: "familySpace == %@ AND archivedAt == nil", family)+        return try graph.stack.fetch(request).map { try choice($0, name: graph.contextPath($0), identity: child.family) }+            .sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }+    }++    func capture(name: String, child: CaptureReference, context: CaptureReference?) throws -> NSManagedObjectID {+        let currentChild = try resolve(child, entity: "ChildProfile")+        try graph.validateCaptureChild(currentChild)+        let childID = currentChild.objectID+        let contextID: NSManagedObjectID?+        if let context {+            guard context.namespace == child.namespace, context.family == child.family else { throw GraphError.differentFamily }+            let object = try resolve(context, entity: "Context")+            guard object.value(forKey: "archivedAt") == nil else { throw GraphError.invalidReference }+            contextID = object.objectID+        } else { contextID = nil }+        return try graph.quickCapture(name: name, childID: childID, contextID: contextID)+    }++    func context(_ reference: CaptureReference) throws -> CaptureChoice {+        let object = try resolve(reference, entity: "Context")+        guard object.value(forKey: "archivedAt") == nil else { throw GraphError.invalidReference }+        try graph.stack.access.check(object, writing: true)+        return try choice(object, name: graph.contextPath(object), identity: reference.family)+    }++    private func resolve(_ reference: CaptureReference, entity: String) throws -> NSManagedObject {+        guard reference.namespace == namespace else { throw AccessError.accountChanged }+        let request = NSFetchRequest<NSManagedObject>(entityName: entity)+        request.predicate = NSPredicate(format: "id == %@ AND familySpace.id == %@",+                                       reference.record as NSUUID, reference.family.family as NSUUID)+        request.affectedStores = [reference.family.shared ? graph.stack.sharedStore : graph.stack.privateStore]+        request.fetchLimit = 2+        let values = try graph.stack.fetch(request)+        guard values.count == 1, let object = values.first else { throw GraphError.invalidReference }+        return try graph.readable(object.objectID, entity: entity)+    }++    private func choice(_ object: NSManagedObject, name: String, identity: FamilyAccessID) throws -> CaptureChoice {+        let family = try graph.family(of: object)+        let reference = CaptureReference(namespace: namespace, family: identity, record: try graph.stable(object))+        return CaptureChoice(reference: reference, name: name, familyName: family.value(forKey: "name") as? String ?? "Family")+    }+}
Halo Family/Halo Family/Persistence/CloudAccessFailure.swift Added +16 / -0
diff --git a/Halo Family/Halo Family/Persistence/CloudAccessFailure.swift b/Halo Family/Halo Family/Persistence/CloudAccessFailure.swiftnew file mode 100644index 0000000..af96689--- /dev/null+++ b/Halo Family/Halo Family/Persistence/CloudAccessFailure.swift	@@ -0,0 +1,16 @@+import CloudKit+import Foundation++nonisolated enum CloudAccessFailure {+    static func removesAccess(_ error: Error?, depth: Int = 0) -> Bool {+        guard let error, depth < 8 else { return false }+        let value = error as NSError+        if value.domain == CKErrorDomain,+           [CKError.permissionFailure.rawValue, CKError.zoneNotFound.rawValue, CKError.userDeletedZone.rawValue].contains(value.code) {+            return true+        }+        if removesAccess(value.userInfo[NSUnderlyingErrorKey] as? Error, depth: depth + 1) { return true }+        let partial = value.userInfo[CKPartialErrorsByItemIDKey] as? [AnyHashable: Error] ?? [:]+        return partial.values.contains { removesAccess($0, depth: depth + 1) }+    }+}
Halo Family/Halo Family/Persistence/ConnectionStateRepository.swift Added +205 / -0
diff --git a/Halo Family/Halo Family/Persistence/ConnectionStateRepository.swift b/Halo Family/Halo Family/Persistence/ConnectionStateRepository.swiftnew file mode 100644index 0000000..48c68ad--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ConnectionStateRepository.swift	@@ -0,0 +1,205 @@+import CoreData+import Foundation++nonisolated enum ClosenessChoice: Int16, CaseIterable, Identifiable, Sendable {+    case metOnce = 1+    case knowThem = 3+    case friend = 5+    case goodFriend = 7+    case bff = 10++    var id: Int16 { rawValue }+    var label: String {+        switch self {+        case .metOnce: "Met once"+        case .knowThem: "Know them"+        case .friend: "Friend"+        case .goodFriend: "Good friend"+        case .bff: "BFF"+        }+    }+}++nonisolated enum ConnectionState: String, CaseIterable, Sendable {+    case active+    case lostContact++    var label: String { self == .active ? "Active" : "Lost contact" }+}++struct ConnectionStateSnapshot {+    let closenessValue: Int16?+    let closeness: ClosenessChoice?+    let closenessID: NSManagedObjectID?+    let closenessNeedsReview: Bool+    let state: ConnectionState+    let statusID: NSManagedObjectID?+    let statusNeedsReview: Bool+    let note: String+}++struct StatePeriodRow: Identifiable {+    let id: NSManagedObjectID+    let value: Int16?+    let state: ConnectionState?+    let note: String+    let startedAt: Date?+}++@MainActor+extension FamilyRepository {+    func currentStatePeriods(_ connectionID: NSManagedObjectID, closeness: Bool) throws -> [StatePeriodRow] {+        let connection = try readable(connectionID, entity: "Connection")+        return try currentPeriods(closeness ? "ConnectionClosenessPeriod" : "ConnectionStatusPeriod",+                                  connection: connection, in: stack.container.viewContext).map {+            StatePeriodRow(id: $0.objectID, value: closeness ? try closenessValue($0) : nil,+                           state: closeness ? nil : try statusValue($0),+                           note: closeness ? "" : $0.value(forKey: "note") as? String ?? "",+                           startedAt: $0.value(forKey: "startedAt") as? Date)+        }+    }++    func resolveCloseness(_ value: Int16, connectionID: NSManagedObjectID, reviewed: Set<NSManagedObjectID>) throws {+        guard (1...10).contains(value) else { throw GraphError.invalidState }+        try resolvePeriods("ConnectionClosenessPeriod", connectionID: connectionID, reviewed: reviewed) {+            $0.setValue(value, forKey: "value")+        }+    }++    func resolveStatus(_ state: ConnectionState, note: String, connectionID: NSManagedObjectID,+                       reviewed: Set<NSManagedObjectID>) throws {+        try resolvePeriods("ConnectionStatusPeriod", connectionID: connectionID, reviewed: reviewed) {+            $0.setValue(state.rawValue, forKey: "state")+            $0.setValue(note.trimmingCharacters(in: .whitespacesAndNewlines), forKey: "note")+        }+    }++    private func resolvePeriods(_ entity: String, connectionID: NSManagedObjectID, reviewed: Set<NSManagedObjectID>,+                                configure: (NSManagedObject) -> Void) throws {+        _ = try write { context in+            let connection = try record(connectionID, entity: "Connection", in: context)+            let periods = try currentPeriods(entity, connection: connection, in: context)+            guard periods.count > 1, Set(periods.map(\.objectID)) == reviewed else { throw GraphError.stateChanged }+            let fresh = try newPeriod(entity, connection: connection, previous: nil, in: context)+            let now = max(Date(), periods.compactMap { $0.value(forKey: "startedAt") as? Date }.max() ?? Date())+            for period in periods { period.setValue(now, forKey: "endedAt") }+            fresh.setValue(now, forKey: "startedAt")+            configure(fresh)+            return fresh+        }+    }+    func connectionState(_ connectionID: NSManagedObjectID) throws -> ConnectionStateSnapshot {+        guard let snapshot = try connectionStates([connectionID])[connectionID] else { throw GraphError.invalidReference }+        return snapshot+    }++    func connectionStates(_ connectionIDs: [NSManagedObjectID]) throws -> [NSManagedObjectID: ConnectionStateSnapshot] {+        guard !connectionIDs.isEmpty else { return [:] }+        let connections = try readable(Array(Set(connectionIDs)), 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+    }+}
Halo Family/Halo Family/Persistence/ContactIdentity.swift Added +27 / -0
diff --git a/Halo Family/Halo Family/Persistence/ContactIdentity.swift b/Halo Family/Halo Family/Persistence/ContactIdentity.swiftnew file mode 100644index 0000000..ac90440--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ContactIdentity.swift	@@ -0,0 +1,27 @@+import CoreData+import Foundation++struct ContactIdentity {+    let familyID: UUID+    let personID: UUID+    let aliases: Set<UUID>+}++@MainActor+extension FamilyRepository {+    func contactIdentity(_ personID: NSManagedObjectID) throws -> ContactIdentity {+        guard stack.role == .host else { throw GraphError.readOnly }+        let person = try readable(personID, entity: "Person")+        let family = try family(of: person)+        guard try !mergeConflicts(in: family.objectID).contains(where: { $0.people.contains { $0.id == personID } }),+              person.value(forKey: "mergedInto") == nil else { throw MergeError.changed }+        var aliases: Set<UUID> = [], seen: Set<NSManagedObjectID> = [], pending = [person]+        while let current = pending.popLast() {+            guard seen.insert(current.objectID).inserted else { throw MergeError.invalidSnapshot }+            try requireSameFamily(current, family: family)+            aliases.insert(try stable(current))+            pending.append(contentsOf: current.value(forKey: "mergedPeople") as? Set<NSManagedObject> ?? [])+        }+        return try ContactIdentity(familyID: stable(family), personID: stable(person), aliases: aliases)+    }+}
Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift Added +88 / -0
diff --git a/Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift b/Halo Family/Halo Family/Persistence/ContextCategoryRepository.swiftnew file mode 100644index 0000000..3e538c1--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ContextCategoryRepository.swift	@@ -0,0 +1,88 @@+import CoreData+import Foundation++struct ContextCategoryRow: Identifiable, Equatable {+    let id: NSManagedObjectID+    let name: String+    let isArchived: Bool+}++@MainActor+extension FamilyRepository {+    static let starterCategories = ["School", "Playgroup", "Parent group", "Childcare", "Activities"]++    func seedCategories(family: NSManagedObject, in context: NSManagedObjectContext) throws {+        guard stack.container.managedObjectModel.entitiesByName["ContextCategory"] != nil else { return }+        let request = NSFetchRequest<NSManagedObject>(entityName: "ContextCategory")+        request.predicate = NSPredicate(format: "familySpace == %@", family)+        let existing = Set(try context.fetch(request).compactMap { ($0.value(forKey: "name") as? String)?.lowercased() })+        for name in Self.starterCategories where !existing.contains(name.lowercased()) {+            let category = insert("ContextCategory", in: context, store: try owningStore(of: family))+            category.setValue(name, forKey: "name")+            category.setValue(family, forKey: "familySpace")+        }+    }++    func addStarterCategories(familyID: NSManagedObjectID) throws {+        _ = try write { context in+            let family = try record(familyID, entity: "FamilySpace", in: context)+            try seedCategories(family: family, in: context)+            return family+        }+    }++    func contextCategories(in familyID: NSManagedObjectID) throws -> [ContextCategoryRow] {+        _ = try readable(familyID, entity: "FamilySpace")+        let request = NSFetchRequest<NSManagedObject>(entityName: "ContextCategory")+        request.predicate = NSPredicate(format: "familySpace == %@", familyID)+        request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]+        return try stack.fetch(request).map(categoryRow)+    }++    func createCategory(name: String, familyID: NSManagedObjectID) throws -> NSManagedObjectID {+        let name = try validated(name)+        return try write { context in+            let family = try record(familyID, entity: "FamilySpace", in: context)+            let category = insert("ContextCategory", in: context, store: try owningStore(of: family))+            category.setValue(family, forKey: "familySpace")+            category.setValue(name, forKey: "name")+            return category+        }+    }++    func updateCategory(_ expected: ContextCategoryRow, name: String, archived: Bool) throws {+        let name = try validated(name)+        _ = try write { context in+            let category = try record(expected.id, entity: "ContextCategory", in: context)+            guard categoryRow(category) == expected else { throw MemoryError.changed }+            category.setValue(name, forKey: "name")+            category.setValue(archived ? (category.value(forKey: "archivedAt") as? Date ?? Date()) : nil, forKey: "archivedAt")+            return category+        }+    }++    func contextCategory(_ contextID: NSManagedObjectID) throws -> NSManagedObjectID? {+        (try readable(contextID, entity: "Context").value(forKey: "category") as? NSManagedObject)?.objectID+    }++    func setContextCategory(_ contextID: NSManagedObjectID, categoryID: NSManagedObjectID?,+                            expectedID: NSManagedObjectID?) throws {+        _ = try write { context in+            let source = try record(contextID, entity: "Context", in: context)+            let current = (source.value(forKey: "category") as? NSManagedObject)?.objectID+            guard current == expectedID else { throw MemoryError.changed }+            let category = try categoryID.map { try record($0, entity: "ContextCategory", in: context) }+            if let category {+                try requireSameFamily(category, family: family(of: source))+                guard category.value(forKey: "archivedAt") == nil || category.objectID == current else { throw MemoryError.changed }+            }+            source.setValue(category, forKey: "category")+            return source+        }+    }++    private func categoryRow(_ object: NSManagedObject) -> ContextCategoryRow {+        ContextCategoryRow(id: object.objectID, name: object.value(forKey: "name") as? String ?? "Unnamed",+                           isArchived: object.value(forKey: "archivedAt") != nil)+    }+}
Halo Family/Halo Family/Persistence/EventMemoryRepository.swift Added +249 / -0
diff --git a/Halo Family/Halo Family/Persistence/EventMemoryRepository.swift b/Halo Family/Halo Family/Persistence/EventMemoryRepository.swiftnew file mode 100644index 0000000..bcc3885--- /dev/null+++ b/Halo Family/Halo Family/Persistence/EventMemoryRepository.swift	@@ -0,0 +1,249 @@+import CoreData+import Foundation++nonisolated enum InvitationState: String, CaseIterable, Sendable {+    case unknown, considering, intendToInvite, invited, accepted, declined+    var label: String {+        switch self {+        case .unknown: "Not recorded"+        case .considering: "Considering"+        case .intendToInvite: "Intend to invite"+        case .invited: "Invited"+        case .accepted: "Accepted"+        case .declined: "Declined"+        }+    }+}++nonisolated enum AttendanceState: String, CaseIterable, Sendable {+    case unknown, attended, didNotAttend+    var label: String {+        switch self {+        case .unknown: "Not recorded"+        case .attended: "Attended"+        case .didNotAttend: "Did not attend"+        }+    }+}++struct ParticipantRow: Identifiable, Equatable {+    let id: NSManagedObjectID+    let personID: NSManagedObjectID+    let name: String+    let roles: Set<String>+    let invitation: InvitationState+    let attendance: AttendanceState+    let note: String+}++struct AttachmentRow: Identifiable {+    let id: NSManagedObjectID+    let assetID: NSManagedObjectID+    let title: String+    let contentType: String+}++struct GiftRow: Identifiable {+    let id: NSManagedObjectID+    let description: String+    let givers: [String]+    let recipients: [String]+    let note: String+    let attachmentIDs: Set<NSManagedObjectID>+    let giverIDs: Set<NSManagedObjectID>+    let groupIDs: Set<NSManagedObjectID>+    let recipientIDs: Set<NSManagedObjectID>+}++struct GiftInput {+    var description: String+    var givers: Set<NSManagedObjectID> = []+    var groups: Set<NSManagedObjectID> = []+    var recipients: Set<NSManagedObjectID> = []+    var attachments: Set<NSManagedObjectID> = []+    var note = ""+}++@MainActor+extension FamilyRepository {+    func updateEvent(_ eventID: NSManagedObjectID, title: String, date: Date?, type: String = "", notes: String,+                     links: (NSManagedObjectID?, NSManagedObjectID?), expected: EventRow) throws {+        let title = try validated(title)+        _ = try write { context in+            let event = try record(eventID, entity: "Event", in: context)+            guard eventRow(event) == expected else { throw MemoryError.changed }+            guard date != nil || expected.date == nil else { throw MemoryError.invalidDate }+            let family = try family(of: event)+            let person = try links.0.map { try record($0, entity: "Person", in: context) }+            let source = try links.1.map { try record($0, entity: "Context", in: context) }+            for link in [person, source].compactMap({ $0 }) { try requireSameFamily(link, family: family) }+            event.setValue(title, forKey: "title")+            event.setValue(date, forKey: "date")+            event.setValue(type.trimmingCharacters(in: .whitespacesAndNewlines), forKey: "type")+            event.setValue(notes, forKey: "notes")+            event.setValue(person, forKey: "subjectPerson")+            event.setValue(source, forKey: "context")+            event.setValue(Date(), forKey: "modifiedAt")+            return event+        }+    }++    func event(_ id: NSManagedObjectID) throws -> EventRow { try eventRow(readable(id, entity: "Event")) }++    func eventRow(_ event: NSManagedObject) -> EventRow {+        EventRow(id: event.objectID, title: event.value(forKey: "title") as? String ?? "Untitled",+                 date: event.value(forKey: "date") as? Date, notes: event.value(forKey: "notes") as? String ?? "",+                 type: event.value(forKey: "type") as? String ?? "",+                 subjectID: (event.value(forKey: "subjectPerson") as? NSManagedObject)?.objectID,+                 contextID: (event.value(forKey: "context") as? NSManagedObject)?.objectID,+                 isArchived: event.value(forKey: "archivedAt") != nil)+    }++    func archiveEvent(_ id: NSManagedObjectID, archived: Bool) throws {+        _ = try write { context in+            let event = try record(id, entity: "Event", in: context)+            event.setValue(archived ? Date() : nil, forKey: "archivedAt")+            event.setValue(Date(), forKey: "modifiedAt")+            return event+        }+    }++    func saveParticipant(eventID: NSManagedObjectID, personID: NSManagedObjectID, roles: Set<String>,+                         invitation: InvitationState, attendance: AttendanceState, note: String = "",+                         expected: ParticipantRow? = nil) throws {+        _ = try write { context in+            let event = try record(eventID, entity: "Event", in: context)+            let person = try record(personID, entity: "Person", in: context)+            let family = try family(of: event)+            try requireSameFamily(person, family: family)+            let participant: NSManagedObject+            if let expected {+                participant = try record(expected.id, entity: "EventPerson", in: context)+                guard (participant.value(forKey: "event") as? NSManagedObject)?.objectID == eventID,+                      sameParticipation(participantRow(participant), expected),+                          expected.personID == personID else { throw MemoryError.changed }+            } else {+                let request = NSFetchRequest<NSManagedObject>(entityName: "EventPerson")+                request.predicate = NSPredicate(format: "event == %@ AND person == %@", event, person)+                guard try context.count(for: request) == 0 else { throw MemoryError.changed }+                participant = insert("EventPerson", in: context, store: try owningStore(of: family))+                participant.setValue(family, forKey: "familySpace")+                participant.setValue(event, forKey: "event")+                participant.setValue(person, forKey: "person")+            }+            let cleaned = Set(roles.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty })+            participant.setValue(String(data: try JSONEncoder().encode(cleaned.sorted()), encoding: .utf8), forKey: "roles")+            participant.setValue(invitation.rawValue, forKey: "invitationState")+            participant.setValue(attendance.rawValue, forKey: "attendanceState")+            participant.setValue(note, forKey: "note")+            return participant+        }+    }++    func participants(_ eventID: NSManagedObjectID) throws -> [ParticipantRow] {+        let request = NSFetchRequest<NSManagedObject>(entityName: "EventPerson")+        request.predicate = NSPredicate(format: "event == %@", eventID)+        request.sortDescriptors = [NSSortDescriptor(key: "person.displayName", ascending: true)]+        return try stack.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.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.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.fetch(participation) + stack.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) }+    }+}
Halo Family/Halo Family/Persistence/ExtensionAccess.swift Added +38 / -0
diff --git a/Halo Family/Halo Family/Persistence/ExtensionAccess.swift b/Halo Family/Halo Family/Persistence/ExtensionAccess.swiftnew file mode 100644index 0000000..298d8ee--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ExtensionAccess.swift	@@ -0,0 +1,38 @@+import Foundation++nonisolated struct FamilyAccessID: Codable, Hashable, Sendable {+    let family: UUID+    let shared: Bool+}++nonisolated struct ExtensionAccess: Codable, Equatable, Sendable {+    let version: Int+    let namespace: String+    let readable: Set<FamilyAccessID>+    let writable: Set<FamilyAccessID>+    let locked: Bool++    static func read(in directory: URL, namespace: String) throws -> ExtensionAccess {+        guard !FileManager.default.fileExists(atPath: directory.appendingPathComponent("AccessLocked").path) else {+            throw AccessError.accountChanged+        }+        let file = directory.appendingPathComponent("ExtensionAccess.json")+        let handle = try FileHandle(forReadingFrom: file)+        defer { try? handle.close() }+        var data = Data()+        while let chunk = try handle.read(upToCount: 65_536), !chunk.isEmpty {+            data.append(chunk)+            guard data.count <= 1_000_000 else { throw AccessError.accountChanged }+        }+        guard let value = try? JSONDecoder().decode(Self.self, from: data), value.version == 1,+              value.namespace == namespace, !value.locked,+              value.writable.isSubset(of: value.readable) else { throw AccessError.accountChanged }+        return value+    }++    func save(in directory: URL) throws {+        let data = try JSONEncoder().encode(self)+        guard data.count <= 1_000_000 else { throw BackupError.tooLarge }+        try data.write(to: directory.appendingPathComponent("ExtensionAccess.json"), options: .atomic)+    }+}
Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift Added +302 / -0
diff --git a/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift b/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swiftnew file mode 100644index 0000000..3bcb397--- /dev/null+++ b/Halo Family/Halo Family/Persistence/FamilyMemoryRepository.swift	@@ -0,0 +1,302 @@+import CoreData+import Foundation++nonisolated struct PartialDate: Equatable, Sendable {+    let year: Int?+    let month: Int?+    let day: Int?++    init(year: Int? = nil, month: Int? = nil, day: Int? = nil) throws {+        guard year != nil || (month == nil && day == nil), month != nil || day == nil,+              year.map({ (1...9999).contains($0) }) ?? true,+              month.map({ (1...12).contains($0) }) ?? true else { throw MemoryError.invalidDate }+        if let year, let month, let day {+            var calendar = Calendar(identifier: .gregorian)+            calendar.timeZone = TimeZone(secondsFromGMT: 0)!+            let parts = DateComponents(year: year, month: month, day: day)+            guard let date = calendar.date(from: parts), calendar.dateComponents([.year, .month, .day], from: date) == parts else {+                throw MemoryError.invalidDate+            }+        }+        self.year = year+        self.month = month+        self.day = day+    }++    var label: String {+        [year.map(String.init), month.map { String(format: "%02d", $0) }, day.map { String(format: "%02d", $0) }]+            .compactMap { $0 }.joined(separator: "-")+    }+}++struct SensitiveSnapshot: Equatable {+    let isDeceased: Bool+    let date: PartialDate+}++nonisolated enum StructuralKind: String, CaseIterable, Sendable {+    case parentOf, guardianOf, siblingOf, partnerOf+    var label: String {+        switch self {+        case .parentOf: "Parent of"+        case .guardianOf: "Guardian of"+        case .siblingOf: "Sibling of"+        case .partnerOf: "Partner of"+        }+    }+}++struct FamilyFactRow: Identifiable {+    let id: NSManagedObjectID+    let sourceID: NSManagedObjectID+    let targetID: NSManagedObjectID+    let source: String+    let target: String+    let label: String+    let nature: String+    let startedAt: Date?+    let endedAt: Date?+    let note: String+    let asserted: Bool+    var isArchived = false+}++struct AddressLabelRow: Identifiable, Equatable {+    let id: NSManagedObjectID+    let label: String+    let usedBy: String+    let language: String+    let script: String+    let usedByPersonID: NSManagedObjectID?+    let usedByGroupID: NSManagedObjectID?+}++struct GroupMemberRow: Identifiable {+    let id: NSManagedObjectID+    let personID: NSManagedObjectID+    let name: String+    let role: String+    let startedAt: Date?+    let endedAt: Date?+}++@MainActor+extension FamilyRepository {+    func primaryPhoto(_ personID: NSManagedObjectID) throws -> NSManagedObjectID? {+        (try readable(personID, entity: "Person").value(forKey: "primaryPhoto") as? NSManagedObject)?.objectID+    }++    func removePhoto(_ personID: NSManagedObjectID) throws {+        _ = try write { context in+            let person = try record(personID, entity: "Person", in: context)+            person.setValue(nil, forKey: "primaryPhoto")+            person.setValue(Date(), forKey: "modifiedAt")+            return person+        }+    }+    func sensitiveDetails(_ personID: NSManagedObjectID) throws -> SensitiveSnapshot {+        try sensitiveSnapshot(readable(personID, entity: "Person"))+    }++    func setSensitiveDetails(_ personID: NSManagedObjectID, deceased: Bool, date: PartialDate,+                             expected: SensitiveSnapshot) throws {+        guard deceased || date.year == nil else { throw MemoryError.invalidDate }+        _ = try write { context in+            let person = try record(personID, entity: "Person", in: context)+            guard try sensitiveSnapshot(person) == expected else { throw MemoryError.changed }+            person.setValue(deceased, forKey: "isDeceased")+            person.setValue(date.year, forKey: "deathYear")+            person.setValue(date.month, forKey: "deathMonth")+            person.setValue(date.day, forKey: "deathDay")+            person.setValue(Date(), forKey: "modifiedAt")+            return person+        }+    }++    private func sensitiveSnapshot(_ person: NSManagedObject) throws -> SensitiveSnapshot {+        SensitiveSnapshot(isDeceased: person.value(forKey: "isDeceased") as? Bool ?? false,+                          date: try PartialDate(year: (person.value(forKey: "deathYear") as? NSNumber)?.intValue,+                                                month: (person.value(forKey: "deathMonth") as? NSNumber)?.intValue,+                                                day: (person.value(forKey: "deathDay") as? NSNumber)?.intValue))+    }++    func addFamilyFact(sourceID: NSManagedObjectID, targetID: NSManagedObjectID, kind: StructuralKind?,+                       label: String = "", nature: String = "", dates: (Date?, Date?) = (nil, nil), note: String = "") throws {+        let label = label.trimmingCharacters(in: .whitespacesAndNewlines)+        guard sourceID != targetID, kind != nil || !label.isEmpty,+              ["", "biological", "adoptive", "step", "foster", "unknown"].contains(nature) else {+            throw MemoryError.invalidRelationship+        }+        try validateDates(dates.0, dates.1)+        _ = try write { context in+            let source = try record(sourceID, entity: "Person", in: context)+            let target = try record(targetID, entity: "Person", in: context)+            let family = try family(of: source)+            try requireSameFamily(target, family: family)+            let fact = insert(kind == nil ? "RelationshipAssertion" : "PersonRelationship", in: context, store: try owningStore(of: family))+            fact.setValue(family, forKey: "familySpace")+            fact.setValue(source, forKey: "source")+            fact.setValue(target, forKey: "target")+            fact.setValue(kind?.rawValue, forKey: "kind")+            if kind == nil { fact.setValue(label, forKey: "customLabel") }+            if kind != nil { fact.setValue(nature.isEmpty ? nil : nature, forKey: "nature") }+            fact.setValue(note, forKey: "note")+            fact.setValue(dates.0, forKey: "startedAt")+            fact.setValue(dates.1, forKey: "endedAt")+            return fact+        }+    }++    func familyFacts(for personID: NSManagedObjectID, includeArchived: Bool = false) throws -> [FamilyFactRow] {+        try ["PersonRelationship", "RelationshipAssertion"].flatMap { entity in+            let request = NSFetchRequest<NSManagedObject>(entityName: entity)+            let modern = stack.container.managedObjectModel.entitiesByName[entity]?.attributesByName["archivedAt"] != nil+            let pair = NSPredicate(format: "source == %@ OR target == %@", personID, personID)+            request.predicate = modern && !includeArchived ?+                NSCompoundPredicate(andPredicateWithSubpredicates: [pair, NSPredicate(format: "archivedAt == nil")]) : pair+            return try stack.fetch(request).compactMap { fact -> FamilyFactRow? in+                guard let source = fact.value(forKey: "source") as? NSManagedObject,+                      let target = fact.value(forKey: "target") as? NSManagedObject else { return nil }+                let asserted = entity == "RelationshipAssertion"+                return FamilyFactRow(id: fact.objectID, sourceID: source.objectID, targetID: target.objectID,+                                     source: source.value(forKey: "displayName") as? String ?? "Unnamed",+                                     target: target.value(forKey: "displayName") as? String ?? "Unnamed",+                                     label: asserted ? fact.value(forKey: "customLabel") as? String ?? "Relationship" :+                                        StructuralKind(rawValue: fact.value(forKey: "kind") as? String ?? "")?.label ?? "Relationship",+                                     nature: asserted ? "" : fact.value(forKey: "nature") as? String ?? "",+                                     startedAt: fact.value(forKey: "startedAt") as? Date,+                                     endedAt: fact.value(forKey: "endedAt") as? Date,+                                     note: fact.value(forKey: "note") as? String ?? "", asserted: asserted,+                                     isArchived: modern && fact.value(forKey: "archivedAt") != nil)+            }+        }+    }++    func endFamilyFact(_ id: NSManagedObjectID, at date: Date) throws {+        guard let entity = id.entity.name, ["PersonRelationship", "RelationshipAssertion"].contains(entity) else {+            throw GraphError.invalidReference+        }+        _ = try write { context in+            let fact = try record(id, entity: entity, in: context)+            guard fact.value(forKey: "endedAt") == nil else { throw MemoryError.changed }+            try validateDates(fact.value(forKey: "startedAt") as? Date, date)+            fact.setValue(date, forKey: "endedAt")+            return fact+        }+    }++    func groups(in familyID: NSManagedObjectID, includeArchived: Bool = false) throws -> [GraphRow] {+        let predicate = includeArchived ? NSPredicate(format: "familySpace == %@", familyID) :+            NSPredicate(format: "familySpace == %@ AND archivedAt == nil", familyID)+        return try rows(entity: "PersonGroup", nameKey: "name", predicate: predicate)+    }++    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.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 let linkedGroup = membership.value(forKey: "group") as? NSManagedObject else { throw GraphError.invalidReference }+            let group = try record(linkedGroup.objectID, entity: "PersonGroup", in: context)+            try requireSameFamily(group, family: family(of: membership))+            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.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+        }+    }+}
Halo Family/Halo Family/Persistence/FamilyRepository.swift Modified +136 / -18
diff --git a/Halo Family/Halo Family/Persistence/FamilyRepository.swift b/Halo Family/Halo Family/Persistence/FamilyRepository.swiftindex 930c20b..77d5d0c 100644--- a/Halo Family/Halo Family/Persistence/FamilyRepository.swift	+++ b/Halo Family/Halo Family/Persistence/FamilyRepository.swift	@@ -4,6 +4,7 @@ import Foundation struct GraphRow: Identifiable, Equatable {     let id: NSManagedObjectID     let name: String+    var isArchived = false }  enum GraphError: LocalizedError {@@ -12,6 +13,18 @@ enum GraphError: LocalizedError {     case invalidReference     case differentFamily     case duplicateConnection+    case duplicateMembership+    case invalidDates+    case contextCycle+    case invalidOrigin+    case readOnly+    case originChanged+    case personChanged+    case originConflict+    case stateChanged+    case stateConflict+    case invalidState+    case roleChanged      var errorDescription: String? {         switch self {@@ -20,6 +33,18 @@ enum GraphError: LocalizedError {         case .invalidReference: "This record is no longer available. Select it again."         case .differentFamily: "These records must belong to the same family."         case .duplicateConnection: "This child already knows this person."+        case .duplicateMembership: "This connection already has a current membership in this context."+        case .invalidDates: "The end date must not be earlier than the start date."+        case .contextCycle: "A context cannot be inside itself or one of its descendants."+        case .invalidOrigin: "Choose one context or event, or enter a description of the first meeting."+        case .readOnly: "You don’t have permission to edit this family."+        case .originChanged: "The first-meeting record changed. Reopen it before saving."+        case .personChanged: "This person’s details changed. Reopen them before saving."+        case .originConflict: "There are different first-meeting accounts. Review them before editing."+        case .stateChanged: "The relationship changed. Reopen it before saving."+        case .stateConflict: "There are overlapping relationship changes. Their history has been retained for review."+        case .invalidState: "A relationship history record could not be read. Its stored value has been preserved."+        case .roleChanged: "This role association changed. Reopen it before saving."         }     } }@@ -37,22 +62,47 @@ final class FamilyRepository {         try rows(entity: "FamilySpace", nameKey: "name")     } -    func children(in family: NSManagedObjectID) throws -> [GraphRow] {-        try rows(entity: "ChildProfile", nameKey: "person.displayName", predicate: NSPredicate(format: "familySpace == %@", family))+    func children(in family: NSManagedObjectID, includeArchived: Bool = false) throws -> [GraphRow] {+        let modern = stack.container.managedObjectModel.entitiesByName["ChildProfile"]?.attributesByName["archivedAt"] != nil+        var predicates = [NSPredicate(format: "familySpace == %@", family)]+        if modern {+            predicates.append(NSPredicate(format: "mergedInto == nil"))+            if !includeArchived { predicates.append(NSPredicate(format: "archivedAt == nil")) }+        }+        if stack.container.managedObjectModel.entitiesByName["Person"]?.attributesByName["archivedAt"] != nil {+            predicates.append(NSPredicate(format: "person.mergedInto == nil"))+            if !includeArchived { predicates.append(NSPredicate(format: "person.archivedAt == nil")) }+        }+        return try rows(entity: "ChildProfile", nameKey: "person.displayName",+                        predicate: NSCompoundPredicate(andPredicateWithSubpredicates: predicates))     }      /// Fetch Connections directly rather than depending on inverse relationship invalidation.-    func connections(for child: NSManagedObjectID) throws -> [GraphRow] {-        try rows(entity: "Connection", nameKey: "person.displayName", predicate: NSPredicate(format: "child == %@", child))+    func connections(for child: NSManagedObjectID, includeDeceased: Bool = true) throws -> [GraphRow] {+        var predicates = [NSPredicate(format: "child == %@", child)]+        if !includeDeceased {+            predicates.append(NSPredicate(format: "person.isDeceased == NO OR person.isDeceased == nil"))+        }+        if stack.container.managedObjectModel.entitiesByName["Person"]?.relationshipsByName["mergedInto"] != nil {+            predicates.append(NSPredicate(format: "person.mergedInto == nil AND person.archivedAt == nil"))+        }+        if stack.container.managedObjectModel.entitiesByName["Connection"]?.attributesByName["archivedAt"] != nil {+            predicates.append(NSPredicate(format: "archivedAt == nil AND mergedInto == nil"))+        }+        return try rows(entity: "Connection", nameKey: "person.displayName",+            predicate: NSCompoundPredicate(andPredicateWithSubpredicates: predicates))     }      func createFamily(name: String) throws -> NSManagedObjectID {+        guard stack.role == .host else { throw GraphError.readOnly }         let name = try validated(name)         return try write { context in             let family = insert("FamilySpace", in: context, store: stack.privateStore)             family.setValue(name, forKey: "name")             family.setValue(Date(), forKey: "createdAt")             family.setValue(Date(), forKey: "modifiedAt")+            try context.obtainPermanentIDs(for: [family])+            try seedCategories(family: family, in: context)             return family         }     }@@ -70,17 +120,45 @@ final class FamilyRepository {         }     } -    func quickCapture(name: String, childID: NSManagedObjectID) throws -> NSManagedObjectID {+    func quickCapture(name: String, childID: NSManagedObjectID, contextID: NSManagedObjectID? = nil) throws -> NSManagedObjectID {         let name = try validated(name)         return try write { context in             let child = try record(childID, entity: "ChildProfile", in: context)+            try validateCaptureChild(child)             guard let family = child.value(forKey: "familySpace") as? NSManagedObject else { throw GraphError.invalidReference }+            let source = try contextID.map { try record($0, entity: "Context", in: context) }+            if let source {+                try requireSameFamily(source, family: family)+                guard source.value(forKey: "archivedAt") == nil else { throw GraphError.invalidReference }+            }             let store = try owningStore(of: family)             let person = makePerson(name: name, family: family, store: store, context: context, needsReview: true)-            return makeConnection(child: child, person: person, family: family, store: store, context: context)+            let connection = makeConnection(child: child, person: person, family: family, store: store, context: context)+            if let source {+                let membership = insert("ConnectionContext", in: context, store: store)+                membership.setValue(family, forKey: "familySpace")+                membership.setValue(connection, forKey: "connection")+                membership.setValue(source, forKey: "context")+            }+            return connection         }     } +    func validateCaptureChild(_ child: NSManagedObject) throws {+        guard child.entity.name == "ChildProfile", !child.isDeleted,+              let person = child.value(forKey: "person") as? NSManagedObject, !person.isDeleted else { throw GraphError.invalidReference }+        for object in [child, person] {+            if object.entity.attributesByName["archivedAt"] != nil,+               object.value(forKey: "archivedAt") != nil { throw GraphError.invalidReference }+            if object.entity.relationshipsByName["mergedInto"] != nil,+               object.value(forKey: "mergedInto") != nil { throw GraphError.invalidReference }+        }+        if person.entity.attributesByName["isDeceased"] != nil,+           person.value(forKey: "isDeceased") as? Bool == true { throw GraphError.invalidReference }+        try requireSameFamily(person, family: family(of: child))+        try stack.access.check(child, writing: true)+    }+     func connect(personID: NSManagedObjectID, childID: NSManagedObjectID) throws -> NSManagedObjectID {         try write { context in             let child = try record(childID, entity: "ChildProfile", in: context)@@ -96,46 +174,86 @@ final class FamilyRepository {         }     } -    private func write(_ operation: (NSManagedObjectContext) throws -> NSManagedObject) throws -> NSManagedObjectID {+    func write(_ operation: (NSManagedObjectContext) throws -> NSManagedObject) throws -> NSManagedObjectID {+        try stack.access.check()+        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)-        try context.save()+        let inserted = Array(context.insertedObjects)+        let updated = Array(context.updatedObjects)+        let deleted = Array(context.deletedObjects)+        let newFamilies = Set(inserted.filter { $0.entity.name == "FamilySpace" }.map(\.objectID))+        var permittedFamilies = Set<FamilyAccessID>()+        let ambiguous = try StoreAccess.ambiguousFamilies(in: context)+        for object in inserted + updated + deleted {+            let family = object.entity.name == "FamilySpace" ? object : object.value(forKey: "familySpace") as? NSManagedObject+            if let family, newFamilies.contains(family.objectID), stack.role == .host,+               family.objectID.persistentStore == stack.privateStore { continue }+            let identity = try StoreAccess.identity(object, checkingDuplicates: false)+            guard !ambiguous.contains(identity) else { throw AccessError.familyUnavailable }+            permittedFamilies.insert(identity)+        }+        try stack.access.save(families: permittedFamilies) { 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])+        do { try stack.refreshAccess() } catch { stack.lockSession() }+        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)]-        return try stack.container.viewContext.fetch(request).map {-            GraphRow(id: $0.objectID, name: $0.value(forKeyPath: nameKey) as? String ?? "Unnamed")+        return try stack.fetch(request).map {+            let ownArchive = $0.entity.attributesByName["archivedAt"] != nil && $0.value(forKey: "archivedAt") != nil+            let person = $0.entity.name == "ChildProfile" ? $0.value(forKey: "person") as? NSManagedObject : nil+            let personArchive = person?.entity.attributesByName["archivedAt"] != nil && person?.value(forKey: "archivedAt") != nil+            return GraphRow(id: $0.objectID, name: $0.value(forKeyPath: nameKey) as? String ?? "Unnamed",+                            isArchived: ownArchive || personArchive)         }     } -    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,+                allowArchived: Bool = false) throws -> NSManagedObject {+        try stack.access.check()+        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 }+        try stack.access.check(object, writing: true)+        if ["Person", "Connection", "ChildProfile"].contains(entity),+           object.entity.relationshipsByName["mergedInto"] != nil,+           object.value(forKey: "mergedInto") != nil { throw MergeError.changed }+        if !allowArchived, ["Person", "Connection", "ChildProfile", "PersonGroup"].contains(entity),+           object.entity.attributesByName["archivedAt"] != nil,+           object.value(forKey: "archivedAt") != nil { throw MergeError.changed }+        if let cloud = stack.container as? NSPersistentCloudKitContainer,+           !cloud.canUpdateRecord(forManagedObjectWith: id) { throw GraphError.readOnly }         return object     } -    private func owningStore(of family: NSManagedObject) throws -> NSPersistentStore {+    func owningStore(of family: NSManagedObject) throws -> NSPersistentStore {         guard let store = family.objectID.persistentStore,               stack.container.persistentStoreCoordinator.persistentStores.contains(store) else { throw GraphError.invalidReference }         return store     } -    private func insert(_ entity: String, in context: NSManagedObjectContext, store: NSPersistentStore) -> NSManagedObject {+    func insert(_ entity: String, in context: NSManagedObjectContext, store: NSPersistentStore) -> NSManagedObject {         let object = NSEntityDescription.insertNewObject(forEntityName: entity, into: context)         context.assign(object, to: store)         object.setValue(UUID(), forKey: "id")         return object     } -    private func makePerson(name: String, family: NSManagedObject, store: NSPersistentStore,-                            context: NSManagedObjectContext, needsReview: Bool) -> NSManagedObject {+    func makePerson(name: String, family: NSManagedObject, store: NSPersistentStore,+                    context: NSManagedObjectContext, needsReview: Bool) -> NSManagedObject {         let person = insert("Person", in: context, store: store)         person.setValue(name, forKey: "displayName")         person.setValue(family, forKey: "familySpace")@@ -155,7 +273,7 @@ final class FamilyRepository {         return connection     } -    private func validated(_ name: String) throws -> String {+    func validated(_ name: String) throws -> String {         let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)         guard !trimmed.isEmpty else { throw GraphError.blankName }         return trimmed
Halo Family/Halo Family/Persistence/FamilySharing.swift Added +105 / -0
diff --git a/Halo Family/Halo Family/Persistence/FamilySharing.swift b/Halo Family/Halo Family/Persistence/FamilySharing.swiftnew file mode 100644index 0000000..2d3896c--- /dev/null+++ b/Halo Family/Halo Family/Persistence/FamilySharing.swift	@@ -0,0 +1,105 @@+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() }+            }+        }+        try stack.access.check()+        try stack.refreshAccess()+    }++    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.+        try stack.didAcceptInvitation(metadata.share.recordID)+        await stack.refreshHistory()+        NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: stack.container)+    }++    private func cloudContainer() throws -> NSPersistentCloudKitContainer {+        try stack.access.check()+        guard stack.role == .host, let cloud = stack.container as? NSPersistentCloudKitContainer else {+            throw SharingError.hostRequired+        }+        return cloud+    }+}
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversion Modified +1 / -1
diff --git a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversion b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversionindex 7a57798..0f17c83 100644--- a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversion	+++ b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/.xccurrentversion	@@ -3,6 +3,6 @@ <plist version="1.0"> <dict> 	<key>_XCCurrentVersionName</key>-	<string>HaloModelV2.xcdatamodel</string>+	<string>HaloModelV6.xcdatamodel</string> </dict> </plist>
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contents Added +100 / -0
diff --git a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contents b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contentsnew file mode 100644index 0000000..bc68ab8--- /dev/null+++ b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV3.xcdatamodel/contents	@@ -0,0 +1,100 @@+<?xml version='1.0' encoding='utf-8'?>+<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" sourceLanguage="Swift" userDefinedModelVersionIdentifier="3" usedWithCloudKit="YES">+  <entity name="FamilySpace" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="name" optional="YES" attributeType="String" />+    <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="familySpace" inverseEntity="Person" toMany="YES" />+    <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="familySpace" inverseEntity="ChildProfile" toMany="YES" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="familySpace" inverseEntity="Connection" toMany="YES" />+    <relationship name="assets" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="familySpace" inverseEntity="Asset" toMany="YES" />+    <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="familySpace" inverseEntity="Context" toMany="YES" />+    <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="familySpace" inverseEntity="Event" toMany="YES" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="familySpace" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="familySpace" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="contextPeople" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="familySpace" inverseEntity="ContextPerson" toMany="YES" />+  </entity>+  <entity name="Person" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="displayName" optional="YES" attributeType="String" />+    <attribute name="needsReview" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="people" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="childProfile" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="person" inverseEntity="ChildProfile" maxCount="1" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="person" inverseEntity="Connection" toMany="YES" />+    <attribute name="givenName" optional="YES" attributeType="String" />+    <attribute name="familyName" optional="YES" attributeType="String" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="contextLinks" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="person" inverseEntity="ContextPerson" toMany="YES" />+  </entity>+  <entity name="ChildProfile" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="isActive" optional="YES" attributeType="Boolean" defaultValueString="YES" usesScalarValueType="YES" />+    <attribute name="displayOrder" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="children" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="childProfile" inverseEntity="Person" maxCount="1" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="child" inverseEntity="Connection" toMany="YES" />+  </entity>+  <entity name="Connection" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="connections" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="child" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="connections" inverseEntity="ChildProfile" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="connections" inverseEntity="Person" maxCount="1" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="connection" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origin" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="connection" inverseEntity="ConnectionOrigin" maxCount="1" />+  </entity>+  <entity name="Asset" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="data" optional="YES" attributeType="Binary" allowsExternalBinaryDataStorage="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="assets" inverseEntity="FamilySpace" maxCount="1" />+  </entity>+  <entity name="Context" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="name" optional="YES" attributeType="String" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contexts" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="parent" inverseEntity="Context" toMany="YES" />+    <relationship name="parent" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="children" inverseEntity="Context" maxCount="1" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="context" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="context" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="context" inverseEntity="ContextPerson" toMany="YES" />+  </entity>+  <entity name="ConnectionContext" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="memberships" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="memberships" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="memberships" inverseEntity="Context" maxCount="1" />+  </entity>+  <entity name="ConnectionOrigin" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="originDescription" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="origins" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="origin" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="origins" inverseEntity="Context" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="origins" inverseEntity="Event" maxCount="1" />+  </entity>+  <entity name="Event" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="title" optional="YES" attributeType="String" />+    <attribute name="date" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="events" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="event" inverseEntity="ConnectionOrigin" toMany="YES" />+  </entity>+  <entity name="ContextPerson" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextPeople" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="people" inverseEntity="Context" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="contextLinks" inverseEntity="Person" maxCount="1" />+  </entity>+</model>\ No newline at end of file
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contents Added +140 / -0
diff --git a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contents b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contentsnew file mode 100644index 0000000..5a844e1--- /dev/null+++ b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV4.xcdatamodel/contents	@@ -0,0 +1,140 @@+<?xml version='1.0' encoding='utf-8'?>+<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" sourceLanguage="Swift" userDefinedModelVersionIdentifier="4" usedWithCloudKit="YES">+  <entity name="FamilySpace" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="name" optional="YES" attributeType="String" />+    <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="familySpace" inverseEntity="Person" toMany="YES" />+    <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="familySpace" inverseEntity="ChildProfile" toMany="YES" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="familySpace" inverseEntity="Connection" toMany="YES" />+    <relationship name="assets" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="familySpace" inverseEntity="Asset" toMany="YES" />+    <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="familySpace" inverseEntity="Context" toMany="YES" />+    <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="familySpace" inverseEntity="Event" toMany="YES" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="familySpace" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="familySpace" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="contextPeople" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="familySpace" inverseEntity="ContextPerson" toMany="YES" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="familySpace" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="familySpace" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+    <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="familySpace" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+  </entity>+  <entity name="Person" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="displayName" optional="YES" attributeType="String" />+    <attribute name="needsReview" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="people" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="childProfile" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="person" inverseEntity="ChildProfile" maxCount="1" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="person" inverseEntity="Connection" toMany="YES" />+    <attribute name="givenName" optional="YES" attributeType="String" />+    <attribute name="familyName" optional="YES" attributeType="String" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="contextLinks" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="person" inverseEntity="ContextPerson" toMany="YES" />+  </entity>+  <entity name="ChildProfile" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="isActive" optional="YES" attributeType="Boolean" defaultValueString="YES" usesScalarValueType="YES" />+    <attribute name="displayOrder" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="children" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="childProfile" inverseEntity="Person" maxCount="1" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="child" inverseEntity="Connection" toMany="YES" />+  </entity>+  <entity name="Connection" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="connections" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="child" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="connections" inverseEntity="ChildProfile" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="connections" inverseEntity="Person" maxCount="1" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="connection" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origin" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="connection" inverseEntity="ConnectionOrigin" maxCount="1" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="connection" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="connection" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+    <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="connection" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+  </entity>+  <entity name="Asset" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="data" optional="YES" attributeType="Binary" allowsExternalBinaryDataStorage="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="assets" inverseEntity="FamilySpace" maxCount="1" />+  </entity>+  <entity name="Context" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="name" optional="YES" attributeType="String" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contexts" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="parent" inverseEntity="Context" toMany="YES" />+    <relationship name="parent" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="children" inverseEntity="Context" maxCount="1" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="context" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="context" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="context" inverseEntity="ContextPerson" toMany="YES" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="context" inverseEntity="OriginProposal" toMany="YES" />+  </entity>+  <entity name="ConnectionContext" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="memberships" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="memberships" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="memberships" inverseEntity="Context" maxCount="1" />+  </entity>+  <entity name="ConnectionOrigin" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="originDescription" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="origins" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="origin" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="origins" inverseEntity="Context" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="origins" inverseEntity="Event" maxCount="1" />+  </entity>+  <entity name="Event" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="title" optional="YES" attributeType="String" />+    <attribute name="date" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="events" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="event" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="event" inverseEntity="OriginProposal" toMany="YES" />+  </entity>+  <entity name="ContextPerson" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextPeople" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="people" inverseEntity="Context" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="contextLinks" inverseEntity="Person" maxCount="1" />+    <attribute name="role" optional="YES" attributeType="String" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+  </entity>+  <entity name="OriginProposal" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="narrative" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="isCleared" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="originProposals" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="originProposals" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="originProposals" inverseEntity="Context" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="originProposals" inverseEntity="Event" maxCount="1" />+    <relationship name="predecessors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="successors" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="successors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="predecessors" inverseEntity="OriginProposal" toMany="YES" />+  </entity>+  <entity name="ConnectionClosenessPeriod" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="value" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="closenessPeriods" inverseEntity="Connection" maxCount="1" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="closenessPeriods" inverseEntity="FamilySpace" maxCount="1" />+  </entity>+  <entity name="ConnectionStatusPeriod" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="state" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="statusPeriods" inverseEntity="Connection" maxCount="1" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="statusPeriods" inverseEntity="FamilySpace" maxCount="1" />+  </entity>+</model>\ No newline at end of file
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contents Added +282 / -0
diff --git a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contents b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contentsnew file mode 100644index 0000000..11690a0--- /dev/null+++ b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV5.xcdatamodel/contents	@@ -0,0 +1,282 @@+<?xml version='1.0' encoding='utf-8'?>+<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" sourceLanguage="Swift" userDefinedModelVersionIdentifier="5" usedWithCloudKit="YES">+  <entity name="FamilySpace" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="name" optional="YES" attributeType="String" />+    <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="familySpace" inverseEntity="Person" toMany="YES" />+    <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="familySpace" inverseEntity="ChildProfile" toMany="YES" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="familySpace" inverseEntity="Connection" toMany="YES" />+    <relationship name="assets" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="familySpace" inverseEntity="Asset" toMany="YES" />+    <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="familySpace" inverseEntity="Context" toMany="YES" />+    <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="familySpace" inverseEntity="Event" toMany="YES" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="familySpace" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="familySpace" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="contextPeople" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="familySpace" inverseEntity="ContextPerson" toMany="YES" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="familySpace" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="familySpace" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+    <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="familySpace" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+    <relationship name="personRelationshipRecords" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="familySpace" inverseEntity="PersonRelationship" toMany="YES" />+    <relationship name="relationshipAssertionRecords" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="familySpace" inverseEntity="RelationshipAssertion" toMany="YES" />+    <relationship name="addressLabelRecords" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="familySpace" inverseEntity="AddressLabel" toMany="YES" />+    <relationship name="personGroupRecords" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="familySpace" inverseEntity="PersonGroup" toMany="YES" />+    <relationship name="groupMembershipRecords" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="familySpace" inverseEntity="GroupMembership" toMany="YES" />+    <relationship name="contextCategoryRecords" optional="YES" deletionRule="Nullify" destinationEntity="ContextCategory" inverseName="familySpace" inverseEntity="ContextCategory" toMany="YES" />+    <relationship name="eventPersonRecords" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="familySpace" inverseEntity="EventPerson" toMany="YES" />+    <relationship name="giftRecordRecords" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="familySpace" inverseEntity="GiftRecord" toMany="YES" />+    <relationship name="eventAttachmentRecords" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="familySpace" inverseEntity="EventAttachment" toMany="YES" />+  </entity>+  <entity name="Person" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="displayName" optional="YES" attributeType="String" />+    <attribute name="needsReview" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="people" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="childProfile" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="person" inverseEntity="ChildProfile" maxCount="1" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="person" inverseEntity="Connection" toMany="YES" />+    <attribute name="givenName" optional="YES" attributeType="String" />+    <attribute name="familyName" optional="YES" attributeType="String" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="contextLinks" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="person" inverseEntity="ContextPerson" toMany="YES" />+    <attribute name="isDeceased" optional="YES" attributeType="Boolean" usesScalarValueType="YES" defaultValueString="NO" />+    <attribute name="deathYear" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+    <attribute name="deathMonth" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+    <attribute name="deathDay" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="mergedInto" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="mergedPeople" inverseEntity="Person" maxCount="1" />+    <relationship name="mergedPeople" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="mergedInto" inverseEntity="Person" toMany="YES" />+    <relationship name="primaryPhoto" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="photoPerson" inverseEntity="Asset" maxCount="1" />+    <relationship name="personRelationshipFrom" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="source" inverseEntity="PersonRelationship" toMany="YES" />+    <relationship name="personRelationshipTo" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="target" inverseEntity="PersonRelationship" toMany="YES" />+    <relationship name="relationshipAssertionFrom" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="source" inverseEntity="RelationshipAssertion" toMany="YES" />+    <relationship name="relationshipAssertionTo" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="target" inverseEntity="RelationshipAssertion" toMany="YES" />+    <relationship name="addressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="target" inverseEntity="AddressLabel" toMany="YES" />+    <relationship name="usedAddressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="usedByPerson" inverseEntity="AddressLabel" toMany="YES" />+    <relationship name="groupMemberships" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="person" inverseEntity="GroupMembership" toMany="YES" />+    <relationship name="subjectEvents" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="subjectPerson" inverseEntity="Event" toMany="YES" />+    <relationship name="eventParticipations" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="person" inverseEntity="EventPerson" toMany="YES" />+    <relationship name="givenGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="givers" inverseEntity="GiftRecord" toMany="YES" />+    <relationship name="receivedGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="recipients" inverseEntity="GiftRecord" toMany="YES" />+  </entity>+  <entity name="ChildProfile" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="isActive" optional="YES" attributeType="Boolean" defaultValueString="YES" usesScalarValueType="YES" />+    <attribute name="displayOrder" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="children" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="childProfile" inverseEntity="Person" maxCount="1" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="child" inverseEntity="Connection" toMany="YES" />+  </entity>+  <entity name="Connection" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="connections" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="child" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="connections" inverseEntity="ChildProfile" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="connections" inverseEntity="Person" maxCount="1" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="connection" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origin" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="connection" inverseEntity="ConnectionOrigin" maxCount="1" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="connection" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="connection" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+    <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="connection" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+  </entity>+  <entity name="Asset" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="data" optional="YES" attributeType="Binary" allowsExternalBinaryDataStorage="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="assets" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="photoPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="primaryPhoto" inverseEntity="Person" maxCount="1" />+    <attribute name="filename" optional="YES" attributeType="String" />+    <attribute name="contentType" optional="YES" attributeType="String" />+    <attribute name="kind" optional="YES" attributeType="String" />+    <attribute name="byteCount" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+    <attribute name="pixelWidth" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+    <attribute name="pixelHeight" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+    <relationship name="eventAttachment" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="asset" inverseEntity="EventAttachment" maxCount="1" />+    <attribute name="contentRevision" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+  </entity>+  <entity name="Context" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="name" optional="YES" attributeType="String" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contexts" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="parent" inverseEntity="Context" toMany="YES" />+    <relationship name="parent" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="children" inverseEntity="Context" maxCount="1" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="context" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="context" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="context" inverseEntity="ContextPerson" toMany="YES" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="context" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="category" optional="YES" deletionRule="Nullify" destinationEntity="ContextCategory" inverseName="contexts" inverseEntity="ContextCategory" maxCount="1" />+    <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="context" inverseEntity="Event" toMany="YES" />+  </entity>+  <entity name="ConnectionContext" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="memberships" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="memberships" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="memberships" inverseEntity="Context" maxCount="1" />+  </entity>+  <entity name="ConnectionOrigin" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="originDescription" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="origins" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="origin" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="origins" inverseEntity="Context" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="origins" inverseEntity="Event" maxCount="1" />+  </entity>+  <entity name="Event" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="title" optional="YES" attributeType="String" />+    <attribute name="date" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="events" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="event" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="event" inverseEntity="OriginProposal" toMany="YES" />+    <attribute name="type" optional="YES" attributeType="String" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endDate" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="subjectPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="subjectEvents" inverseEntity="Person" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="events" inverseEntity="Context" maxCount="1" />+    <relationship name="participants" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="event" inverseEntity="EventPerson" toMany="YES" />+    <relationship name="gifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="event" inverseEntity="GiftRecord" toMany="YES" />+    <relationship name="attachments" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="event" inverseEntity="EventAttachment" toMany="YES" />+  </entity>+  <entity name="ContextPerson" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextPeople" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="people" inverseEntity="Context" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="contextLinks" inverseEntity="Person" maxCount="1" />+    <attribute name="role" optional="YES" attributeType="String" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+  </entity>+  <entity name="OriginProposal" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="narrative" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="isCleared" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="originProposals" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="originProposals" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="originProposals" inverseEntity="Context" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="originProposals" inverseEntity="Event" maxCount="1" />+    <relationship name="predecessors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="successors" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="successors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="predecessors" inverseEntity="OriginProposal" toMany="YES" />+  </entity>+  <entity name="ConnectionClosenessPeriod" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="value" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="closenessPeriods" inverseEntity="Connection" maxCount="1" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="closenessPeriods" inverseEntity="FamilySpace" maxCount="1" />+  </entity>+  <entity name="ConnectionStatusPeriod" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="state" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="statusPeriods" inverseEntity="Connection" maxCount="1" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="statusPeriods" inverseEntity="FamilySpace" maxCount="1" />+  </entity>+  <entity name="PersonRelationship" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personRelationshipRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="source" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="personRelationshipFrom" inverseEntity="Person" maxCount="1" />+    <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="personRelationshipTo" inverseEntity="Person" maxCount="1" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="kind" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="nature" optional="YES" attributeType="String" />+  </entity>+  <entity name="RelationshipAssertion" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="relationshipAssertionRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="source" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="relationshipAssertionFrom" inverseEntity="Person" maxCount="1" />+    <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="relationshipAssertionTo" inverseEntity="Person" maxCount="1" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="kind" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="customLabel" optional="YES" attributeType="String" />+    <attribute name="side" optional="YES" attributeType="String" />+    <attribute name="relatedBy" optional="YES" attributeType="String" />+  </entity>+  <entity name="AddressLabel" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="addressLabelRecords" inverseEntity="FamilySpace" maxCount="1" />+    <attribute name="label" optional="YES" attributeType="String" />+    <attribute name="language" optional="YES" attributeType="String" />+    <attribute name="script" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="isPreferred" optional="YES" attributeType="Boolean" usesScalarValueType="YES" defaultValueString="NO" />+    <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="addressLabels" inverseEntity="Person" maxCount="1" />+    <relationship name="usedByPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="usedAddressLabels" inverseEntity="Person" maxCount="1" />+    <relationship name="usedByGroup" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="usedAddressLabels" inverseEntity="PersonGroup" maxCount="1" />+  </entity>+  <entity name="PersonGroup" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personGroupRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="usedAddressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="usedByGroup" inverseEntity="AddressLabel" toMany="YES" />+    <attribute name="name" optional="YES" attributeType="String" />+    <attribute name="type" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="group" inverseEntity="GroupMembership" toMany="YES" />+    <relationship name="givenGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="giverGroups" inverseEntity="GiftRecord" toMany="YES" />+  </entity>+  <entity name="GroupMembership" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="groupMembershipRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="group" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="memberships" inverseEntity="PersonGroup" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="groupMemberships" inverseEntity="Person" maxCount="1" />+    <attribute name="role" optional="YES" attributeType="String" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+  </entity>+  <entity name="ContextCategory" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextCategoryRecords" inverseEntity="FamilySpace" maxCount="1" />+    <attribute name="name" optional="YES" attributeType="String" />+    <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="category" inverseEntity="Context" toMany="YES" />+  </entity>+  <entity name="EventPerson" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="eventPersonRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="participants" inverseEntity="Event" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="eventParticipations" inverseEntity="Person" maxCount="1" />+    <attribute name="roles" optional="YES" attributeType="String" />+    <attribute name="invitationState" optional="YES" attributeType="String" />+    <attribute name="attendanceState" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+  </entity>+  <entity name="GiftRecord" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="giftRecordRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="gifts" inverseEntity="Event" maxCount="1" />+    <attribute name="descriptionText" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <relationship name="givers" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="givenGifts" inverseEntity="Person" toMany="YES" />+    <relationship name="giverGroups" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="givenGifts" inverseEntity="PersonGroup" toMany="YES" />+    <relationship name="recipients" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="receivedGifts" inverseEntity="Person" toMany="YES" />+    <relationship name="attachments" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="gifts" inverseEntity="EventAttachment" toMany="YES" />+  </entity>+  <entity name="EventAttachment" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="eventAttachmentRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="attachments" inverseEntity="Event" maxCount="1" />+    <relationship name="asset" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="eventAttachment" inverseEntity="Asset" maxCount="1" />+    <relationship name="gifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="attachments" inverseEntity="GiftRecord" toMany="YES" />+    <attribute name="kind" optional="YES" attributeType="String" />+    <attribute name="title" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+  </entity>+</model>\ No newline at end of file
Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV6.xcdatamodel/contents Added +324 / -0
diff --git a/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV6.xcdatamodel/contents b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV6.xcdatamodel/contentsnew file mode 100644index 0000000..42db605--- /dev/null+++ b/Halo Family/Halo Family/Persistence/HaloModel.xcdatamodeld/HaloModelV6.xcdatamodel/contents	@@ -0,0 +1,324 @@+<?xml version='1.0' encoding='utf-8'?>+<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" sourceLanguage="Swift" userDefinedModelVersionIdentifier="6" usedWithCloudKit="YES">+  <entity name="FamilySpace" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="name" optional="YES" attributeType="String" />+    <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="familySpace" inverseEntity="Person" toMany="YES" />+    <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="familySpace" inverseEntity="ChildProfile" toMany="YES" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="familySpace" inverseEntity="Connection" toMany="YES" />+    <relationship name="assets" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="familySpace" inverseEntity="Asset" toMany="YES" />+    <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="familySpace" inverseEntity="Context" toMany="YES" />+    <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="familySpace" inverseEntity="Event" toMany="YES" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="familySpace" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="familySpace" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="contextPeople" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="familySpace" inverseEntity="ContextPerson" toMany="YES" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="familySpace" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="familySpace" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+    <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="familySpace" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+    <relationship name="personRelationshipRecords" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="familySpace" inverseEntity="PersonRelationship" toMany="YES" />+    <relationship name="relationshipAssertionRecords" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="familySpace" inverseEntity="RelationshipAssertion" toMany="YES" />+    <relationship name="addressLabelRecords" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="familySpace" inverseEntity="AddressLabel" toMany="YES" />+    <relationship name="personGroupRecords" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="familySpace" inverseEntity="PersonGroup" toMany="YES" />+    <relationship name="groupMembershipRecords" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="familySpace" inverseEntity="GroupMembership" toMany="YES" />+    <relationship name="contextCategoryRecords" optional="YES" deletionRule="Nullify" destinationEntity="ContextCategory" inverseName="familySpace" inverseEntity="ContextCategory" toMany="YES" />+    <relationship name="eventPersonRecords" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="familySpace" inverseEntity="EventPerson" toMany="YES" />+    <relationship name="giftRecordRecords" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="familySpace" inverseEntity="GiftRecord" toMany="YES" />+    <relationship name="eventAttachmentRecords" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="familySpace" inverseEntity="EventAttachment" toMany="YES" />+    <relationship name="personMerges" optional="YES" deletionRule="Nullify" destinationEntity="PersonMerge" inverseName="familySpace" inverseEntity="PersonMerge" toMany="YES" />+    <relationship name="mergeConnectionReviews" optional="YES" deletionRule="Nullify" destinationEntity="MergeConnectionReview" inverseName="familySpace" inverseEntity="MergeConnectionReview" toMany="YES" />+    <relationship name="personMergeRecoveries" optional="YES" deletionRule="Nullify" destinationEntity="PersonMergeRecovery" inverseName="familySpace" inverseEntity="PersonMergeRecovery" toMany="YES" />+  </entity>+  <entity name="Person" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="displayName" optional="YES" attributeType="String" />+    <attribute name="needsReview" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="people" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="childProfile" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="person" inverseEntity="ChildProfile" maxCount="1" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="person" inverseEntity="Connection" toMany="YES" />+    <attribute name="givenName" optional="YES" attributeType="String" />+    <attribute name="familyName" optional="YES" attributeType="String" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="contextLinks" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="person" inverseEntity="ContextPerson" toMany="YES" />+    <attribute name="isDeceased" optional="YES" attributeType="Boolean" usesScalarValueType="YES" defaultValueString="NO" />+    <attribute name="deathYear" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+    <attribute name="deathMonth" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+    <attribute name="deathDay" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="mergedInto" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="mergedPeople" inverseEntity="Person" maxCount="1" />+    <relationship name="mergedPeople" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="mergedInto" inverseEntity="Person" toMany="YES" />+    <relationship name="primaryPhoto" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="photoPerson" inverseEntity="Asset" maxCount="1" />+    <relationship name="personRelationshipFrom" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="source" inverseEntity="PersonRelationship" toMany="YES" />+    <relationship name="personRelationshipTo" optional="YES" deletionRule="Nullify" destinationEntity="PersonRelationship" inverseName="target" inverseEntity="PersonRelationship" toMany="YES" />+    <relationship name="relationshipAssertionFrom" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="source" inverseEntity="RelationshipAssertion" toMany="YES" />+    <relationship name="relationshipAssertionTo" optional="YES" deletionRule="Nullify" destinationEntity="RelationshipAssertion" inverseName="target" inverseEntity="RelationshipAssertion" toMany="YES" />+    <relationship name="addressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="target" inverseEntity="AddressLabel" toMany="YES" />+    <relationship name="usedAddressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="usedByPerson" inverseEntity="AddressLabel" toMany="YES" />+    <relationship name="groupMemberships" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="person" inverseEntity="GroupMembership" toMany="YES" />+    <relationship name="subjectEvents" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="subjectPerson" inverseEntity="Event" toMany="YES" />+    <relationship name="eventParticipations" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="person" inverseEntity="EventPerson" toMany="YES" />+    <relationship name="givenGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="givers" inverseEntity="GiftRecord" toMany="YES" />+    <relationship name="receivedGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="recipients" inverseEntity="GiftRecord" toMany="YES" />+  </entity>+  <entity name="ChildProfile" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="isActive" optional="YES" attributeType="Boolean" defaultValueString="YES" usesScalarValueType="YES" />+    <attribute name="displayOrder" optional="YES" attributeType="Integer 64" defaultValueString="0" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="children" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="childProfile" inverseEntity="Person" maxCount="1" />+    <relationship name="connections" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="child" inverseEntity="Connection" toMany="YES" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="mergedInto" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="mergedRecords" inverseEntity="ChildProfile" maxCount="1" />+    <relationship name="mergedRecords" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="mergedInto" inverseEntity="ChildProfile" toMany="YES" />+  </entity>+  <entity name="Connection" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="connections" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="child" optional="YES" deletionRule="Nullify" destinationEntity="ChildProfile" inverseName="connections" inverseEntity="ChildProfile" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="connections" inverseEntity="Person" maxCount="1" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="connection" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origin" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="connection" inverseEntity="ConnectionOrigin" maxCount="1" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="connection" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="closenessPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionClosenessPeriod" inverseName="connection" inverseEntity="ConnectionClosenessPeriod" toMany="YES" />+    <relationship name="statusPeriods" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionStatusPeriod" inverseName="connection" inverseEntity="ConnectionStatusPeriod" toMany="YES" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="mergedInto" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="mergedRecords" inverseEntity="Connection" maxCount="1" />+    <relationship name="mergedRecords" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="mergedInto" inverseEntity="Connection" toMany="YES" />+  </entity>+  <entity name="Asset" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="data" optional="YES" attributeType="Binary" allowsExternalBinaryDataStorage="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="assets" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="photoPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="primaryPhoto" inverseEntity="Person" maxCount="1" />+    <attribute name="filename" optional="YES" attributeType="String" />+    <attribute name="contentType" optional="YES" attributeType="String" />+    <attribute name="kind" optional="YES" attributeType="String" />+    <attribute name="byteCount" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+    <attribute name="pixelWidth" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+    <attribute name="pixelHeight" optional="YES" attributeType="Integer 64" usesScalarValueType="NO" />+    <relationship name="eventAttachment" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="asset" inverseEntity="EventAttachment" maxCount="1" />+    <attribute name="contentRevision" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+  </entity>+  <entity name="Context" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="name" optional="YES" attributeType="String" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contexts" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="children" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="parent" inverseEntity="Context" toMany="YES" />+    <relationship name="parent" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="children" inverseEntity="Context" maxCount="1" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionContext" inverseName="context" inverseEntity="ConnectionContext" toMany="YES" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="context" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="people" optional="YES" deletionRule="Nullify" destinationEntity="ContextPerson" inverseName="context" inverseEntity="ContextPerson" toMany="YES" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="context" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="category" optional="YES" deletionRule="Nullify" destinationEntity="ContextCategory" inverseName="contexts" inverseEntity="ContextCategory" maxCount="1" />+    <relationship name="events" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="context" inverseEntity="Event" toMany="YES" />+  </entity>+  <entity name="ConnectionContext" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="memberships" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="memberships" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="memberships" inverseEntity="Context" maxCount="1" />+  </entity>+  <entity name="ConnectionOrigin" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="originDescription" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="origins" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="origin" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="origins" inverseEntity="Context" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="origins" inverseEntity="Event" maxCount="1" />+  </entity>+  <entity name="Event" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="title" optional="YES" attributeType="String" />+    <attribute name="date" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="events" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="origins" optional="YES" deletionRule="Nullify" destinationEntity="ConnectionOrigin" inverseName="event" inverseEntity="ConnectionOrigin" toMany="YES" />+    <relationship name="originProposals" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="event" inverseEntity="OriginProposal" toMany="YES" />+    <attribute name="type" optional="YES" attributeType="String" />+    <attribute name="modifiedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endDate" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="subjectPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="subjectEvents" inverseEntity="Person" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="events" inverseEntity="Context" maxCount="1" />+    <relationship name="participants" optional="YES" deletionRule="Nullify" destinationEntity="EventPerson" inverseName="event" inverseEntity="EventPerson" toMany="YES" />+    <relationship name="gifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="event" inverseEntity="GiftRecord" toMany="YES" />+    <relationship name="attachments" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="event" inverseEntity="EventAttachment" toMany="YES" />+  </entity>+  <entity name="ContextPerson" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="notes" optional="YES" attributeType="String" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextPeople" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="people" inverseEntity="Context" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="contextLinks" inverseEntity="Person" maxCount="1" />+    <attribute name="role" optional="YES" attributeType="String" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+  </entity>+  <entity name="OriginProposal" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="narrative" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="isCleared" optional="YES" attributeType="Boolean" defaultValueString="NO" usesScalarValueType="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="originProposals" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="originProposals" inverseEntity="Connection" maxCount="1" />+    <relationship name="context" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="originProposals" inverseEntity="Context" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="originProposals" inverseEntity="Event" maxCount="1" />+    <relationship name="predecessors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="successors" inverseEntity="OriginProposal" toMany="YES" />+    <relationship name="successors" optional="YES" deletionRule="Nullify" destinationEntity="OriginProposal" inverseName="predecessors" inverseEntity="OriginProposal" toMany="YES" />+  </entity>+  <entity name="ConnectionClosenessPeriod" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="value" optional="YES" attributeType="Integer 16" usesScalarValueType="NO" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="closenessPeriods" inverseEntity="Connection" maxCount="1" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="closenessPeriods" inverseEntity="FamilySpace" maxCount="1" />+  </entity>+  <entity name="ConnectionStatusPeriod" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="state" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="connection" optional="YES" deletionRule="Nullify" destinationEntity="Connection" inverseName="statusPeriods" inverseEntity="Connection" maxCount="1" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="statusPeriods" inverseEntity="FamilySpace" maxCount="1" />+  </entity>+  <entity name="PersonRelationship" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personRelationshipRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="source" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="personRelationshipFrom" inverseEntity="Person" maxCount="1" />+    <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="personRelationshipTo" inverseEntity="Person" maxCount="1" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="kind" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="nature" optional="YES" attributeType="String" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+  </entity>+  <entity name="RelationshipAssertion" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="relationshipAssertionRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="source" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="relationshipAssertionFrom" inverseEntity="Person" maxCount="1" />+    <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="relationshipAssertionTo" inverseEntity="Person" maxCount="1" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="kind" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="customLabel" optional="YES" attributeType="String" />+    <attribute name="side" optional="YES" attributeType="String" />+    <attribute name="relatedBy" optional="YES" attributeType="String" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+  </entity>+  <entity name="AddressLabel" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="addressLabelRecords" inverseEntity="FamilySpace" maxCount="1" />+    <attribute name="label" optional="YES" attributeType="String" />+    <attribute name="language" optional="YES" attributeType="String" />+    <attribute name="script" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="isPreferred" optional="YES" attributeType="Boolean" usesScalarValueType="YES" defaultValueString="NO" />+    <relationship name="target" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="addressLabels" inverseEntity="Person" maxCount="1" />+    <relationship name="usedByPerson" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="usedAddressLabels" inverseEntity="Person" maxCount="1" />+    <relationship name="usedByGroup" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="usedAddressLabels" inverseEntity="PersonGroup" maxCount="1" />+  </entity>+  <entity name="PersonGroup" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personGroupRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="usedAddressLabels" optional="YES" deletionRule="Nullify" destinationEntity="AddressLabel" inverseName="usedByGroup" inverseEntity="AddressLabel" toMany="YES" />+    <attribute name="name" optional="YES" attributeType="String" />+    <attribute name="type" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <relationship name="memberships" optional="YES" deletionRule="Nullify" destinationEntity="GroupMembership" inverseName="group" inverseEntity="GroupMembership" toMany="YES" />+    <relationship name="givenGifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="giverGroups" inverseEntity="GiftRecord" toMany="YES" />+  </entity>+  <entity name="GroupMembership" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="groupMembershipRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="group" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="memberships" inverseEntity="PersonGroup" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="groupMemberships" inverseEntity="Person" maxCount="1" />+    <attribute name="role" optional="YES" attributeType="String" />+    <attribute name="startedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="endedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+  </entity>+  <entity name="ContextCategory" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="contextCategoryRecords" inverseEntity="FamilySpace" maxCount="1" />+    <attribute name="name" optional="YES" attributeType="String" />+    <relationship name="contexts" optional="YES" deletionRule="Nullify" destinationEntity="Context" inverseName="category" inverseEntity="Context" toMany="YES" />+    <attribute name="archivedAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+  </entity>+  <entity name="EventPerson" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="eventPersonRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="participants" inverseEntity="Event" maxCount="1" />+    <relationship name="person" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="eventParticipations" inverseEntity="Person" maxCount="1" />+    <attribute name="roles" optional="YES" attributeType="String" />+    <attribute name="invitationState" optional="YES" attributeType="String" />+    <attribute name="attendanceState" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+  </entity>+  <entity name="GiftRecord" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="giftRecordRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="gifts" inverseEntity="Event" maxCount="1" />+    <attribute name="descriptionText" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <relationship name="givers" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="givenGifts" inverseEntity="Person" toMany="YES" />+    <relationship name="giverGroups" optional="YES" deletionRule="Nullify" destinationEntity="PersonGroup" inverseName="givenGifts" inverseEntity="PersonGroup" toMany="YES" />+    <relationship name="recipients" optional="YES" deletionRule="Nullify" destinationEntity="Person" inverseName="receivedGifts" inverseEntity="Person" toMany="YES" />+    <relationship name="attachments" optional="YES" deletionRule="Nullify" destinationEntity="EventAttachment" inverseName="gifts" inverseEntity="EventAttachment" toMany="YES" />+  </entity>+  <entity name="EventAttachment" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="eventAttachmentRecords" inverseEntity="FamilySpace" maxCount="1" />+    <relationship name="event" optional="YES" deletionRule="Nullify" destinationEntity="Event" inverseName="attachments" inverseEntity="Event" maxCount="1" />+    <relationship name="asset" optional="YES" deletionRule="Nullify" destinationEntity="Asset" inverseName="eventAttachment" inverseEntity="Asset" maxCount="1" />+    <relationship name="gifts" optional="YES" deletionRule="Nullify" destinationEntity="GiftRecord" inverseName="attachments" inverseEntity="GiftRecord" toMany="YES" />+    <attribute name="kind" optional="YES" attributeType="String" />+    <attribute name="title" optional="YES" attributeType="String" />+    <attribute name="note" optional="YES" attributeType="String" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+  </entity>+  <entity name="PersonMerge" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="sourceID" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="survivorID" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="undoneAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="undoUnavailableAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="sourceName" optional="YES" attributeType="String" />+    <attribute name="survivorName" optional="YES" attributeType="String" />+    <attribute name="beforeData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+    <attribute name="afterData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personMerges" inverseEntity="FamilySpace" maxCount="1" />+    <attribute name="archivedData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+    <attribute name="recoveryIDs" optional="YES" attributeType="String" />+  </entity>+  <entity name="MergeConnectionReview" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="connectionID" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="reviewedData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="mergeConnectionReviews" inverseEntity="FamilySpace" maxCount="1" />+  </entity>+  <entity name="PersonMergeRecovery" representedClassName="NSManagedObject" syncable="YES">+    <attribute name="id" optional="YES" attributeType="UUID" usesScalarValueType="NO" />+    <attribute name="createdAt" optional="YES" attributeType="Date" usesScalarValueType="NO" />+    <attribute name="mergeIDs" optional="YES" attributeType="String" />+    <attribute name="beforeData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+    <attribute name="afterData" optional="YES" attributeType="Binary" usesScalarValueType="NO" allowsExternalBinaryDataStorage="YES" />+    <relationship name="familySpace" optional="YES" deletionRule="Nullify" destinationEntity="FamilySpace" inverseName="personMergeRecoveries" inverseEntity="FamilySpace" maxCount="1" />+  </entity>+</model>\ No newline at end of file
Halo Family/Halo Family/Persistence/HistoryProcessor.swift Modified +5 / -1
diff --git a/Halo Family/Halo Family/Persistence/HistoryProcessor.swift b/Halo Family/Halo Family/Persistence/HistoryProcessor.swiftindex 55dc025..ead1a10 100644--- a/Halo Family/Halo Family/Persistence/HistoryProcessor.swift	+++ b/Halo Family/Halo Family/Persistence/HistoryProcessor.swift	@@ -17,18 +17,21 @@ final class HistoryProcessor {     private let container: NSPersistentContainer     private let directory: URL     private let consumer: String+    private let access: StoreAccess     private var processing = false     private var needsAnotherPass = false -    init(container: NSPersistentContainer, directory: URL, consumer: String) {+    init(container: NSPersistentContainer, directory: URL, consumer: String, access: StoreAccess = StoreAccess()) {         self.container = container         self.directory = directory         self.consumer = consumer+        self.access = access     }      /// Overlapping notifications coalesce, while writes arriving during a pass request another pass.     @discardableResult     func process() async throws -> Int {+        try access.check()         if processing {             needsAnotherPass = true             return 0@@ -67,6 +70,7 @@ final class HistoryProcessor {             }         }         let batch = try await fetch(store: store, token: token)+        try access.check()         if reset || batch.recovered {             container.viewContext.refreshAllObjects()         }
Halo Family/Halo Family/Persistence/ImageImport.swift Added +84 / -0
diff --git a/Halo Family/Halo Family/Persistence/ImageImport.swift b/Halo Family/Halo Family/Persistence/ImageImport.swiftnew file mode 100644index 0000000..c75d01f--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ImageImport.swift	@@ -0,0 +1,84 @@+import Foundation+import ImageIO+import CoreGraphics+import UniformTypeIdentifiers++nonisolated enum MemoryError: LocalizedError {+    case unsupportedFile+    case fileTooLarge+    case invalidImage+    case invalidDate+    case changed+    case invalidRelationship+    case invalidParticipation++    var errorDescription: String? {+        switch self {+        case .unsupportedFile: "Choose a JPEG, PNG or PDF file. Person photos must be JPEG or PNG."+        case .fileTooLarge: "The file exceeds the allowed size. Photos must be at most 4 MB after processing; attachments at most 20 MB."+        case .invalidImage: "This image or document could not be read."+        case .invalidDate: "Enter a valid partial date, starting with the year."+        case .changed: "These details changed. Reopen them before saving."+        case .invalidRelationship: "Choose different people from this family and valid relationship details."+        case .invalidParticipation: "Choose people, groups and attachments from this event's family."+        }+    }+}++nonisolated struct PreparedAsset: Sendable {+    let data: Data+    let filename: String+    let contentType: String+    let width: Int?+    let height: Int?+}++/// Decode only a bounded thumbnail, then encode a fresh image without source EXIF/GPS metadata.+nonisolated enum ImageImport {+    static let photoLimit = 4_000_000+    static let attachmentLimit = 20_000_000++    static func prepare(_ data: Data, filename: String, photo: Bool) throws -> PreparedAsset {+        guard !data.isEmpty, data.count <= attachmentLimit else { throw MemoryError.fileTooLarge }+        if !photo, data.starts(with: Data("%PDF-".utf8)) {+            guard let provider = CGDataProvider(data: data as CFData), CGPDFDocument(provider) != nil else {+                throw MemoryError.invalidImage+            }+            return PreparedAsset(data: data, filename: safeName(filename, extension: "pdf"),+                                 contentType: UTType.pdf.identifier, width: nil, height: nil)+        }+        guard let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary),+              let type = CGImageSourceGetType(source) as String?,+              type == UTType.jpeg.identifier || type == UTType.png.identifier else { throw MemoryError.unsupportedFile }+        let options: [CFString: Any] = [+            kCGImageSourceCreateThumbnailFromImageAlways: true,+            kCGImageSourceThumbnailMaxPixelSize: photo ? 2048 : 4096,+            kCGImageSourceCreateThumbnailWithTransform: true,+            kCGImageSourceShouldCacheImmediately: true,+        ]+        guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else {+            throw MemoryError.invalidImage+        }+        let outputType = photo ? UTType.jpeg : (type == UTType.png.identifier ? .png : .jpeg)+        let limit = photo ? photoLimit : attachmentLimit+        for quality in [0.88, 0.72, 0.55] {+            let output = NSMutableData()+            guard let destination = CGImageDestinationCreateWithData(output, outputType.identifier as CFString, 1, nil) else {+                throw MemoryError.invalidImage+            }+            // Never copy the source properties dictionary: it can contain GPS and identifying metadata.+            CGImageDestinationAddImage(destination, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)+            guard CGImageDestinationFinalize(destination) else { throw MemoryError.invalidImage }+            if output.length <= limit {+                return PreparedAsset(data: output as Data, filename: safeName(filename, extension: outputType == .png ? "png" : "jpg"),+                                     contentType: outputType.identifier, width: image.width, height: image.height)+            }+        }+        throw MemoryError.fileTooLarge+    }++    private static func safeName(_ name: String, extension suffix: String) -> String {+        let base = URL(fileURLWithPath: name).deletingPathExtension().lastPathComponent+        return "\(base.isEmpty ? "Attachment" : String(base.prefix(120))).\(suffix)"+    }+}
Halo Family/Halo Family/Persistence/KinshipQueries.swift Added +82 / -0
diff --git a/Halo Family/Halo Family/Persistence/KinshipQueries.swift b/Halo Family/Halo Family/Persistence/KinshipQueries.swiftnew file mode 100644index 0000000..d9e6e28--- /dev/null+++ b/Halo Family/Halo Family/Persistence/KinshipQueries.swift	@@ -0,0 +1,82 @@+import CoreData+import Foundation++struct DerivedKinshipRow: Identifiable {+    let id: NSManagedObjectID+    let name: String+    let label: String+}++@MainActor+extension FamilyRepository {+    /// Conservative labels describe the known path; no gender, side or address label is inferred.+    func derivedKinship(for personID: NSManagedObjectID, asOf date: Date = Date()) throws -> [DerivedKinshipRow] {+        let person = try readable(personID, entity: "Person")+        let family = try family(of: person)+        let request = NSFetchRequest<NSManagedObject>(entityName: "PersonRelationship")+        let modern = stack.container.managedObjectModel.entitiesByName["PersonRelationship"]?.attributesByName["archivedAt"] != nil+        let active = NSPredicate(format: "familySpace == %@ AND (startedAt == nil OR startedAt <= %@) " ++                                        "AND (endedAt == nil OR endedAt > %@)",+                                        family, date as NSDate, date as NSDate)+        request.predicate = modern ?+            NSCompoundPredicate(andPredicateWithSubpredicates: [active, NSPredicate(format: "archivedAt == nil")]) : active+        let facts = try stack.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+    }++}
Halo Family/Halo Family/Persistence/LocalContactLinks.swift Added +95 / -0
diff --git a/Halo Family/Halo Family/Persistence/LocalContactLinks.swift b/Halo Family/Halo Family/Persistence/LocalContactLinks.swiftnew file mode 100644index 0000000..7fb1bdf--- /dev/null+++ b/Halo Family/Halo Family/Persistence/LocalContactLinks.swift	@@ -0,0 +1,95 @@+import Foundation++nonisolated struct DeviceContactLink: Codable, Equatable, Identifiable, Sendable {+    let id: UUID+    let familyID: UUID+    let personID: UUID+    let contactIdentifier: String+    let label: String?+    let createdAt: Date+}++nonisolated enum LocalContactError: LocalizedError {+    case invalidStore, invalidIdentifier, tooManyLinks+    var errorDescription: String? {+        switch self {+        case .invalidStore: "The device-local contact links could not be read. Existing links have not been changed."+        case .invalidIdentifier: "Choose a contact before saving its link."+        case .tooManyLinks: "The device-local contact link limit has been reached."+        }+    }+}++/// The host shares one actor per stack. This file is never part of the CloudKit graph or a family export.+actor LocalContactLinks {+    private struct Archive: Codable {+        let formatVersion: Int+        var links: [DeviceContactLink]+    }+    private let file: URL+    init(file: URL) { self.file = file }++    func links(familyID: UUID, personIDs: Set<UUID>) throws -> [DeviceContactLink] {+        try read().filter { $0.familyID == familyID && personIDs.contains($0.personID) }+            .sorted { $0.createdAt < $1.createdAt }+    }++    @discardableResult+    func link(_ identifier: String, label: String? = nil, familyID: UUID, personID: UUID) throws -> DeviceContactLink {+        let identifier = identifier.trimmingCharacters(in: .whitespacesAndNewlines)+        guard !identifier.isEmpty, identifier.utf8.count <= 1_024 else { throw LocalContactError.invalidIdentifier }+        var links = try read()+        if let existing = links.first(where: {+            $0.familyID == familyID && $0.personID == personID && $0.contactIdentifier == identifier+        }) { return existing }+        guard links.count < 20_000,+              links.filter({ $0.familyID == familyID && $0.personID == personID }).count < 32 else {+            throw LocalContactError.tooManyLinks+        }+        let link = DeviceContactLink(id: UUID(), familyID: familyID, personID: personID,+                                     contactIdentifier: identifier, label: label.map { String($0.prefix(500)) }, createdAt: Date())+        links.append(link); try save(links)+        return link+    }++    func unlink(_ link: DeviceContactLink) throws {+        let links = try read().filter { $0 != link }+        try save(links)+    }++    private func read() throws -> [DeviceContactLink] {+        let handle: FileHandle+        do { handle = try FileHandle(forReadingFrom: file) } catch let error as CocoaError+            where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile {+            return []+        }+        defer { try? handle.close() }+        var data = Data()+        while data.count <= 4_000_000 {+            guard let chunk = try handle.read(upToCount: min(65_536, 4_000_001 - data.count)), !chunk.isEmpty else { break }+            data.append(chunk)+        }+        guard data.count <= 4_000_000,+              let archive = try? JSONDecoder().decode(Archive.self, from: data), archive.formatVersion == 1,+              archive.links.count <= 20_000, Set(archive.links.map(\.id)).count == archive.links.count,+              archive.links.allSatisfy({ !$0.contactIdentifier.isEmpty && $0.contactIdentifier.utf8.count <= 1_024 }) else {+            throw LocalContactError.invalidStore+        }+        return archive.links+    }++    private func save(_ links: [DeviceContactLink]) throws {+        let data = try JSONEncoder().encode(Archive(formatVersion: 1, links: links))+        guard data.count <= 4_000_000 else { throw LocalContactError.tooManyLinks }+        var directory = file.deletingLastPathComponent()+        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+        var values = URLResourceValues(); values.isExcludedFromBackup = true+        try directory.setResourceValues(values)+        try data.write(to: file, options: .atomic)+        NotificationCenter.default.post(name: .haloContactLinksDidChange, object: nil)+    }+}++extension Notification.Name {+    nonisolated static let haloContactLinksDidChange = Notification.Name("HaloContactLinksDidChange")+}
Halo Family/Halo Family/Persistence/MergeAccountReview.swift Added +126 / -0
diff --git a/Halo Family/Halo Family/Persistence/MergeAccountReview.swift b/Halo Family/Halo Family/Persistence/MergeAccountReview.swiftnew file mode 100644index 0000000..6920526--- /dev/null+++ b/Halo Family/Halo Family/Persistence/MergeAccountReview.swift	@@ -0,0 +1,126 @@+import CoreData+import Foundation++struct LateMergeAccounts: Identifiable {+    let id: NSManagedObjectID+    let stableID: UUID+    let name: String+    let targetID: NSManagedObjectID?+    let records: [MergeRecord]+    let unreviewedIDs: Set<UUID>+}++@MainActor+extension FamilyRepository {+    func lateMergeAccounts(in familyID: NSManagedObjectID) throws -> [LateMergeAccounts] {+        let family = try readable(familyID, entity: "FamilySpace")+        return try lateMergeAccounts(family: family, in: stack.container.viewContext)+    }++    private func lateMergeAccounts(family: NSManagedObject, in context: NSManagedObjectContext) throws -> [LateMergeAccounts] {+        let audits = NSFetchRequest<NSManagedObject>(entityName: "PersonMerge")+        audits.predicate = NSPredicate(format: "familySpace == %@ AND undoneAt == nil", family)+        let history = try context.fetch(audits)+        guard !history.isEmpty else { return [] }+        var baselines: [UUID: [[MergeRecord]]] = [:]+        for audit in history {+            let rows = try MergeSnapshot.decode(audit.value(forKey: "archivedData") as? Data)+            for (id, accounts) in mergeAccountIndex(rows) { baselines[id, default: []].append(accounts) }+        }+        guard !baselines.isEmpty else { return [] }+        let reviewed = NSFetchRequest<NSManagedObject>(entityName: "MergeConnectionReview")+        reviewed.predicate = NSPredicate(format: "familySpace == %@", family)+        for review in try context.fetch(reviewed) {+            guard let id = review.value(forKey: "connectionID") as? UUID else { throw MergeError.invalidSnapshot }+            baselines[id, default: []].append(try MergeSnapshot.decode(review.value(forKey: "reviewedData") as? Data))+        }+        let current = try MergeSnapshot.records(family: family, in: context)+        let indexed = mergeAccountIndex(current)+        let objects = try MergeSnapshot.objects(family: family, in: context)+        return try baselines.keys.sorted(by: { $0.uuidString < $1.uuidString }).compactMap { id in+            guard let connection = objects[id], connection.value(forKey: "archivedAt") != nil else { return nil }+            let rows = indexed[id] ?? []+            guard !(baselines[id] ?? []).contains(rows) else { return nil }+            var seen: [UUID: [MergeRecord]] = [:]+            for baseline in baselines[id] ?? [] {+                for row in baseline { seen[row.id, default: []].append(row) }+            }+            let unreviewed = Set(rows.filter { !(seen[$0.id] ?? []).contains($0) }.map(\.id))+            return LateMergeAccounts(id: connection.objectID, stableID: id,+                name: connection.value(forKeyPath: "person.displayName") as? String ?? "Earlier relationship",+                targetID: try activeMergeConnection(connection)?.objectID, records: rows, unreviewedIDs: unreviewed)+        }+    }++    /// Copies late accounts as alternatives, without choosing a new current truth. Original IDs stay in history.+    func reviewLateMergeAccounts(_ preview: LateMergeAccounts) throws {+        _ = try write { context in+            let connection = try context.existingObject(with: preview.id)+            guard connection.entity.name == "Connection", connection.value(forKey: "archivedAt") != nil,+                  try stable(connection) == preview.stableID else { throw MergeError.changed }+            let family = try family(of: connection)+            _ = try record(family.objectID, entity: "FamilySpace", in: context)+            guard let fresh = try lateMergeAccounts(family: family, in: context).first(where: { $0.id == preview.id }),+                  fresh.records == preview.records, fresh.unreviewedIDs == preview.unreviewedIDs else { throw MergeError.changed }+            let target = try activeMergeConnection(connection)+            guard target?.objectID == preview.targetID else { throw MergeError.changed }+            if let target {+                _ = try record(target.objectID, entity: "Connection", in: context)+                // Seed a causal account for any pre-proposal first meeting on the current relationship.+                _ = try preparedHeads(connection: target, heads: originHeads(connection: target, in: context), in: context)+                for head in try mergeOrigins(connection) where head.recordID != nil && preview.unreviewedIDs.contains(head.id) {+                    _ = try makeProposal(input: OriginInput(contextID: head.contextID, eventID: head.eventID, narrative: head.narrative),+                        cleared: head.cleared, connection: target, predecessors: [], in: context)+                }+                try copyLatePeriodsAndMemberships(connection, to: target, unreviewed: preview.unreviewedIDs, in: context)+            }+            let review = insert("MergeConnectionReview", in: context, store: try owningStore(of: family))+            review.setValue(family, forKey: "familySpace"); review.setValue(preview.stableID, forKey: "connectionID")+            review.setValue(Date(), forKey: "createdAt")+            review.setValue(try MergeSnapshot.encode(preview.records), forKey: "reviewedData")+            try requireMergeWritePermissions(context)+            return review+        }+    }++    private func copyLatePeriodsAndMemberships(_ source: NSManagedObject, to target: NSManagedObject,+                                               unreviewed: Set<UUID>, in context: NSManagedObjectContext) throws {+        let family = try family(of: source)+        let entities = ["ConnectionClosenessPeriod", "ConnectionStatusPeriod", "ConnectionContext"]+        for entity in entities {+            let request = NSFetchRequest<NSManagedObject>(entityName: entity)+            request.predicate = NSPredicate(format: "connection == %@ AND endedAt == nil", source)+            for original in try context.fetch(request) {+                guard try unreviewed.contains(stable(original)) else { continue }+                let copy = insert(entity, in: context, store: try owningStore(of: family))+                for key in original.entity.attributesByName.keys where key != "id" {+                    copy.setValue(original.value(forKey: key), forKey: key)+                }+                copy.setValue(family, forKey: "familySpace"); copy.setValue(target, forKey: "connection")+                if entity == "ConnectionContext" { copy.setValue(original.value(forKey: "context"), forKey: "context") }+            }+        }+    }++    private func activeMergeConnection(_ original: NSManagedObject) throws -> NSManagedObject? {+        let family = try family(of: original)+        var visited: Set<NSManagedObjectID> = [original.objectID]+        var current = original+        while let next = current.value(forKey: "mergedInto") as? NSManagedObject {+            guard visited.insert(next.objectID).inserted else { throw MergeError.invalidSnapshot }+            try requireSameFamily(next, family: family)+            current = next+        }+        return current.value(forKey: "archivedAt") == nil ? current : nil+    }++    private func mergeAccountIndex(_ records: [MergeRecord]) -> [UUID: [MergeRecord]] {+        var result: [UUID: [MergeRecord]] = [:]+        for row in records {+            if row.entity == "Connection" { result[row.id, default: []].append(row) } else {+                for id in row.links["connection"] ?? [] { result[id, default: []].append(row) }+            }+        }+        return result+    }+}
Halo Family/Halo Family/Persistence/MergeConflictRecovery.swift Added +184 / -0
diff --git a/Halo Family/Halo Family/Persistence/MergeConflictRecovery.swift b/Halo Family/Halo Family/Persistence/MergeConflictRecovery.swiftnew file mode 100644index 0000000..2ab6150--- /dev/null+++ b/Halo Family/Halo Family/Persistence/MergeConflictRecovery.swift	@@ -0,0 +1,184 @@+import CoreData+import Foundation++struct PersonMergeConflict: Identifiable {+    let id: String+    let familyID: NSManagedObjectID+    let people: [GraphRow]+    let mergeIDs: [UUID]+    let records: [MergeRecord]+}++private struct MergeRecoveryState {+    let acknowledged: Set<UUID>+    let byPerson: [UUID: Set<UUID>]+}++@MainActor+extension FamilyRepository {+    func mergeConflicts(in familyID: NSManagedObjectID) throws -> [PersonMergeConflict] {+        let family = try readable(familyID, entity: "FamilySpace")+        return try mergeConflicts(family: family, in: stack.container.viewContext)+    }++    /// Recovery exposes the separate identities and retains the currently saved references and competing audits.+    /// It deliberately does not replay an old full snapshot over intervening edits.+    func recoverCompetingMerges(_ preview: PersonMergeConflict) throws {+        _ = try write { context in+            let family = try record(preview.familyID, entity: "FamilySpace", in: context)+            let conflicts = try mergeConflicts(family: family, in: context)+            guard let current = conflicts.first(where: { $0.id == preview.id }), current.records == preview.records,+                  current.mergeIDs == preview.mergeIDs else { throw MergeError.changed }+            let objects = try MergeSnapshot.objects(family: family, in: context)+            for person in current.people {+                let object = try context.existingObject(with: person.id)+                guard object.entity.name == "Person", try self.family(of: object) == family else { throw GraphError.differentFamily }+                object.setValue(nil, forKey: "mergedInto"); object.setValue(nil, forKey: "archivedAt")+                object.setValue(true, forKey: "needsReview"); object.setValue(Date(), forKey: "modifiedAt")+            }+            let recovery = insert("PersonMergeRecovery", in: context, store: try owningStore(of: family))+            recovery.setValue(family, forKey: "familySpace"); recovery.setValue(Date(), forKey: "createdAt")+            recovery.setValue(String(data: try JSONEncoder().encode(preview.mergeIDs), encoding: .utf8), forKey: "mergeIDs")+            let ids = Set(try current.people.map { try stable(context.existingObject(with: $0.id)) })+            recovery.setValue(try MergeSnapshot.encode(preview.records.filter { ids.contains($0.id) }), forKey: "beforeData")+            recovery.setValue(try MergeSnapshot.encode(try ids.map {+                guard let object = objects[$0] else { throw MergeError.invalidSnapshot }+                return try MergeSnapshot.record(object)+            }.sorted { $0.id.uuidString < $1.id.uuidString }), forKey: "afterData")+            try requireMergeWritePermissions(context)+            return recovery+        }+    }++    func mergeConflicts(family: NSManagedObject, in context: NSManagedObjectContext) throws -> [PersonMergeConflict] {+        guard context.persistentStoreCoordinator?.managedObjectModel.entitiesByName["PersonMerge"] != nil else { return [] }+        let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMerge")+        request.predicate = NSPredicate(format: "familySpace == %@ AND undoneAt == nil", family)+        let audits = try context.fetch(request)+        if audits.isEmpty {+            let aliases = NSFetchRequest<NSManagedObject>(entityName: "Person")+            aliases.predicate = NSPredicate(format: "familySpace == %@ AND mergedInto != nil", family)+            aliases.fetchLimit = 1+            guard try !context.fetch(aliases).isEmpty else { return [] }+        }+        let recovery = try mergeRecoveryState(family: family, in: context)+        let peopleRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")+        peopleRequest.predicate = NSPredicate(format: "familySpace == %@", family)+        let people = try context.fetch(peopleRequest)+        var objects: [UUID: NSManagedObject] = [:]+        for person in people {+            guard objects.updateValue(person, forKey: try stable(person)) == nil else { throw MergeError.invalidSnapshot }+        }+        var edges: [UUID: Set<UUID>] = [:]+        var accounts: [(id: UUID, source: UUID, target: UUID)] = []+        var stale: Set<UUID> = []+        for audit in audits {+            let id = try stable(audit)+            guard !recovery.acknowledged.contains(id) else { continue }+            guard let source = audit.value(forKey: "sourceID") as? UUID,+                  let target = audit.value(forKey: "survivorID") as? UUID,+                  objects[source] != nil, objects[target] != nil else { throw MergeError.invalidSnapshot }+            edges[source, default: []].insert(target)+            accounts.append((id, source, target))+            let known = try decodedMergeIDs(audit.value(forKey: "recoveryIDs") as? String)+            let required = (recovery.byPerson[source] ?? []).union(recovery.byPerson[target] ?? [])+            if !required.isSubset(of: Set(known)) { stale.formUnion([source, target]) }+        }+        var problematic = Set(edges.filter { $0.value.count > 1 }.keys).union(stale)+        problematic.formUnion(cycleMembers(edges))+        let supported = mergeAuditComponents(edges)+        var currentEdges: [UUID: Set<UUID>] = [:]+        for (id, person) in objects {+            if let target = person.value(forKey: "mergedInto") as? NSManagedObject {+                try requireSameFamily(target, family: family)+                let targetID = try stable(target)+                currentEdges[id, default: []].insert(targetID)+                if supported[id] == nil || supported[id] != supported[targetID] { problematic.formUnion([id, targetID]) }+            }+        }+        problematic.formUnion(cycleMembers(currentEdges))+        for (id, targets) in currentEdges { edges[id, default: []].formUnion(targets) }+        guard !problematic.isEmpty else { return [] }+        let components = mergeConflictComponents(problematic, edges: edges)+        let records = try MergeSnapshot.records(family: family, in: context)+        return try components.map { ids in+            let sorted = ids.sorted { $0.uuidString < $1.uuidString }+            let rows = try sorted.map { id -> GraphRow in+                guard let person = objects[id] else { throw MergeError.invalidSnapshot }+                return GraphRow(id: person.objectID, name: person.value(forKey: "displayName") as? String ?? "Person")+            }+            return PersonMergeConflict(id: sorted.map(\.uuidString).joined(separator: "|"), familyID: family.objectID,+                people: rows, mergeIDs: accounts.filter { ids.contains($0.source) || ids.contains($0.target) }.map(\.id)+                    .sorted { $0.uuidString < $1.uuidString }, records: records)+        }.sorted { $0.id < $1.id }+    }++    private func decodedMergeIDs(_ text: String?) throws -> [UUID] {+        guard let text else { return [] }+        guard let ids = try? JSONDecoder().decode([UUID].self, from: Data(text.utf8)) else { throw MergeError.invalidSnapshot }+        return ids+    }++    private func mergeRecoveryState(family: NSManagedObject, in context: NSManagedObjectContext) throws -> MergeRecoveryState {+        let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMergeRecovery")+        request.predicate = NSPredicate(format: "familySpace == %@", family)+        var acknowledged: Set<UUID> = [], byPerson: [UUID: Set<UUID>] = [:]+        for recovery in try context.fetch(request) {+            let id = try stable(recovery)+            acknowledged.formUnion(try decodedMergeIDs(recovery.value(forKey: "mergeIDs") as? String))+            for row in try MergeSnapshot.decode(recovery.value(forKey: "afterData") as? Data) where row.entity == "Person" {+                byPerson[row.id, default: []].insert(id)+            }+        }+        return MergeRecoveryState(acknowledged: acknowledged, byPerson: byPerson)+    }++    private func mergeAuditComponents(_ edges: [UUID: Set<UUID>]) -> [UUID: UUID] {+        let ids = Set(edges.keys).union(edges.values.flatMap { $0 })+        let components = mergeConflictComponents(ids, edges: edges)+        var result: [UUID: UUID] = [:]+        for component in components {+            guard let first = component.first else { continue }+            for id in component { result[id] = first }+        }+        return result+    }++    private func cycleMembers(_ edges: [UUID: Set<UUID>]) -> Set<UUID> {+        var incoming: [UUID: Int] = [:]+        for (source, targets) in edges {+            incoming[source, default: 0] += 0+            for target in targets { incoming[target, default: 0] += 1 }+        }+        var pending = incoming.filter { $0.value == 0 }.map(\.key)+        var index = 0+        while index < pending.count {+            let source = pending[index]; index += 1+            for target in edges[source] ?? [] {+                incoming[target, default: 0] -= 1+                if incoming[target] == 0 { pending.append(target) }+            }+        }+        return Set(incoming.filter { $0.value > 0 }.keys)+    }++    private func mergeConflictComponents(_ problematic: Set<UUID>, edges: [UUID: Set<UUID>]) -> [Set<UUID>] {+        var neighbours: [UUID: Set<UUID>] = [:]+        for (source, targets) in edges {+            for target in targets {+                neighbours[source, default: []].insert(target); neighbours[target, default: []].insert(source)+            }+        }+        var remaining = problematic, components: [Set<UUID>] = []+        while let first = remaining.first {+            var component: Set<UUID> = [], pending = [first]+            while let id = pending.popLast() {+                guard component.insert(id).inserted else { continue }+                pending.append(contentsOf: neighbours[id] ?? [])+            }+            remaining.subtract(component); components.append(component)+        }+        return components+    }++}
Halo Family/Halo Family/Persistence/MergeSnapshot.swift Added +186 / -0
diff --git a/Halo Family/Halo Family/Persistence/MergeSnapshot.swift b/Halo Family/Halo Family/Persistence/MergeSnapshot.swiftnew file mode 100644index 0000000..f0027e5--- /dev/null+++ b/Halo Family/Halo Family/Persistence/MergeSnapshot.swift	@@ -0,0 +1,186 @@+import CoreData+import Foundation++nonisolated enum MergeError: LocalizedError {+    case changed+    case invalidSnapshot+    case choiceRequired+    case unavailable++    var errorDescription: String? {+        switch self {+        case .changed: "These records changed. Review a fresh merge preview before continuing."+        case .invalidSnapshot: "The merge history could not be read. No records were changed."+        case .choiceRequired: "Choose the connection, first meeting and relationship values to retain for each overlap."+        case .unavailable: "Undo is unavailable because an affected record changed or this merge was already undone."+        }+    }+}++/// Metadata only: photos and attachments retain their existing Asset UUIDs and bytes.+nonisolated enum SnapshotValue: Codable, Equatable, Sendable {+    case text(String), integer(Int64), decimal(Double), flag(Bool), date(Date), uuid(UUID)+}++nonisolated struct MergeRecord: Codable, Equatable, Sendable {+    let id: UUID+    let entity: String+    let attributes: [String: SnapshotValue]+    let links: [String: [UUID]]+}++@MainActor+enum MergeSnapshot {+    static func records(family: NSManagedObject, in context: NSManagedObjectContext) throws -> [MergeRecord] {+        guard let model = context.persistentStoreCoordinator?.managedObjectModel else { throw MergeError.invalidSnapshot }+        var records: [MergeRecord] = []+        var identities: Set<UUID> = []+        let historyEntities = ["FamilySpace", "PersonMerge", "MergeConnectionReview", "PersonMergeRecovery"]+        for entity in model.entities where !historyEntities.contains(entity.name ?? "") {+            guard let name = entity.name, entity.relationshipsByName["familySpace"] != nil else { continue }+            let request = NSFetchRequest<NSManagedObject>(entityName: name)+            request.predicate = NSPredicate(format: "familySpace == %@", family)+            for object in try context.fetch(request) {+                let row = try record(object)+                guard identities.insert(row.id).inserted else { throw MergeError.invalidSnapshot }+                records.append(row)+            }+        }+        guard let familyID = family.value(forKey: "id") as? UUID else { throw MergeError.invalidSnapshot }+        identities.insert(familyID)+        guard records.allSatisfy({ $0.links.values.allSatisfy { Set($0).isSubset(of: identities) } }) else {+            throw GraphError.differentFamily+        }+        return records.sorted { $0.id.uuidString < $1.id.uuidString }+    }++    static func record(_ object: NSManagedObject) throws -> MergeRecord {+        guard let id = object.value(forKey: "id") as? UUID, let entity = object.entity.name else { throw MergeError.invalidSnapshot }+        var values: [String: SnapshotValue] = [:]+        for (key, attribute) in object.entity.attributesByName {+            // Skip before reading: external payloads must not be materialized by merge preview.+            if attribute.attributeType == .binaryDataAttributeType { continue }+            guard let value = object.value(forKey: key) else { continue }+            switch value {+            case let uuid as UUID: values[key] = .uuid(uuid)+            case let date as Date: values[key] = .date(date)+            case let text as String: values[key] = .text(text)+            case let number as NSNumber:+                if attribute.attributeType == .booleanAttributeType { values[key] = .flag(number.boolValue) } else if+                    [.doubleAttributeType, .floatAttributeType, .decimalAttributeType].contains(attribute.attributeType) {+                    values[key] = .decimal(number.doubleValue)+                } else { values[key] = .integer(number.int64Value) }+            default: throw MergeError.invalidSnapshot+            }+        }+        var links: [String: [UUID]] = [:]+        for (key, relationship) in object.entity.relationshipsByName {+            let objects: [NSManagedObject]+            if relationship.isToMany { objects = Array(object.value(forKey: key) as? Set<NSManagedObject> ?? []) } else {+                objects = (object.value(forKey: key) as? NSManagedObject).map { [$0] } ?? []+            }+            links[key] = try objects.map {+                guard let id = $0.value(forKey: "id") as? UUID else { throw MergeError.invalidSnapshot }+                return id+            }.sorted { $0.uuidString < $1.uuidString }+        }+        return MergeRecord(id: id, entity: entity, attributes: values, links: links)+    }++    static func objects(family: NSManagedObject, in context: NSManagedObjectContext) throws -> [UUID: NSManagedObject] {+        var result: [UUID: NSManagedObject] = [:]+        guard let familyID = family.value(forKey: "id") as? UUID else { throw MergeError.invalidSnapshot }+        result[familyID] = family+        for entity in context.persistentStoreCoordinator?.managedObjectModel.entities ?? [] {+            guard let name = entity.name, name != "FamilySpace", entity.relationshipsByName["familySpace"] != nil else { continue }+            let request = NSFetchRequest<NSManagedObject>(entityName: name)+            request.predicate = NSPredicate(format: "familySpace == %@", family)+            for object in try context.fetch(request) {+                guard let id = object.value(forKey: "id") as? UUID, result.updateValue(object, forKey: id) == nil else {+                    throw MergeError.invalidSnapshot+                }+            }+        }+        return result+    }++    static func restore(_ records: [MergeRecord], objects: [UUID: NSManagedObject]) throws {+        for row in records { try validate(row, objects: objects) }+        for row in records {+            guard let object = objects[row.id], object.entity.name == row.entity else { throw MergeError.invalidSnapshot }+            for (key, attribute) in object.entity.attributesByName where attribute.attributeType != .binaryDataAttributeType {+                object.setValue(row.attributes[key].map(value), forKey: key)+            }+        }+        for row in records {+            guard let object = objects[row.id] else { throw MergeError.invalidSnapshot }+            for (key, ids) in row.links {+                guard let relationship = object.entity.relationshipsByName[key] else { throw MergeError.invalidSnapshot }+                let targets = try ids.map {+                    guard let target = objects[$0], !target.isDeleted else { throw MergeError.invalidSnapshot }+                    return target+                }+                if relationship.isToMany { object.setValue(NSSet(array: targets), forKey: key) } else {+                    object.setValue(targets.first, forKey: key)+                }+            }+        }+    }++    private static func validate(_ row: MergeRecord, objects: [UUID: NSManagedObject]) throws {+        guard let object = objects[row.id], object.entity.name == row.entity, row.attributes["id"] == .uuid(row.id),+              Set(row.links.keys) == Set(object.entity.relationshipsByName.keys) else { throw MergeError.invalidSnapshot }+        for (key, value) in row.attributes {+            guard let attribute = object.entity.attributesByName[key], accepts(value, type: attribute.attributeType) else {+                throw MergeError.invalidSnapshot+            }+        }+        for (key, ids) in row.links {+            guard let relationship = object.entity.relationshipsByName[key], relationship.isToMany || ids.count <= 1,+                  Set(ids).count == ids.count else { throw MergeError.invalidSnapshot }+            for id in ids {+                guard let target = objects[id], !target.isDeleted,+                      target.entity.name == relationship.destinationEntity?.name else { throw MergeError.invalidSnapshot }+            }+        }+    }++    private static func accepts(_ value: SnapshotValue, type: NSAttributeType) -> Bool {+        switch (value, type) {+        case (.text, .stringAttributeType), (.flag, .booleanAttributeType), (.uuid, .UUIDAttributeType): true+        case (.date(let date), .dateAttributeType): date.timeIntervalSinceReferenceDate.isFinite+        case (.integer(let number), .integer16AttributeType): Int16(exactly: number) != nil+        case (.integer(let number), .integer32AttributeType): Int32(exactly: number) != nil+        case (.integer, .integer64AttributeType): true+        case (.decimal(let value), .doubleAttributeType), (.decimal(let value), .floatAttributeType),+             (.decimal(let value), .decimalAttributeType): value.isFinite+        default: false+        }+    }++    private static func value(_ value: SnapshotValue) -> Any {+        switch value {+        case .text(let value): value+        case .integer(let value): NSNumber(value: value)+        case .decimal(let value): NSNumber(value: value)+        case .flag(let value): NSNumber(value: value)+        case .date(let value): value+        case .uuid(let value): value+        }+    }++    nonisolated static func encode(_ records: [MergeRecord]) throws -> Data {+        let encoder = JSONEncoder()+        encoder.outputFormatting = [.sortedKeys]+        let data = try encoder.encode(records)+        guard data.count <= 16_000_000 else { throw MergeError.invalidSnapshot }+        return data+    }++    nonisolated static func decode(_ data: Data?) throws -> [MergeRecord] {+        guard let data, data.count <= 16_000_000,+              let records = try? JSONDecoder().decode([MergeRecord].self, from: data),+              Set(records.map(\.id)).count == records.count else { throw MergeError.invalidSnapshot }+        return records+    }+}
Halo Family/Halo Family/Persistence/OriginRepository.swift Added +267 / -0
diff --git a/Halo Family/Halo Family/Persistence/OriginRepository.swift b/Halo Family/Halo Family/Persistence/OriginRepository.swiftnew file mode 100644index 0000000..9eefe8d--- /dev/null+++ b/Halo Family/Halo Family/Persistence/OriginRepository.swift	@@ -0,0 +1,267 @@+import CoreData+import Foundation++struct OriginProposalRow: Identifiable, Equatable {+    let id: NSManagedObjectID+    let stableID: UUID+    let contextID: NSManagedObjectID?+    let eventID: NSManagedObjectID?+    let sourceName: String?+    let narrative: String+    let isCleared: Bool+}++struct OriginOverview {+    let origin: OriginRow?+    let conflicts: [OriginProposalRow]+    let headIDs: Set<UUID>+}++/// Proposals are immutable. Each new proposal acknowledges only the heads it actually saw.+/// Concurrent offline edits therefore remain separate heads until a parent resolves them.+@MainActor+extension FamilyRepository {+    func origin(for connectionID: NSManagedObjectID) throws -> OriginRow? {+        let overview = try originOverview(for: connectionID)+        guard overview.conflicts.isEmpty else { throw GraphError.originConflict }+        return overview.origin+    }++    func originOverview(for connectionID: NSManagedObjectID) throws -> OriginOverview {+        let context = stack.container.viewContext+        let connection = try readable(connectionID, entity: "Connection")+        return try originOverview(connection: connection, heads: originHeads(connection: connection, in: context), in: context)+    }++    func originHistory(for connectionID: NSManagedObjectID) throws -> [OriginProposalRow] {+        let request = NSFetchRequest<NSManagedObject>(entityName: "OriginProposal")+        request.predicate = NSPredicate(format: "connection == %@", connectionID)+        request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]+        return try stack.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.fetch(request)+        let grouped = Dictionary(grouping: proposals) {+            ($0.value(forKey: "connection") as? NSManagedObject)?.objectID ?? $0.objectID+        }+        var conflicts: Set<NSManagedObjectID> = []+        for (connectionID, records) in grouped {+            guard connectionID.entity.name == "Connection" else { throw GraphError.invalidReference }+            if try proposalHeads(records).count > 1 { conflicts.insert(connectionID) }+        }+        return conflicts+    }++    func saveOrigin(connectionID: NSManagedObjectID, input: OriginInput, expectedOrigin: OriginRow?,+                    expectedHeads: Set<UUID> = []) throws {+        _ = try write { context in+            let connection = try record(connectionID, entity: "Connection", in: context)+            let heads = try originHeads(connection: connection, in: context)+            let overview = try originOverview(connection: connection, heads: heads, in: context)+            guard overview.conflicts.isEmpty else { throw GraphError.originConflict }+            guard sameOriginValue(overview.origin, expectedOrigin),+                  overview.headIDs == (expectedOrigin?.revisionIDs ?? expectedHeads) else { throw GraphError.originChanged }+            let predecessors = try preparedHeads(connection: connection, heads: heads, in: context)+            _ = try makeProposal(input: input, cleared: false, connection: connection, predecessors: predecessors, in: context)+            return try updateProjection(input: input, cleared: false, connection: connection, in: context)+        }+    }++    func clearOrigin(connectionID: NSManagedObjectID, expectedOrigin: OriginRow) throws {+        _ = try write { context in+            let connection = try record(connectionID, entity: "Connection", in: context)+            let heads = try originHeads(connection: connection, in: context)+            let overview = try originOverview(connection: connection, heads: heads, in: context)+            guard overview.conflicts.isEmpty else { throw GraphError.originConflict }+            guard sameOriginValue(overview.origin, expectedOrigin) else { throw GraphError.originChanged }+            let predecessors = try preparedHeads(connection: connection, heads: heads, in: context)+            _ = try makeProposal(input: OriginInput(), cleared: true, connection: connection, predecessors: predecessors, in: context)+            return try updateProjection(input: OriginInput(), cleared: true, connection: connection, in: context)+        }+    }++    func resolveOrigin(connectionID: NSManagedObjectID, choosing proposalID: NSManagedObjectID, expectedHeads: Set<UUID>) throws {+        _ = try write { context in+            let connection = try record(connectionID, entity: "Connection", in: context)+            let heads = try originHeads(connection: connection, in: context)+            let ids = Set(try heads.map { try proposalRow($0).stableID })+            guard ids == expectedHeads, heads.count > 1,+                  let chosen = heads.first(where: { $0.objectID == proposalID }) else { throw GraphError.originChanged }+            let row = try proposalRow(chosen)+            let input = row.isCleared ? OriginInput() :+                OriginInput(contextID: row.contextID, eventID: row.eventID, narrative: row.narrative)+            _ = try makeProposal(input: input, cleared: row.isCleared, connection: connection, predecessors: heads, in: context)+            return try updateProjection(input: input, cleared: row.isCleared, connection: connection, in: context)+        }+    }++    private func originOverview(connection: NSManagedObject, heads: [NSManagedObject],+                                in context: NSManagedObjectContext) throws -> OriginOverview {+        let rows = try heads.map { try proposalRow($0) }+        let ids = Set(rows.map(\.stableID))+        if rows.count > 1 { return OriginOverview(origin: nil, conflicts: rows, headIDs: ids) }+        let canonical = try projectionOrigins(connection: connection, in: context)+        if let row = rows.first {+            let origin = row.isCleared ? nil : OriginRow(id: canonical.first?.objectID ?? row.id,+                                                         contextID: row.contextID, eventID: row.eventID,+                                                         sourceName: row.sourceName, narrative: row.narrative, revisionIDs: ids)+            return OriginOverview(origin: origin, conflicts: [], headIDs: ids)+        }+        guard canonical.count <= 1 else { throw GraphError.originChanged }+        let legacy = canonical.first.map { originRow($0) }+        return OriginOverview(origin: legacy, conflicts: [], headIDs: [])+    }++    func originHeads(connection: NSManagedObject, in context: NSManagedObjectContext) throws -> [NSManagedObject] {+        let request = NSFetchRequest<NSManagedObject>(entityName: "OriginProposal")+        request.predicate = NSPredicate(format: "connection == %@", connection)+        return try proposalHeads(context.fetch(request))+    }++    private func proposalHeads(_ all: [NSManagedObject]) throws -> [NSManagedObject] {+        let allIDs = Set(all.map(\.objectID))+        var stableIDs: Set<UUID> = []+        var remainingParents: [NSManagedObjectID: Int] = [:]+        var children: [NSManagedObjectID: [NSManagedObjectID]] = [:]+        for proposal in all {+            guard stableIDs.insert(try validateProposal(proposal)).inserted else { throw GraphError.invalidReference }+            let parents = proposal.value(forKey: "predecessors") as? Set<NSManagedObject> ?? []+            guard parents.allSatisfy({ allIDs.contains($0.objectID) && $0.objectID != proposal.objectID }) else {+                throw GraphError.invalidReference+            }+            remainingParents[proposal.objectID] = parents.count+            for parent in parents { children[parent.objectID, default: []].append(proposal.objectID) }+        }+        // Validate every component, including cycles concealed alongside a valid head.+        var queue = remainingParents.filter { $0.value == 0 }.map(\.key)+        var index = 0+        while index < queue.count {+            for child in children[queue[index], default: []] {+                remainingParents[child, default: 0] -= 1+                if remainingParents[child] == 0 { queue.append(child) }+            }+            index += 1+        }+        guard queue.count == all.count else { throw GraphError.invalidReference }+        return all.filter { children[$0.objectID, default: []].isEmpty }.sorted {+            (($0.value(forKey: "id") as? UUID)?.uuidString ?? "") < (($1.value(forKey: "id") as? UUID)?.uuidString ?? "")+        }+    }++    func preparedHeads(connection: NSManagedObject, heads: [NSManagedObject],+                       in context: NSManagedObjectContext) throws -> [NSManagedObject] {+        guard heads.isEmpty, let legacy = try projectionOrigins(connection: connection, in: context).first else { return heads }+        let row = originRow(legacy)+        let input = OriginInput(contextID: row.contextID, eventID: row.eventID, narrative: row.narrative)+        return [try makeProposal(input: input, cleared: false, connection: connection, predecessors: [], in: context)]+    }++    func makeProposal(input: OriginInput, cleared: Bool, connection: NSManagedObject,+                      predecessors: [NSManagedObject], in context: NSManagedObjectContext) throws -> NSManagedObject {+        let family = try family(of: connection)+        let narrative = input.narrative.trimmingCharacters(in: .whitespacesAndNewlines)+        guard cleared || (!(input.contextID != nil && input.eventID != nil) &&+                          (input.contextID != nil || input.eventID != nil || !narrative.isEmpty)) else { throw GraphError.invalidOrigin }+        let source = try input.contextID.map { try record($0, entity: "Context", in: context) }+        let event = try input.eventID.map { try record($0, entity: "Event", in: context) }+        if let source { try requireSameFamily(source, family: family) }+        if let event { try requireSameFamily(event, family: family) }+        let proposal = insert("OriginProposal", in: context, store: try owningStore(of: family))+        proposal.setValue(family, forKey: "familySpace")+        proposal.setValue(connection, forKey: "connection")+        proposal.setValue(source, forKey: "context")+        proposal.setValue(event, forKey: "event")+        proposal.setValue(narrative.isEmpty ? nil : narrative, forKey: "narrative")+        proposal.setValue(cleared, forKey: "isCleared")+        proposal.setValue(Date(), forKey: "createdAt")+        proposal.setValue(Set(predecessors), forKey: "predecessors")+        return proposal+    }++    private func updateProjection(input: OriginInput, cleared: Bool, connection: NSManagedObject,+                                  in context: NSManagedObjectContext) throws -> NSManagedObject {+        let existing = try projectionOrigins(connection: connection, in: context)+        if cleared {+            existing.forEach(context.delete)+            return connection+        }+        let family = try family(of: connection)+        let store = try owningStore(of: family)+        let origin = existing.first ?? insert("ConnectionOrigin", in: context, store: store)+        // Concurrent first writes can import two materialized rows. Proposals preserve both+        // accounts; resolution compacts only this replaceable projection.+        existing.dropFirst().forEach(context.delete)+        origin.setValue(family, forKey: "familySpace")+        origin.setValue(connection, forKey: "connection")+        origin.setValue(try input.contextID.map { try record($0, entity: "Context", in: context) }, forKey: "context")+        origin.setValue(try input.eventID.map { try record($0, entity: "Event", in: context) }, forKey: "event")+        origin.setValue(input.narrative.trimmingCharacters(in: .whitespacesAndNewlines), forKey: "originDescription")+        return origin+    }++    private func projectionOrigins(connection: NSManagedObject, in context: NSManagedObjectContext) throws -> [NSManagedObject] {+        let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionOrigin")+        request.predicate = NSPredicate(format: "connection == %@", connection)+        let records = try context.fetch(request)+        return records.sorted {+            (($0.value(forKey: "id") as? UUID)?.uuidString ?? "") < (($1.value(forKey: "id") as? UUID)?.uuidString ?? "")+        }+    }++    private func originRow(_ object: NSManagedObject) -> OriginRow {+        let source = object.value(forKey: "context") as? NSManagedObject+        let event = object.value(forKey: "event") as? NSManagedObject+        return OriginRow(id: object.objectID, contextID: source?.objectID, eventID: event?.objectID,+                         sourceName: sourceName(context: source, event: event),+                         narrative: object.value(forKey: "originDescription") as? String ?? "")+    }++    private func proposalRow(_ object: NSManagedObject) throws -> OriginProposalRow {+        let id = try validateProposal(object)+        let source = object.value(forKey: "context") as? NSManagedObject+        let event = object.value(forKey: "event") as? NSManagedObject+        return OriginProposalRow(id: object.objectID, stableID: id, contextID: source?.objectID, eventID: event?.objectID,+                                 sourceName: sourceName(context: source, event: event),+                                 narrative: object.value(forKey: "narrative") as? String ?? "",+                                 isCleared: object.value(forKey: "isCleared") as? Bool ?? false)+    }++    private func validateProposal(_ object: NSManagedObject) throws -> UUID {+        guard let id = object.value(forKey: "id") as? UUID,+              let connection = object.value(forKey: "connection") as? NSManagedObject else { throw GraphError.invalidReference }+        let family = try family(of: connection)+        try requireSameFamily(object, family: family)+        let source = object.value(forKey: "context") as? NSManagedObject+        let event = object.value(forKey: "event") as? NSManagedObject+        let narrative = object.value(forKey: "narrative") as? String ?? ""+        let cleared = object.value(forKey: "isCleared") as? Bool ?? false+        guard source == nil || event == nil,+              cleared ? (source == nil && event == nil && narrative.isEmpty) :+                (source != nil || event != nil || !narrative.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) else {+            throw GraphError.invalidOrigin+        }+        if let source { try requireSameFamily(source, family: family) }+        if let event { try requireSameFamily(event, family: family) }+        return id+    }++    private func sourceName(context: NSManagedObject?, event: NSManagedObject?) -> String? {+        if let context { return "Context: \(contextPath(context))" }+        if let event {+            let row = EventRow(id: event.objectID, title: event.value(forKey: "title") as? String ?? "Untitled",+                               date: event.value(forKey: "date") as? Date, notes: "")+            return "Event: \(row.label)"+        }+        return nil+    }++    private func sameOriginValue(_ current: OriginRow?, _ expected: OriginRow?) -> Bool {+        current?.id == expected?.id && current?.contextID == expected?.contextID && current?.eventID == expected?.eventID &&+            current?.narrative == expected?.narrative && current?.revisionIDs == expected?.revisionIDs+    }+}
Halo Family/Halo Family/Persistence/PeopleSearch.swift Added +88 / -0
diff --git a/Halo Family/Halo Family/Persistence/PeopleSearch.swift b/Halo Family/Halo Family/Persistence/PeopleSearch.swiftnew file mode 100644index 0000000..2a578b3--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PeopleSearch.swift	@@ -0,0 +1,88 @@+import CoreData+import Foundation++struct PersonContextRoleRow: Identifiable {+    let association: ContextPersonRow+    let contextPath: String+    let isArchived: Bool+    var id: NSManagedObjectID { association.id }+}++@MainActor+extension FamilyRepository {+    /// Each key path has at most one to-many traversal, supported by the SQLite store.+    /// Entered names and titles stay literal; this does not infer gender or family terminology.+    func peopleSearch(_ text: String, familyID: NSManagedObjectID) throws -> NSPredicate {+        let model = stack.container.managedObjectModel+        let scalar = ["displayName", "givenName", "familyName"]+        let paths = ["addressLabels.label", "contextLinks.role", "contextLinks.context.name",+                     "groupMemberships.group.name", "groupMemberships.role",+                     "relationshipAssertionFrom.customLabel", "relationshipAssertionFrom.target.displayName",+                     "relationshipAssertionTo.source.displayName", "personRelationshipFrom.kind",+                     "personRelationshipFrom.target.displayName", "personRelationshipTo.source.displayName"]+        guard let person = model.entitiesByName["Person"] else { throw GraphError.modelUnavailable }+        var predicates = scalar.filter { person.attributesByName[$0] != nil }.map {+            NSPredicate(format: "%K CONTAINS[cd] %@", $0, text)+        }+        for path in paths where validSearchPath(path, from: person) {+            predicates.append(NSPredicate(format: "ANY %K CONTAINS[cd] %@", path, text))+        }+        if person.relationshipsByName["personRelationshipFrom"] != nil {+            let kinds = StructuralKind.allCases.filter {+                $0.label.range(of: text, options: [.caseInsensitive, .diacriticInsensitive]) != nil+            }+            predicates.append(NSPredicate(format: "ANY personRelationshipFrom.kind IN %@", kinds.map(\.rawValue)))+            let symmetric = kinds.filter { $0 == .siblingOf || $0 == .partnerOf }.map(\.rawValue)+            predicates.append(NSPredicate(format: "ANY personRelationshipTo.kind IN %@", symmetric))+        }+        if model.entitiesByName["ConnectionContext"] != nil {+            // Context paths may be arbitrarily deep. Match the derived path once, then fetch+            // membership rows directly rather than joining two to-many relationships from Person.+            let contexts = try contexts(in: familyID).filter {+                $0.path.range(of: text, options: [.caseInsensitive, .diacriticInsensitive]) != nil+            }+            if !contexts.isEmpty {+                let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionContext")+                request.predicate = NSPredicate(format: "familySpace == %@ AND context IN %@", familyID, contexts.map(\.id))+                request.relationshipKeyPathsForPrefetching = ["connection.person"]+                let ids = Set(try stack.fetch(request).compactMap {+                    ($0.value(forKeyPath: "connection.person") as? NSManagedObject)?.objectID+                })+                predicates.append(NSPredicate(format: "SELF IN %@", Array(ids)))+                let roles = NSFetchRequest<NSManagedObject>(entityName: "ContextPerson")+                roles.predicate = NSPredicate(format: "familySpace == %@ AND context IN %@", familyID, contexts.map(\.id))+                roles.relationshipKeyPathsForPrefetching = ["person"]+                let people = Set(try stack.fetch(roles).compactMap {+                    ($0.value(forKey: "person") as? NSManagedObject)?.objectID+                })+                predicates.append(NSPredicate(format: "SELF IN %@", Array(people)))+            }+        }+        return NSCompoundPredicate(orPredicateWithSubpredicates: predicates)+    }++    func personContextRoles(_ personID: NSManagedObjectID) throws -> [PersonContextRoleRow] {+        _ = try readable(personID, entity: "Person")+        let request = NSFetchRequest<NSManagedObject>(entityName: "ContextPerson")+        request.predicate = NSPredicate(format: "person == %@", personID)+        request.relationshipKeyPathsForPrefetching = ["context", "person"]+        return try stack.fetch(request).compactMap { row in+            guard let context = row.value(forKey: "context") as? NSManagedObject else { return nil }+            let association = ContextPersonRow(id: row.objectID, contextID: context.objectID, personID: personID,+                name: row.value(forKeyPath: "person.displayName") as? String ?? "Unnamed", role: row.value(forKey: "role") as? String ?? "",+                startedAt: row.value(forKey: "startedAt") as? Date, endedAt: row.value(forKey: "endedAt") as? Date)+            return PersonContextRoleRow(association: association, contextPath: contextPath(context),+                                        isArchived: context.value(forKey: "archivedAt") != nil)+        }.sorted { $0.contextPath.localizedStandardCompare($1.contextPath) == .orderedAscending }+    }++    private func validSearchPath(_ path: String, from root: NSEntityDescription) -> Bool {+        let keys = path.split(separator: ".").map(String.init)+        var entity = root+        for key in keys.dropLast() {+            guard let destination = entity.relationshipsByName[key]?.destinationEntity else { return false }+            entity = destination+        }+        return keys.last.map { entity.attributesByName[$0]?.attributeType == .stringAttributeType } ?? false+    }+}
Halo Family/Halo Family/Persistence/PersistenceStack.swift Modified +197 / -13
diff --git a/Halo Family/Halo Family/Persistence/PersistenceStack.swift b/Halo Family/Halo Family/Persistence/PersistenceStack.swiftindex 5fc89c3..510f0c2 100644--- a/Halo Family/Halo Family/Persistence/PersistenceStack.swift	+++ b/Halo Family/Halo Family/Persistence/PersistenceStack.swift	@@ -1,3 +1,4 @@+import CloudKit import CoreData import Foundation import Observation@@ -7,20 +8,40 @@ import OSLog @Observable final class PersistenceStack {     private static var hostTask: Task<PersistenceStack, Error>?+    private static var hostGeneration: UUID?+    private static weak var hostStack: PersistenceStack?+    private static var deviceTask: Task<PersistenceStack, Error>?+    private static weak var deviceStack: PersistenceStack?     let container: NSPersistentContainer     let privateStore: NSPersistentStore     let sharedStore: NSPersistentStore     let role: PersistenceRole+    let nativeContactsEnabled: Bool+    let accountScope: AccountScope?+    @ObservationIgnored let access: StoreAccess+    @ObservationIgnored private let accountContainer: CKContainer?+    private(set) var accessIssue: String?+    private(set) var storageNotice: String?+    @ObservationIgnored var importingBackup = false+    @ObservationIgnored var verifyingShares = false+    @ObservationIgnored var verifySharesAgain = false+    @ObservationIgnored var shareVerificationGeneration = UUID()     private(set) var issue: String?     private(set) var syncIssue: String?     @ObservationIgnored private var history: HistoryProcessor?     @ObservationIgnored private var observation: PersistenceObservation?+    @ObservationIgnored private var contactLinks: LocalContactLinks?+    @ObservationIgnored private var accountObservation: PersistenceObservation?     @ObservationIgnored private let logger = Logger(subsystem: "me.nore.ig.halo-family", category: "Persistence")      /// Test/local coordinators never mirror CloudKit. Production uses the async factory below.     init(directory: URL, model: NSManagedObjectModel? = nil, role: PersistenceRole = .host) throws {         try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)         self.role = role+        accountScope = nil+        access = StoreAccess()+        accountContainer = nil+        nativeContactsEnabled = false         container = NSPersistentContainer(name: "HaloModel", managedObjectModel: try model ?? Self.loadModel())         let coordinator = container.persistentStoreCoordinator         let descriptions = StoreConfiguration(directory: directory, role: role, mirrorsCloud: false).descriptions()@@ -38,34 +59,122 @@ final class PersistenceStack {         configureViewContext()     } -    private init(container: NSPersistentContainer, configuration: StoreConfiguration) throws {+    private init(container: NSPersistentContainer, configuration: StoreConfiguration, access: StoreAccess) throws {         let coordinator = container.persistentStoreCoordinator         guard let owned = coordinator.persistentStore(for: configuration.directory.appendingPathComponent("Private.sqlite")),               let shared = coordinator.persistentStore(for: configuration.directory.appendingPathComponent("Shared.sqlite")) else {             throw PersistenceError.storesUnavailable         }         self.container = container+        self.access = access         privateStore = owned         sharedStore = shared         role = configuration.role+        accountScope = configuration.accountScope+        accountContainer = configuration.accountScope?.mirrorsCloud == true ?+            CKContainer(identifier: StoreConfiguration.cloudContainer) : nil+        nativeContactsEnabled = configuration.role == .host         configureViewContext()     }      static func production(role: PersistenceRole = .host) async throws -> PersistenceStack {-        guard role == .host else { return try await open(configuration: .production(role: role)) }+        guard role == .host else { return try await openProduction(role: role) }         // Multiple windows share one host coordinator and one mirroring owner.-        if let hostTask { return try await hostTask.value }-        let task = Task { @MainActor in try await open(configuration: .production(role: .host)) }+        if let hostTask {+            let stack = try await hostTask.value+            try stack.access.check()+            return stack+        }+        let generation = UUID()+        let task = Task { @MainActor in+            let stack = try await openProduction(role: .host)+            if stack.accountScope?.mirrorsCloud == true { hostStack = stack }+            return stack+        }+        hostGeneration = generation         hostTask = task         do {-            return try await task.value+            let stack = try await task.value+            if stack.accountScope == .local, hostGeneration == generation { hostTask = nil; hostGeneration = nil }+            return stack         } catch {-            hostTask = nil+            if hostGeneration == generation { hostTask = nil; hostGeneration = nil }             throw error         }     } -    static func open(configuration: StoreConfiguration) async throws -> PersistenceStack {+    private static func openProduction(role: PersistenceRole) async throws -> PersistenceStack {+        let opening = AccountOpeningGuard()+        let scope = try await AccountScope.current(container: opening.container)+        try opening.access.check()+        if scope == .local { return try await deviceLibrary(role: role) }+        let configuration = try StoreConfiguration.production(role: role, scope: scope)+        if role != .host { _ = try ExtensionAccess.read(in: configuration.directory, namespace: scope.namespace) }+        let stack = try await open(configuration: configuration, access: opening.access)+        stack.observeAccount(directory: configuration.directory)+        do {+            guard try await AccountScope.current(container: opening.container) == scope else { throw AccessError.accountChanged }+            try stack.access.check()+            if role == .host {+                let marker = configuration.directory.appendingPathComponent("AccessLocked")+                if FileManager.default.fileExists(atPath: marker.path) { try FileManager.default.removeItem(at: marker) }+                try stack.refreshAccess()+                stack.startHistory(directory: configuration.directory.appendingPathComponent("History", isDirectory: true))+                await stack.refreshHistory()+                let root = configuration.directory.deletingLastPathComponent().deletingLastPathComponent()+                if FileManager.default.fileExists(atPath: root.appendingPathComponent("Private.sqlite").path) {+                    stack.storageNotice = "Earlier unscoped stores are retained separately. They were not attached to this account."+                } else if scope == .local {+                    stack.storageNotice = "This library is stored only on this device. Signing in opens a separate iCloud library."+                }+            } else {+                stack.access.watchExtensionAccess(directory: configuration.directory, namespace: scope.namespace)+                try stack.access.check()+            }+            try stack.access.check()+            return stack+        } catch {+            stack.lockSession()+            throw error+        }+    }++    static func deviceLibrary(role: PersistenceRole = .host) async throws -> PersistenceStack {+        if role != .host { return try await openDeviceLibrary(role: role) }+        if let deviceTask {+            let stack = try await deviceTask.value+            try stack.access.check()+            return stack+        }+        let task = Task { @MainActor in+            let stack = try await openDeviceLibrary(role: .host)+            deviceStack = stack+            return stack+        }+        deviceTask = task+        do { return try await task.value } catch { deviceTask = nil; throw error }+    }++    private static func openDeviceLibrary(role: PersistenceRole) async throws -> PersistenceStack {+        let configuration = try StoreConfiguration.production(role: role, scope: .local)+        if role != .host { _ = try ExtensionAccess.read(in: configuration.directory, namespace: "local") }+        let stack = try await open(configuration: configuration)+        if role == .host {+            let marker = configuration.directory.appendingPathComponent("AccessLocked")+            if FileManager.default.fileExists(atPath: marker.path) { try FileManager.default.removeItem(at: marker) }+            try stack.refreshAccess()+            stack.startHistory(directory: configuration.directory.appendingPathComponent("History", isDirectory: true))+            await stack.refreshHistory()+            stack.storageNotice = "This library stays on this device. Use backup/import to make an explicit copy into your iCloud library."+        } else {+            stack.access.watchExtensionAccess(directory: configuration.directory, namespace: "local")+            try stack.access.check()+        }+        return stack+    }++    static func open(configuration: StoreConfiguration, access: StoreAccess = StoreAccess()) async throws -> PersistenceStack {+        try access.check()         if configuration.role == .host {             try FileManager.default.createDirectory(at: configuration.directory, withIntermediateDirectories: true)         } else {@@ -95,8 +204,12 @@ final class PersistenceStack {                 }             }         }-        let stack = try PersistenceStack(container: container, configuration: configuration)-        if configuration.role == .host {+        do { try access.check() } catch {+            for store in container.persistentStoreCoordinator.persistentStores { try? container.persistentStoreCoordinator.remove(store) }+            throw error+        }+        let stack = try PersistenceStack(container: container, configuration: configuration, access: access)+        if configuration.role == .host && configuration.accountScope == nil {             stack.startHistory(directory: configuration.directory.appendingPathComponent("History", isDirectory: true))             await stack.refreshHistory()         }@@ -105,7 +218,7 @@ final class PersistenceStack {      func startHistory(directory: URL) {         guard history == nil else { return }-        history = HistoryProcessor(container: container, directory: directory, consumer: role.rawValue)+        history = HistoryProcessor(container: container, directory: directory, consumer: role.rawValue, access: access)         let token = NotificationCenter.default.addObserver(             forName: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator, queue: nil         ) { [weak self] _ in@@ -122,10 +235,13 @@ final class PersistenceStack {             Task { @MainActor [weak self] in                 if succeeded {                     self?.syncIssue = nil+                    do { try self?.refreshAccess() } catch { self?.lockSession() }                 } else {                     self?.syncIssue = "iCloud sync is delayed: \(message ?? "Please try again later.")"-                    self?.logger.error("CloudKit operation failed: \(message ?? "Unknown error", privacy: .public)")+                    self?.logger.error("CloudKit operation failed: \(message ?? "Unknown error", privacy: .private)")                 }+                if event.storeIdentifier == self?.sharedStore.identifier,+                   CloudAccessFailure.removesAccess(event.error) { await self?.revalidateSharedAccess() }             }         }         observation = PersistenceObservation(tokens: [token, cloudToken])@@ -134,12 +250,80 @@ final class PersistenceStack {     func refreshHistory() async {         guard let history else { return }         do {+            try access.check()             _ = try await history.process()+            try access.check()+            try refreshAccess()+            await revalidateSharedAccess(ifRequired: true)             issue = nil         } catch {             issue = "Couldn’t refresh saved changes: \(error.localizedDescription)"-            logger.error("History processing failed: \(error.localizedDescription, privacy: .public)")+            logger.error("History processing failed: \(error.localizedDescription, privacy: .private)")+        }+    }++    func localContactLinks() throws -> LocalContactLinks {+        try access.check()+        guard role == .host, let directory = privateStore.url?.deletingLastPathComponent() else { throw GraphError.readOnly }+        if let contactLinks { return contactLinks }+        let store = LocalContactLinks(file: directory.appendingPathComponent("DeviceLinks/contacts.json"))+        contactLinks = store+        return store+    }++    func verifyAccount() async {+        guard let accountScope, accountScope.mirrorsCloud else { return }+        do {+            guard let accountContainer,+                  try await AccountScope.current(container: accountContainer) == accountScope else { throw AccessError.accountChanged }+            try access.check()+            try refreshAccess()+            await revalidateSharedAccess(ifRequired: true)+        } catch { lockSession() }+    }++    private func observeAccount(directory: URL) {+        let access = access+        let marker = directory.appendingPathComponent("AccessLocked")+        let token = NotificationCenter.default.addObserver(forName: .CKAccountChanged, object: nil, queue: nil) { [weak self] _ in+            if access.invalidate() { try? Data().write(to: marker, options: .atomic) }+            Task { @MainActor [weak self] in self?.lockSession() }         }+        accountObservation = PersistenceObservation(tokens: [token])+    }++    func lockSession() {+        guard accessIssue == nil else { return }+        access.invalidate()+        accessIssue = AccessError.accountChanged.localizedDescription+        if accountScope != nil, let directory = privateStore.url?.deletingLastPathComponent() {+            try? Data().write(to: directory.appendingPathComponent("AccessLocked"), options: .atomic)+        }+        observation = nil+        accountObservation = nil+        container.viewContext.reset()+        NotificationCenter.default.post(name: .haloPersistenceDidRefresh, object: container)+        // Detach; never destroy/reset SQLite files or another account's directory.+        for store in container.persistentStoreCoordinator.persistentStores {+            do { try container.persistentStoreCoordinator.remove(store) } catch {+                issue = "The previous data session could not be closed. Restart Halo Family before reopening."+                return+            }+        }+        if Self.hostStack === self {+            Self.hostStack = nil+            Self.hostTask = nil+            Self.hostGeneration = nil+        }+        if Self.deviceStack === self { Self.deviceStack = nil; Self.deviceTask = nil }+    }++    func shareVerificationFailed(_ error: Error) {+        syncIssue = "Shared-family access needs verification: \(error.localizedDescription)"+    }++    func shareVerificationSucceeded() {+        if syncIssue?.hasPrefix("Shared-family access needs verification:") == true { syncIssue = nil }     }      private func configureViewContext() {@@ -148,7 +332,7 @@ final class PersistenceStack {         container.viewContext.mergePolicy = NSMergePolicy(merge: .mergeByPropertyObjectTrumpMergePolicyType)     } -    static func loadModel(version: String = "HaloModelV2") throws -> NSManagedObjectModel {+    static func loadModel(version: String = "HaloModelV6") throws -> NSManagedObjectModel {         #if SWIFT_PACKAGE         let bundle = Bundle.module         #else
Halo Family/Halo Family/Persistence/PersonMergeHistory.swift Added +104 / -0
diff --git a/Halo Family/Halo Family/Persistence/PersonMergeHistory.swift b/Halo Family/Halo Family/Persistence/PersonMergeHistory.swiftnew file mode 100644index 0000000..86be035--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PersonMergeHistory.swift	@@ -0,0 +1,104 @@+import CoreData+import Foundation++@MainActor+extension FamilyRepository {+    func mergeRecoveryHistory(in familyID: NSManagedObjectID) throws -> [PersonMergeRecoveryRow] {+        _ = try readable(familyID, entity: "FamilySpace")+        let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMergeRecovery")+        request.predicate = NSPredicate(format: "familySpace == %@", familyID)+        request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]+        return try stack.fetch(request).map {+            try PersonMergeRecoveryRow(id: $0.objectID, createdAt: $0.value(forKey: "createdAt") as? Date,+                people: MergeSnapshot.decode($0.value(forKey: "beforeData") as? Data))+        }+    }++    func mergeHistory(in familyID: NSManagedObjectID) throws -> [PersonMergeHistoryRow] {+        let context = stack.container.viewContext+        let family = try readable(familyID, entity: "FamilySpace")+        let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMerge")+        request.predicate = NSPredicate(format: "familySpace == %@", family)+        request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]+        let audits = try context.fetch(request)+        guard !audits.isEmpty else { return [] }+        let needsComparison = audits.contains { $0.value(forKey: "undoneAt") == nil && $0.value(forKey: "undoUnavailableAt") == nil }+        let current = needsComparison ?+            Dictionary(uniqueKeysWithValues: try MergeSnapshot.records(family: family, in: context).map { ($0.id, $0) }) : [:]+        let people = NSFetchRequest<NSManagedObject>(entityName: "Person")+        people.predicate = NSPredicate(format: "familySpace == %@", family)+        var objects: [UUID: NSManagedObject] = [:]+        for person in try context.fetch(people) {+            guard objects.updateValue(person, forKey: try stable(person)) == nil else { throw MergeError.invalidSnapshot }+        }+        return audits.map { audit in+            let source = audit.value(forKey: "sourceID") as? UUID+            let survivor = audit.value(forKey: "survivorID") as? UUID+            let undone = audit.value(forKey: "undoneAt") != nil+            let after = undone || audit.value(forKey: "undoUnavailableAt") != nil ? nil : try? checkedMergeHistory(audit).after+            let unchanged = after?.allSatisfy { current[$0.id] == $0 } ?? false+            return PersonMergeHistoryRow(id: audit.objectID, sourceName: audit.value(forKey: "sourceName") as? String ?? "Person",+                survivorName: audit.value(forKey: "survivorName") as? String ?? "Person",+                sourceID: source.flatMap { objects[$0]?.objectID }, survivorID: survivor.flatMap { objects[$0]?.objectID },+                createdAt: audit.value(forKey: "createdAt") as? Date, undone: undone,+                undoAvailable: !undone && audit.value(forKey: "undoUnavailableAt") == nil && unchanged)+        }+    }++    func undoPersonMerge(_ auditID: NSManagedObjectID) throws {+        _ = try write { context in+            let audit = try record(auditID, entity: "PersonMerge", in: context)+            guard audit.value(forKey: "undoneAt") == nil, audit.value(forKey: "undoUnavailableAt") == nil else {+                throw MergeError.unavailable+            }+            let family = try family(of: audit)+            let history = try checkedMergeHistory(audit)+            let current = Dictionary(uniqueKeysWithValues: try MergeSnapshot.records(family: family, in: context).map { ($0.id, $0) })+            guard history.after.allSatisfy({ current[$0.id] == $0 }) else { throw MergeError.unavailable }+            let objects = try MergeSnapshot.objects(family: family, in: context)+            let beforeIDs = Set(history.before.map(\.id))+            for row in history.after where !beforeIDs.contains(row.id) {+                guard ["OriginProposal", "ConnectionClosenessPeriod", "ConnectionStatusPeriod"].contains(row.entity),+                      let object = objects[row.id], object.entity.name == row.entity else { throw MergeError.invalidSnapshot }+                // Only untouched merge-generated projections are removed. Original accounts/UUIDs remain;+                // their generated alternatives and selection stay documented in this retained audit.+                context.delete(object)+            }+            try MergeSnapshot.restore(history.before, objects: objects)+            let restored = Dictionary(uniqueKeysWithValues: try MergeSnapshot.records(family: family, in: context).map { ($0.id, $0) })+            guard history.before.allSatisfy({ restored[$0.id] == $0 }) else { throw MergeError.invalidSnapshot }+            audit.setValue(Date(), forKey: "undoneAt")+            try requireMergeWritePermissions(context)+            return audit+        }+    }++    func mergePreviousDetails(_ auditID: NSManagedObjectID) throws -> [MergeRecord] {+        try checkedMergeHistory(readable(auditID, entity: "PersonMerge")).before+    }++    func archivedMergeConnections(_ auditID: NSManagedObjectID) throws -> [GraphRow] {+        let audit = try readable(auditID, entity: "PersonMerge")+        let family = try family(of: audit)+        let objects = try MergeSnapshot.objects(family: family, in: stack.container.viewContext)+        return try checkedMergeHistory(audit).after.compactMap { row in+            guard row.entity == "Connection", row.attributes["archivedAt"] != nil,+                  let object = objects[row.id] else { return nil }+            let child = object.value(forKeyPath: "child.person.displayName") as? String ?? "Child"+            return GraphRow(id: object.objectID, name: "Earlier relationship for \(child)")+        }+    }++    private func checkedMergeHistory(_ audit: NSManagedObject) throws -> (before: [MergeRecord], after: [MergeRecord]) {+        let before = try MergeSnapshot.decode(audit.value(forKey: "beforeData") as? Data)+        let after = try MergeSnapshot.decode(audit.value(forKey: "afterData") as? Data)+        guard let sourceID = audit.value(forKey: "sourceID") as? UUID,+              let survivorID = audit.value(forKey: "survivorID") as? UUID, sourceID != survivorID,+              before.contains(where: { $0.id == sourceID && $0.entity == "Person" && ($0.links["mergedInto"] ?? []).isEmpty }),+              before.contains(where: { $0.id == survivorID && $0.entity == "Person" }),+              after.contains(where: { $0.id == sourceID && $0.entity == "Person" && $0.links["mergedInto"] == [survivorID] }),+              after.contains(where: { $0.id == survivorID && $0.entity == "Person" }),+              Set(before.map(\.id)).isSubset(of: Set(after.map(\.id))) else { throw MergeError.invalidSnapshot }+        return (before, after)+    }+}
Halo Family/Halo Family/Persistence/PersonMergePreview.swift Added +157 / -0
diff --git a/Halo Family/Halo Family/Persistence/PersonMergePreview.swift b/Halo Family/Halo Family/Persistence/PersonMergePreview.swiftnew file mode 100644index 0000000..a3dfea1--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PersonMergePreview.swift	@@ -0,0 +1,157 @@+import CoreData+import Foundation++@MainActor+extension FamilyRepository {+    func mergedPersonTarget(_ personID: NSManagedObjectID) throws -> NSManagedObjectID? {+        var current = try readable(personID, entity: "Person")+        guard current.entity.relationshipsByName["mergedInto"] != nil else { return nil }+        let family = try family(of: current)+        var visited: Set<NSManagedObjectID> = [personID]+        var result: NSManagedObjectID?+        while let next = current.value(forKey: "mergedInto") as? NSManagedObject {+            guard visited.insert(next.objectID).inserted else { throw MergeError.invalidSnapshot }+            try requireSameFamily(next, family: family)+            current = next; result = next.objectID+        }+        return result+    }++    func likelyDuplicates(in familyID: NSManagedObjectID) throws -> [DuplicatePersonPair] {+        // Suggestions only. Same-name people are valid; deceased people are excluded from routine suggestions.+        let people = try people(in: familyID, includeDeceased: false)+        func words(_ name: String) -> [String] {+            name.folding(options: [.caseInsensitive, .diacriticInsensitive], locale: Locale(identifier: "en_US_POSIX"))+                .split(whereSeparator: { $0.isWhitespace }).map(String.init)+        }+        let indexed = Dictionary(grouping: people) { words($0.name).first ?? "" }+        var result: [DuplicatePersonPair] = []+        for key in indexed.keys.sorted() where !key.isEmpty {+            let group = indexed[key] ?? []+            for (index, person) in group.enumerated() {+                for other in group.dropFirst(index + 1).prefix(20) {+                    let first = words(person.name), second = words(other.name)+                    if first.count == 1 || second.count == 1 || first == second ||+                        first.dropFirst().first?.first == second.dropFirst().first?.first {+                        let ids = try [person, other].map { try stable(readable($0.id, entity: "Person")).uuidString }.sorted()+                        result.append(DuplicatePersonPair(source: person, survivor: other, id: ids.joined(separator: "|")))+                        if result.count >= 100 { return result }+                    }+                }+            }+        }+        return result+    }++    func mergePreview(sourceID: NSManagedObjectID, survivorID: NSManagedObjectID) throws -> PersonMergePreview {+        let context = stack.container.viewContext+        let source = try readable(sourceID, entity: "Person"), survivor = try readable(survivorID, entity: "Person")+        let family = try family(of: source)+        try requireSameFamily(survivor, family: family)+        guard try mergeConflicts(in: family.objectID).isEmpty else { throw MergeError.changed }+        guard source != survivor, source.value(forKey: "mergedInto") == nil,+              survivor.value(forKey: "mergedInto") == nil else { throw MergeError.changed }+        let records = try MergeSnapshot.records(family: family, in: context)+        let sourceProfile = source.value(forKey: "childProfile") as? NSManagedObject+        let survivorProfile = survivor.value(forKey: "childProfile") as? NSManagedObject+        let combines = sourceProfile != nil && survivorProfile != nil+        var childMap: [NSManagedObjectID: NSManagedObjectID] = [:]+        if let sourceProfile, let survivorProfile { childMap[sourceProfile.objectID] = survivorProfile.objectID }+        let request = NSFetchRequest<NSManagedObject>(entityName: "Connection")+        request.predicate = NSPredicate(format: "familySpace == %@ AND mergedInto == nil AND archivedAt == nil", family)+        let all = try context.fetch(request)+        let relevant = all.filter {+            let person = $0.value(forKey: "person") as? NSManagedObject+            let child = $0.value(forKey: "child") as? NSManagedObject+            return person == source || person == survivor || (combines && (child == sourceProfile || child == survivorProfile))+        }+        var groups: [String: [NSManagedObject]] = [:]+        var selfConnections: [NSManagedObjectID] = []+        for connection in relevant {+            guard let child = connection.value(forKey: "child") as? NSManagedObject,+                  let person = connection.value(forKey: "person") as? NSManagedObject else { throw GraphError.invalidReference }+            let childID = childMap[child.objectID] ?? child.objectID+            let personID = person == source ? survivorID : person.objectID+            let childPerson = child.value(forKey: "person") as? NSManagedObject+            let childPersonID = childPerson == source ? survivorID : childPerson?.objectID+            if personID == childPersonID { selfConnections.append(connection.objectID); continue }+            let key = childID.uriRepresentation().absoluteString + "|" + personID.uriRepresentation().absoluteString+            groups[key, default: []].append(connection)+        }+        let overlaps = try groups.keys.sorted().compactMap { key -> MergeConnectionOverlap? in+            let connections = try (groups[key] ?? []).sorted { try stable($0).uuidString < stable($1).uuidString }+            guard connections.count > 1 else { return nil }+            let kept = connections.first {+                ($0.value(forKey: "person") as? NSManagedObject) != source &&+                    (!combines || ($0.value(forKey: "child") as? NSManagedObject) != sourceProfile)+            } ?? connections[0]+            let child = kept.value(forKey: "child") as? NSManagedObject+            let person = kept.value(forKey: "person") as? NSManagedObject+            return try MergeConnectionOverlap(id: stable(kept), keptID: kept.objectID,+                connections: connections.map(\.objectID), childName: child?.value(forKeyPath: "person.displayName") as? String ?? "Child",+                personName: person?.value(forKey: "displayName") as? String ?? "Person",+                origins: try connections.flatMap { try mergeOrigins($0) },+                closeness: try connections.flatMap { try mergePeriods($0, closeness: true) },+                statuses: try connections.flatMap { try mergePeriods($0, closeness: false) })+        }+        let sourceUUID = try stable(source), survivorUUID = try stable(survivor)+        let references = records.filter { row in+            row.id != sourceUUID && row.id != survivorUUID && row.links.values.contains { $0.contains(sourceUUID) }+        }+        let selfLinks = records.filter {+            ["PersonRelationship", "RelationshipAssertion"].contains($0.entity) &&+                Set(($0.links["source"] ?? []) + ($0.links["target"] ?? [])) == [sourceUUID, survivorUUID]+        }.count+        let participations = records.filter { $0.entity == "EventPerson" }+        let events = Set(participations.filter { $0.links["person"] == [sourceUUID] }.flatMap { $0.links["event"] ?? [] })+        let duplicateAccounts = participations.filter {+            $0.links["person"] == [survivorUUID] && !events.isDisjoint(with: $0.links["event"] ?? [])+        }.count+        return PersonMergePreview(familyID: family.objectID, source: try mergePerson(source), survivor: try mergePerson(survivor),+            records: records, overlaps: overlaps,+            referenceCounts: Dictionary(grouping: references, by: \.entity).mapValues(\.count), combinesChildProfiles: combines,+            selfRelationships: selfLinks, selfConnections: selfConnections, duplicateEventAccounts: duplicateAccounts)+    }++    func stable(_ object: NSManagedObject) throws -> UUID {+        guard let id = object.value(forKey: "id") as? UUID else { throw MergeError.invalidSnapshot }+        return id+    }++    private func mergePerson(_ object: NSManagedObject) throws -> MergePersonValues {+        let structured = object.entity.attributesByName["givenName"] != nil+        return try MergePersonValues(id: object.objectID, stableID: stable(object),+                          name: object.value(forKey: "displayName") as? String ?? "Unnamed",+                          notes: object.value(forKey: "notes") as? String ?? "", sensitive: try sensitiveDetails(object.objectID),+                          photoID: (object.value(forKey: "primaryPhoto") as? NSManagedObject)?.objectID,+                          givenName: structured ? object.value(forKey: "givenName") as? String ?? "" : "",+                          familyName: structured ? object.value(forKey: "familyName") as? String ?? "" : "")+    }++    func mergeOrigins(_ connection: NSManagedObject) throws -> [MergeOriginChoice] {+        let label = connection.value(forKeyPath: "person.displayName") as? String ?? "Person"+        let overview = try originOverview(for: connection.objectID)+        let history = try originHistory(for: connection.objectID).filter { overview.headIDs.contains($0.stableID) }+        if !history.isEmpty {+            return history.map {+                MergeOriginChoice(id: $0.stableID, recordID: $0.id, connectionID: connection.objectID,+                    label: label + ": " + ($0.isCleared ? "No first meeting" : ($0.sourceName ?? $0.narrative)),+                    contextID: $0.contextID, eventID: $0.eventID, narrative: $0.narrative, cleared: $0.isCleared, proposal: true)+            }+        }+        let origin = overview.origin+        let id = try origin.map { try readable($0.id, entity: "ConnectionOrigin") }.map(stable) ?? stable(connection)+        return [MergeOriginChoice(id: id, recordID: origin?.id, connectionID: connection.objectID,+            label: label + ": " + (origin?.sourceName ?? origin?.narrative ?? "No first meeting recorded"),+            contextID: origin?.contextID, eventID: origin?.eventID, narrative: origin?.narrative ?? "",+            cleared: origin == nil, proposal: false)]+    }++    private func mergePeriods(_ connection: NSManagedObject, closeness: Bool) throws -> [MergePeriodChoice] {+        let name = connection.value(forKeyPath: "person.displayName") as? String ?? "Person"+        return try currentStatePeriods(connection.objectID, closeness: closeness).map {+            let value = $0.value.map { ClosenessChoice(rawValue: $0)?.label ?? "Closeness \($0)" } ?? $0.state?.label ?? "Unknown"+            return MergePeriodChoice(id: $0.id, label: name + ": " + value, value: $0.value, state: $0.state, note: $0.note)+        }+    }+}
Halo Family/Halo Family/Persistence/PersonMergeRepository.swift Added +193 / -0
diff --git a/Halo Family/Halo Family/Persistence/PersonMergeRepository.swift b/Halo Family/Halo Family/Persistence/PersonMergeRepository.swiftnew file mode 100644index 0000000..65ec7f7--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PersonMergeRepository.swift	@@ -0,0 +1,193 @@+import CoreData+import Foundation++@MainActor+extension FamilyRepository {+    func mergePeople(_ preview: PersonMergePreview, choices: PersonMergeChoices) throws -> NSManagedObjectID {+        try write { context in+            let source = try record(preview.source.id, entity: "Person", in: context)+            let survivor = try record(preview.survivor.id, entity: "Person", in: context)+            let family = try record(preview.familyID, entity: "FamilySpace", in: context)+            try requireSameFamily(source, family: family)+            try requireSameFamily(survivor, family: family)+            let before = try MergeSnapshot.records(family: family, in: context)+            guard try mergeConflicts(family: family, in: context).isEmpty else { throw MergeError.changed }+            guard before == preview.records, source != survivor, source.value(forKey: "mergedInto") == nil,+                  survivor.value(forKey: "mergedInto") == nil else { throw MergeError.changed }+            // Validate every displayed choice before changing anything.+            try validateMergeChoices(preview.overlaps, choices: choices)+            let all = try MergeSnapshot.objects(family: family, in: context)+            try applyPersonFields(source: source, survivor: survivor, choices: choices)+            let sourceProfile = source.value(forKey: "childProfile") as? NSManagedObject+            let survivorProfile = survivor.value(forKey: "childProfile") as? NSManagedObject+            var retainedHistoricalProfile: NSManagedObject?+            if let sourceProfile, let survivorProfile {+                // Both marked the same child. Keep the survivor's profile identity and all peer references.+                for object in all.values where object.entity.name == "Connection" &&+                    (object.value(forKey: "child") as? NSManagedObject) == sourceProfile {+                    object.setValue(survivorProfile, forKey: "child")+                }+                sourceProfile.setValue(Date(), forKey: "archivedAt")+                sourceProfile.setValue(survivorProfile, forKey: "mergedInto")+                retainedHistoricalProfile = sourceProfile+            }+            for object in all.values where object != source && object != survivor && object != family &&+                object != retainedHistoricalProfile && object.entity.name != "PersonMerge" {+                try repointPersonReferences(object, from: source, to: survivor)+            }+            for overlap in preview.overlaps {+                guard let choice = choices.connections[overlap.id] else { throw MergeError.choiceRequired }+                try consolidate(overlap, choices: choice, family: family, in: context)+            }+            // A fact between the duplicate identities becomes a self-reference. Retain it as archived history.+            let selfLinks = Set(before.filter {+                ["PersonRelationship", "RelationshipAssertion"].contains($0.entity) &&+                    Set(($0.links["source"] ?? []) + ($0.links["target"] ?? [])) == [preview.source.stableID, preview.survivor.stableID]+            }.map(\.id))+            for id in selfLinks { all[id]?.setValue(Date(), forKey: "archivedAt") }+            for id in preview.selfConnections {+                try record(id, entity: "Connection", in: context).setValue(Date(), forKey: "archivedAt")+            }+            source.setValue(survivor, forKey: "mergedInto")+            source.setValue(Date(), forKey: "archivedAt")+            source.setValue(Date(), forKey: "modifiedAt")+            let after = try MergeSnapshot.records(family: family, in: context)+            let old = Dictionary(uniqueKeysWithValues: before.map { ($0.id, $0) })+            let changed = after.filter { old[$0.id] != $0 }+            let changedIDs = Set(changed.map(\.id))+            let audit = insert("PersonMerge", in: context, store: try owningStore(of: family))+            audit.setValue(family, forKey: "familySpace")+            audit.setValue(preview.source.stableID, forKey: "sourceID")+            audit.setValue(preview.survivor.stableID, forKey: "survivorID")+            audit.setValue(preview.source.name, forKey: "sourceName")+            audit.setValue(preview.survivor.name, forKey: "survivorName")+            audit.setValue(Date(), forKey: "createdAt")+            let recoveries = NSFetchRequest<NSManagedObject>(entityName: "PersonMergeRecovery")+            recoveries.predicate = NSPredicate(format: "familySpace == %@", family)+            let recoveryIDs = try context.fetch(recoveries).map(stable).sorted { $0.uuidString < $1.uuidString }+            audit.setValue(String(data: try JSONEncoder().encode(recoveryIDs), encoding: .utf8), forKey: "recoveryIDs")+            audit.setValue(try MergeSnapshot.encode(before.filter { changedIDs.contains($0.id) }), forKey: "beforeData")+            audit.setValue(try MergeSnapshot.encode(changed), forKey: "afterData")+            let archivedIDs = Set(changed.filter {+                $0.entity == "Connection" && $0.attributes["archivedAt"] != nil && old[$0.id]?.attributes["archivedAt"] == nil+            }.map(\.id))+            audit.setValue(try MergeSnapshot.encode(after.filter {+                archivedIDs.contains($0.id) || !archivedIDs.isDisjoint(with: $0.links["connection"] ?? [])+            }), forKey: "archivedData")+            try requireMergeWritePermissions(context)+            return audit+        }+    }++    private func applyPersonFields(source: NSManagedObject, survivor: NSManagedObject, choices: PersonMergeChoices) throws {+        let selectedName = choices.name == .source ? source : survivor+        survivor.setValue(try validated(selectedName.value(forKey: "displayName") as? String ?? ""), forKey: "displayName")+        for (key, side) in [("givenName", choices.givenName), ("familyName", choices.familyName)]+            where survivor.entity.attributesByName[key] != nil && source.entity.attributesByName[key] != nil {+            let selected = side == .source ? source : survivor+            survivor.setValue(selected.value(forKey: key), forKey: key)+        }+        let sourceNotes = source.value(forKey: "notes") as? String ?? ""+        let survivorNotes = survivor.value(forKey: "notes") as? String ?? ""+        let notes: String+        switch choices.notes {+        case .source: notes = sourceNotes+        case .survivor: notes = survivorNotes+        case .both:+            notes = sourceNotes.isEmpty || sourceNotes == survivorNotes ? survivorNotes :+                (survivorNotes.isEmpty ? sourceNotes : survivorNotes + "\n\n" + sourceNotes)+        }+        survivor.setValue(notes.isEmpty ? nil : notes, forKey: "notes")+        let sensitive = choices.sensitive == .source ? source : survivor+        let sensitiveValues = ["isDeceased", "deathYear", "deathMonth", "deathDay"].map { sensitive.value(forKey: $0) }+        for (key, value) in zip(["isDeceased", "deathYear", "deathMonth", "deathDay"], sensitiveValues) {+            survivor.setValue(value, forKey: key)+        }+        if choices.photo == .source { survivor.setValue(source.value(forKey: "primaryPhoto"), forKey: "primaryPhoto") }+        // Person photos have a to-one owner. Keep both payloads, but only the selected photo is primary.+        source.setValue(nil, forKey: "primaryPhoto")+        let review = (source.value(forKey: "needsReview") as? Bool ?? false) || (survivor.value(forKey: "needsReview") as? Bool ?? false)+        survivor.setValue(review, forKey: "needsReview")+        survivor.setValue(Date(), forKey: "modifiedAt")+    }++    private func repointPersonReferences(_ object: NSManagedObject, from source: NSManagedObject, to survivor: NSManagedObject) throws {+        for (key, relationship) in object.entity.relationshipsByName where relationship.destinationEntity?.name == "Person" {+            if relationship.isToMany {+                var people = object.value(forKey: key) as? Set<NSManagedObject> ?? []+                if people.remove(source) != nil { people.insert(survivor); object.setValue(people, forKey: key) }+            } else if (object.value(forKey: key) as? NSManagedObject) == source {+                object.setValue(survivor, forKey: key)+            }+        }+    }++    private func validateMergeChoices(_ overlaps: [MergeConnectionOverlap], choices: PersonMergeChoices) throws {+        for overlap in overlaps {+            guard let choice = choices.connections[overlap.id], overlap.origins.contains(where: { $0.id == choice.originID }),+                  overlap.closeness.isEmpty || overlap.closeness.contains(where: { $0.id == choice.closenessID }),+                  overlap.statuses.isEmpty || overlap.statuses.contains(where: { $0.id == choice.statusID }) else {+                throw MergeError.choiceRequired+            }+        }+    }++    private func consolidate(_ overlap: MergeConnectionOverlap, choices: MergeConnectionChoices,+                             family: NSManagedObject, in context: NSManagedObjectContext) throws {+        let kept = try record(overlap.keptID, entity: "Connection", in: context)+        guard let chosen = overlap.origins.first(where: { $0.id == choices.originID }) else { throw MergeError.choiceRequired }+        var predecessors = try preparedHeads(connection: kept, heads: originHeads(connection: kept, in: context), in: context)+        for origin in overlap.origins where origin.connectionID != kept.objectID && origin.recordID != nil {+            // Preserve original immutable accounts on the archived connection; copy them as merge alternatives.+            let input = OriginInput(contextID: origin.contextID, eventID: origin.eventID, narrative: origin.narrative)+            let copy = try makeProposal(input: input, cleared: origin.cleared, connection: kept, predecessors: [], in: context)+            predecessors.append(copy)+        }+        if !predecessors.isEmpty || !chosen.cleared {+            _ = try makeProposal(input: OriginInput(contextID: chosen.contextID, eventID: chosen.eventID, narrative: chosen.narrative),+                                 cleared: chosen.cleared, connection: kept, predecessors: predecessors, in: context)+        }+        let store = try owningStore(of: family)+        if let selected = overlap.closeness.first(where: { $0.id == choices.closenessID }) {+            try mergePeriod("ConnectionClosenessPeriod", kept: kept, family: family, store: store, in: context) {+                $0.setValue(selected.value, forKey: "value")+            }+        }+        if let selected = overlap.statuses.first(where: { $0.id == choices.statusID }) {+            try mergePeriod("ConnectionStatusPeriod", kept: kept, family: family, store: store, in: context) {+                $0.setValue(selected.state?.rawValue, forKey: "state"); $0.setValue(selected.note, forKey: "note")+            }+        }+        for id in overlap.connections where id != kept.objectID {+            let connection = try record(id, entity: "Connection", in: context)+            let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionContext")+            request.predicate = NSPredicate(format: "connection == %@", connection)+            for membership in try context.fetch(request) { membership.setValue(kept, forKey: "connection") }+            connection.setValue(kept, forKey: "mergedInto")+            connection.setValue(Date(), forKey: "archivedAt")+        }+    }++    private func mergePeriod(_ entity: String, kept: NSManagedObject, family: NSManagedObject, store: NSPersistentStore,+                             in context: NSManagedObjectContext, configure: (NSManagedObject) -> Void) throws {+        let request = NSFetchRequest<NSManagedObject>(entityName: entity)+        request.predicate = NSPredicate(format: "connection == %@ AND endedAt == nil", kept)+        let previous = try context.fetch(request)+        let now = max(Date(), previous.compactMap { $0.value(forKey: "startedAt") as? Date }.max() ?? Date())+        for period in previous { period.setValue(now, forKey: "endedAt") }+        let period = insert(entity, in: context, store: store)+        period.setValue(family, forKey: "familySpace"); period.setValue(kept, forKey: "connection")+        period.setValue(now, forKey: "startedAt")+        configure(period)+    }++    func requireMergeWritePermissions(_ context: NSManagedObjectContext) throws {+        guard let cloud = stack.container as? NSPersistentCloudKitContainer else { return }+        for object in context.updatedObjects where !object.objectID.isTemporaryID {+            guard cloud.canUpdateRecord(forManagedObjectWith: object.objectID) else { throw GraphError.readOnly }+        }+        for object in context.deletedObjects {+            guard cloud.canDeleteRecord(forManagedObjectWith: object.objectID) else { throw GraphError.readOnly }+        }+    }+}
Halo Family/Halo Family/Persistence/PersonMergeTypes.swift Added +114 / -0
diff --git a/Halo Family/Halo Family/Persistence/PersonMergeTypes.swift b/Halo Family/Halo Family/Persistence/PersonMergeTypes.swiftnew file mode 100644index 0000000..2162632--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PersonMergeTypes.swift	@@ -0,0 +1,114 @@+import CoreData+import Foundation++nonisolated enum MergeSide: String, CaseIterable, Identifiable, Sendable {+    case survivor, source+    var id: Self { self }+    var label: String { self == .survivor ? "Kept person" : "Person being merged" }+}++nonisolated enum MergeNotesChoice: String, CaseIterable, Identifiable, Sendable {+    case both, survivor, source+    var id: Self { self }+    var label: String {+        switch self {+        case .both: "Keep both notes"+        case .survivor: "Kept person's notes"+        case .source: "Other person's notes"+        }+    }+}++struct MergePersonValues {+    let id: NSManagedObjectID+    let stableID: UUID+    let name: String+    let notes: String+    let sensitive: SensitiveSnapshot+    let photoID: NSManagedObjectID?+    var givenName = ""+    var familyName = ""+}++struct MergeOriginChoice: Identifiable {+    let id: UUID+    let recordID: NSManagedObjectID?+    let connectionID: NSManagedObjectID+    let label: String+    let contextID: NSManagedObjectID?+    let eventID: NSManagedObjectID?+    let narrative: String+    let cleared: Bool+    let proposal: Bool+}++struct MergePeriodChoice: Identifiable {+    let id: NSManagedObjectID+    let label: String+    let value: Int16?+    let state: ConnectionState?+    let note: String+}++struct MergeConnectionOverlap: Identifiable {+    let id: UUID+    let keptID: NSManagedObjectID+    let connections: [NSManagedObjectID]+    let childName: String+    let personName: String+    let origins: [MergeOriginChoice]+    let closeness: [MergePeriodChoice]+    let statuses: [MergePeriodChoice]+}++struct PersonMergePreview {+    let familyID: NSManagedObjectID+    let source: MergePersonValues+    let survivor: MergePersonValues+    let records: [MergeRecord]+    let overlaps: [MergeConnectionOverlap]+    let referenceCounts: [String: Int]+    let combinesChildProfiles: Bool+    let selfRelationships: Int+    let selfConnections: [NSManagedObjectID]+    let duplicateEventAccounts: Int+}++struct MergeConnectionChoices: Equatable {+    var originID: UUID?+    var closenessID: NSManagedObjectID?+    var statusID: NSManagedObjectID?+}++struct PersonMergeChoices: Equatable {+    var name: MergeSide = .survivor+    var givenName: MergeSide = .survivor+    var familyName: MergeSide = .survivor+    var notes: MergeNotesChoice = .both+    var photo: MergeSide = .survivor+    var sensitive: MergeSide = .survivor+    var connections: [UUID: MergeConnectionChoices] = [:]+}++struct PersonMergeHistoryRow: Identifiable {+    let id: NSManagedObjectID+    let sourceName: String+    let survivorName: String+    let sourceID: NSManagedObjectID?+    let survivorID: NSManagedObjectID?+    let createdAt: Date?+    let undone: Bool+    let undoAvailable: Bool+}++struct DuplicatePersonPair: Identifiable {+    let source: GraphRow+    let survivor: GraphRow+    let id: String+}++struct PersonMergeRecoveryRow: Identifiable {+    let id: NSManagedObjectID+    let createdAt: Date?+    let people: [MergeRecord]+}
Halo Family/Halo Family/Persistence/PortableGraph.swift Added +106 / -0
diff --git a/Halo Family/Halo Family/Persistence/PortableGraph.swift b/Halo Family/Halo Family/Persistence/PortableGraph.swiftnew file mode 100644index 0000000..d10d2b1--- /dev/null+++ b/Halo Family/Halo Family/Persistence/PortableGraph.swift	@@ -0,0 +1,106 @@+import CoreData+import Foundation++nonisolated enum PortableValue: Codable, Equatable, Sendable {+    case text(String)+    case number(Int64)+    case decimal(Double)+    case flag(Bool)+    case date(Date)+    case uuid(UUID)+    case binary(String)+}++nonisolated struct PortableRecord: Codable, Equatable, Sendable {+    let id: UUID+    let entity: String+    var attributes: [String: PortableValue]+    var relationships: [String: [UUID]]+}++nonisolated struct FamilyBackup: Codable, Sendable {+    let formatVersion: Int+    let modelVersion: Int+    let familyID: UUID+    let createdAt: Date+    let records: [PortableRecord]+}++/// Canonical UUID references are independent of local Core Data object-ID URI/store paths.+nonisolated enum PortableGraph {+    static func record(_ object: NSManagedObject, binary: (String, Data) throws -> String) throws -> PortableRecord {+        guard let id = object.value(forKey: "id") as? UUID, let entity = object.entity.name else { throw BackupError.missingIdentity }+        var values: [String: PortableValue] = [:]+        for (name, attribute) in object.entity.attributesByName {+            guard let value = object.value(forKey: name) else { continue }+            switch attribute.attributeType {+            case .stringAttributeType: values[name] = .text(try cast(value))+            case .booleanAttributeType: values[name] = .flag((try cast(value) as NSNumber).boolValue)+            case .integer16AttributeType, .integer32AttributeType, .integer64AttributeType:+                values[name] = .number((try cast(value) as NSNumber).int64Value)+            case .doubleAttributeType, .floatAttributeType, .decimalAttributeType:+                values[name] = .decimal((try cast(value) as NSNumber).doubleValue)+            case .dateAttributeType: values[name] = .date(try cast(value))+            case .UUIDAttributeType: values[name] = .uuid(try cast(value))+            case .binaryDataAttributeType: values[name] = .binary(try binary(name, cast(value)))+            default: throw BackupError.unsupportedVersion+            }+        }+        var links: [String: [UUID]] = [:]+        for (name, relationship) in object.entity.relationshipsByName {+            let targets: [NSManagedObject]+            if relationship.isToMany { targets = Array((object.value(forKey: name) as? Set<NSManagedObject>) ?? []) } else {+                targets = (object.value(forKey: name) as? NSManagedObject).map { [$0] } ?? []+            }+            links[name] = try targets.map { target in+                guard let uuid = target.value(forKey: "id") as? UUID else { throw BackupError.missingIdentity }+                return uuid+            }.sorted { $0.uuidString < $1.uuidString }+        }+        return PortableRecord(id: id, entity: entity, attributes: values, relationships: links)+    }++    static func value(_ portable: PortableValue, binary: (String) throws -> Data) throws -> Any {+        switch portable {+        case .text(let value): value+        case .number(let value): NSNumber(value: value)+        case .decimal(let value): NSNumber(value: value)+        case .flag(let value): NSNumber(value: value)+        case .date(let value): value+        case .uuid(let value): value+        case .binary(let path): try binary(path)+        }+    }++    static func accepts(_ value: PortableValue, attribute: NSAttributeDescription) -> Bool {+        switch (value, attribute.attributeType) {+        case (.text, .stringAttributeType), (.flag, .booleanAttributeType),+             (.uuid, .UUIDAttributeType), (.binary, .binaryDataAttributeType): true+        case (.date(let date), .dateAttributeType): date.timeIntervalSinceReferenceDate.isFinite+        case (.number(let number), .integer16AttributeType): Int16(exactly: number) != nil+        case (.number(let number), .integer32AttributeType): Int32(exactly: number) != nil+        case (.number, .integer64AttributeType): true+        case (.decimal(let number), .doubleAttributeType), (.decimal(let number), .floatAttributeType),+             (.decimal(let number), .decimalAttributeType): number.isFinite+        default: false+        }+    }++    static func encode<T: Encodable>(_ value: T) throws -> Data {+        let encoder = JSONEncoder()+        encoder.outputFormatting = [.sortedKeys, .prettyPrinted]+        encoder.dateEncodingStrategy = .deferredToDate+        return try encoder.encode(value)+    }++    static func decode<T: Decodable>(_ type: T.Type, data: Data) throws -> T {+        let decoder = JSONDecoder()+        decoder.dateDecodingStrategy = .deferredToDate+        return try decoder.decode(type, from: data)+    }++    private static func cast<T>(_ value: Any) throws -> T {+        guard let value = value as? T else { throw BackupError.invalidArchive }+        return value+    }+}
Halo Family/Halo Family/Persistence/RelationshipMutations.swift Added +203 / -0
diff --git a/Halo Family/Halo Family/Persistence/RelationshipMutations.swift b/Halo Family/Halo Family/Persistence/RelationshipMutations.swiftnew file mode 100644index 0000000..0822f21--- /dev/null+++ b/Halo Family/Halo Family/Persistence/RelationshipMutations.swift	@@ -0,0 +1,203 @@+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 {+        try updatePerson(personID, input: PersonInput(name: name, notes: notes, needsReview: needsReview), expected: expected)+    }++    func updatePerson(_ personID: NSManagedObjectID, input: PersonInput, expected: PersonDetail) throws {+        let name = try validated(input.name)+        let notes = input.notes.trimmingCharacters(in: .whitespacesAndNewlines)+        _ = try write { context in+            let person = try record(personID, entity: "Person", in: context)+            let supportsNotes = person.entity.attributesByName["notes"] != nil+            let structured = person.entity.attributesByName["givenName"] != nil+            let given = structured ? person.value(forKey: "givenName") as? String ?? "" : ""+            let family = structured ? person.value(forKey: "familyName") as? String ?? "" : ""+            guard expected.id == personID,+                  (person.value(forKey: "displayName") as? String ?? "Unnamed") == expected.name,+                  (supportsNotes ? person.value(forKey: "notes") as? String ?? "" : "") == expected.notes,+                  (person.value(forKey: "needsReview") as? Bool ?? false) == expected.needsReview,+                  given == expected.givenName, family == expected.familyName else {+                throw GraphError.personChanged+            }+            guard structured || (input.givenName == nil && input.familyName == nil) else { throw GraphError.modelUnavailable }+            guard supportsNotes || notes.isEmpty else { throw GraphError.modelUnavailable }+            person.setValue(name, forKey: "displayName")+            if supportsNotes { person.setValue(notes, forKey: "notes") }+            person.setValue(input.needsReview, forKey: "needsReview")+            for (key, value) in [("givenName", input.givenName), ("familyName", input.familyName)] {+                if let value {+                    let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)+                    person.setValue(trimmed.isEmpty ? nil : trimmed, forKey: key)+                }+            }+            person.setValue(Date(), forKey: "modifiedAt")+            return person+        }+    }++    func createContext(name: String, familyID: NSManagedObjectID, parentID: NSManagedObjectID? = nil) throws -> NSManagedObjectID {+        let name = try validated(name)+        return try write { context in+            let family = try record(familyID, entity: "FamilySpace", in: context)+            let parent = try parentID.map { try record($0, entity: "Context", in: context) }+            if let parent { try requireSameFamily(parent, family: family) }+            let source = insert("Context", in: context, store: try owningStore(of: family))+            source.setValue(name, forKey: "name")+            source.setValue(family, forKey: "familySpace")+            source.setValue(parent, forKey: "parent")+            return source+        }+    }++    func moveContext(_ contextID: NSManagedObjectID, parentID: NSManagedObjectID?) throws {+        _ = try write { context in+            let source = try record(contextID, entity: "Context", in: context)+            let family = try family(of: source)+            let parent = try parentID.map { try record($0, entity: "Context", in: context) }+            if let parent { try requireSameFamily(parent, family: family) }+            var current = parent+            var seen: Set<NSManagedObjectID> = [source.objectID]+            while let node = current {+                guard seen.insert(node.objectID).inserted else { throw GraphError.contextCycle }+                current = node.value(forKey: "parent") as? NSManagedObject+            }+            source.setValue(parent, forKey: "parent")+            return source+        }+    }++    func archiveContext(_ contextID: NSManagedObjectID, archived: Bool) throws {+        _ = try write { context in+            let source = try record(contextID, entity: "Context", in: context)+            source.setValue(archived ? Date() : nil, forKey: "archivedAt")+            return source+        }+    }++    func addMembership(connectionID: NSManagedObjectID, contextID: NSManagedObjectID,+                       startedAt: Date? = nil, endedAt: Date? = nil) throws -> NSManagedObjectID {+        try validateDates(startedAt, endedAt)+        return try write { context in+            let connection = try record(connectionID, entity: "Connection", in: context)+            let source = try record(contextID, entity: "Context", in: context)+            let family = try family(of: connection)+            try requireSameFamily(source, family: family)+            let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionContext")+            request.predicate = NSPredicate(format: "connection == %@ AND context == %@ AND endedAt == nil", connection, source)+            if endedAt == nil, try context.count(for: request) > 0 { throw GraphError.duplicateMembership }+            let membership = insert("ConnectionContext", in: context, store: try owningStore(of: family))+            membership.setValue(family, forKey: "familySpace")+            membership.setValue(connection, forKey: "connection")+            membership.setValue(source, forKey: "context")+            membership.setValue(startedAt, forKey: "startedAt")+            membership.setValue(endedAt, forKey: "endedAt")+            return membership+        }+    }++    func endMembership(_ membershipID: NSManagedObjectID, at date: Date) throws {+        _ = try write { context in+            let membership = try record(membershipID, entity: "ConnectionContext", in: context)+            guard let connection = membership.value(forKey: "connection") as? NSManagedObject else { throw GraphError.invalidReference }+            _ = try record(connection.objectID, entity: "Connection", in: context)+            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 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 person = try record(expected.personID, entity: "Person", in: context)+            try requireSameFamily(person, family: family(of: link))+            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 }+    }+}
Halo Family/Halo Family/Persistence/RelationshipQueries.swift Added +223 / -0
diff --git a/Halo Family/Halo Family/Persistence/RelationshipQueries.swift b/Halo Family/Halo Family/Persistence/RelationshipQueries.swiftnew file mode 100644index 0000000..4d69ec2--- /dev/null+++ b/Halo Family/Halo Family/Persistence/RelationshipQueries.swift	@@ -0,0 +1,223 @@+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+    var givenName = ""+    var familyName = ""+    var isArchived = false+}++struct PersonInput {+    var name: String+    var notes = ""+    var needsReview = true+    // Omitted values preserve existing names for lightweight callers; empty values explicitly clear them.+    var givenName: String?+    var familyName: String?+}++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, includeArchived: Bool = false) throws -> [GraphRow] {+        var predicates = [NSPredicate(format: "familySpace == %@", familyID)]+        if stack.container.managedObjectModel.entitiesByName["Person"]?.attributesByName["archivedAt"] != nil {+            let conflicted = try mergeConflicts(in: familyID).flatMap { $0.people.map(\.id) }+            let current = includeArchived ? "mergedInto == nil" : "archivedAt == nil AND mergedInto == nil"+            predicates.append(NSPredicate(format: "(\(current)) OR SELF IN %@", conflicted))+            if needsReview || !includeDeceased { predicates.append(NSPredicate(format: "isDeceased == NO OR isDeceased == nil")) }+        }+        let search = search.trimmingCharacters(in: .whitespacesAndNewlines)+        if !search.isEmpty { predicates.append(try peopleSearch(search, familyID: familyID)) }+        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")+        let structured = person.entity.attributesByName["givenName"] != nil+        return PersonDetail(id: id, name: person.value(forKey: "displayName") as? String ?? "Unnamed",+                            notes: person.entity.attributesByName["notes"] != nil ? person.value(forKey: "notes") as? String ?? "" : "",+                            needsReview: person.value(forKey: "needsReview") as? Bool ?? false,+                            givenName: structured ? person.value(forKey: "givenName") as? String ?? "" : "",+                            familyName: structured ? person.value(forKey: "familyName") as? String ?? "" : "",+                            isArchived: person.entity.attributesByName["archivedAt"] != nil && person.value(forKey: "archivedAt") != nil)+    }++    func personID(for connectionID: NSManagedObjectID) throws -> NSManagedObjectID {+        let connection = try readable(connectionID, entity: "Connection")+        guard let person = connection.value(forKey: "person") as? NSManagedObject else { throw GraphError.invalidReference }+        return person.objectID+    }++    func connections(to personID: NSManagedObjectID) throws -> [GraphRow] {+        let modern = stack.container.managedObjectModel.entitiesByName["Connection"]?.attributesByName["archivedAt"] != nil+        return try rows(entity: "Connection", nameKey: "child.person.displayName", predicate: modern ?+            NSPredicate(format: "person == %@ AND archivedAt == nil AND mergedInto == nil", personID) :+            NSPredicate(format: "person == %@", personID))+    }++    func contextIsArchived(_ contextID: NSManagedObjectID) throws -> Bool {+        try readable(contextID, entity: "Context").value(forKey: "archivedAt") != nil+    }++    func contexts(in familyID: NSManagedObjectID, includeArchived: Bool = true) throws -> [ContextRow] {+        let request = NSFetchRequest<NSManagedObject>(entityName: "Context")+        request.predicate = NSPredicate(format: "familySpace == %@", familyID)+        return try stack.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.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.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.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.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 let object = try readable([id], entity: entity).first else { throw GraphError.invalidReference }+        return object+    }++    func readable(_ ids: [NSManagedObjectID], entity: String) throws -> [NSManagedObject] {+        try stack.access.check()+        // This synchronous batch checks root uniqueness once per family/store; permissions remain checked for every record.+        var checked = Set<FamilyAccessID>()+        return try ids.map { id in+            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 }+            let identity = try StoreAccess.identity(object, checkingDuplicates: false)+            if checked.insert(identity).inserted {+                try stack.access.check(object)+            } else {+                try stack.access.check(family: identity.family, shared: identity.shared)+            }+            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: " › ")+    }+}
Halo Family/Halo Family/Persistence/ReviewRepository.swift Added +37 / -0
diff --git a/Halo Family/Halo Family/Persistence/ReviewRepository.swift b/Halo Family/Halo Family/Persistence/ReviewRepository.swiftnew file mode 100644index 0000000..51518de--- /dev/null+++ b/Halo Family/Halo Family/Persistence/ReviewRepository.swift	@@ -0,0 +1,37 @@+import CoreData+import Foundation++struct ConnectionReviewRow: Identifiable {+    let id: NSManagedObjectID+    let name: String+    let childName: String+    let originNeedsReview: Bool+    let relationshipNeedsReview: Bool+}++@MainActor+extension FamilyRepository {+    func reviewConnections(in familyID: NSManagedObjectID) throws -> [ConnectionReviewRow] {+        _ = try readable(familyID, entity: "FamilySpace")+        let request = NSFetchRequest<NSManagedObject>(entityName: "Connection")+        let modern = stack.container.managedObjectModel.entitiesByName["Connection"]?.attributesByName["archivedAt"] != nil+        request.predicate = modern ? NSPredicate(format: "familySpace == %@ AND archivedAt == nil AND mergedInto == nil", familyID) :+            NSPredicate(format: "familySpace == %@", familyID)+        request.sortDescriptors = [NSSortDescriptor(key: "person.displayName", ascending: true),+                                   NSSortDescriptor(key: "child.person.displayName", ascending: true)]+        request.relationshipKeyPathsForPrefetching = ["person", "child.person"]+        let connections = try stack.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)+        }+    }+}
Halo Family/Halo Family/Persistence/StoreConfiguration.swift Modified +9 / -3
diff --git a/Halo Family/Halo Family/Persistence/StoreConfiguration.swift b/Halo Family/Halo Family/Persistence/StoreConfiguration.swiftindex 1781e4e..479924f 100644--- a/Halo Family/Halo Family/Persistence/StoreConfiguration.swift	+++ b/Halo Family/Halo Family/Persistence/StoreConfiguration.swift	@@ -15,13 +15,15 @@ nonisolated struct StoreConfiguration: Sendable {     let directory: URL     let role: PersistenceRole     let mirrorsCloud: Bool+    var accountScope: AccountScope? -    static func production(role: PersistenceRole) throws -> StoreConfiguration {+    static func production(role: PersistenceRole, scope: AccountScope) throws -> StoreConfiguration {         guard let group = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {             throw PersistenceError.appGroupUnavailable         }-        return StoreConfiguration(directory: group.appendingPathComponent("Persistence", isDirectory: true),-                                  role: role, mirrorsCloud: role == .host)+        let root = group.appendingPathComponent("Persistence", isDirectory: true)+        return StoreConfiguration(directory: scope.directory(in: root), role: role,+                                  mirrorsCloud: role == .host && scope.mirrorsCloud, accountScope: scope)     }      func descriptions() -> [NSPersistentStoreDescription] {@@ -31,6 +33,10 @@ nonisolated struct StoreConfiguration: Sendable {             description.shouldMigrateStoreAutomatically = role == .host             description.shouldInferMappingModelAutomatically = role == .host             description.isReadOnly = role == .widget+            #if os(iOS)+            description.setOption(FileProtectionType.completeUntilFirstUserAuthentication.rawValue as NSString,+                                  forKey: NSPersistentStoreFileProtectionKey)+            #endif             description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)             description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)             if mirrorsCloud && role == .host {
Halo Family/Halo Family/Persistence/SyntheticLaunch.swift Added +15 / -0
diff --git a/Halo Family/Halo Family/Persistence/SyntheticLaunch.swift b/Halo Family/Halo Family/Persistence/SyntheticLaunch.swiftnew file mode 100644index 0000000..8fa757e--- /dev/null+++ b/Halo Family/Halo Family/Persistence/SyntheticLaunch.swift	@@ -0,0 +1,15 @@+import Foundation++/// Debug UI checks use a fresh local directory and never open the App Group or CloudKit.+nonisolated enum SyntheticLaunch {+    static func directory(arguments: [String] = ProcessInfo.processInfo.arguments) throws -> URL? {+        guard let position = arguments.firstIndex(of: "--synthetic-store") else { return nil }+        guard arguments.indices.contains(position + 1) else { throw GraphError.invalidReference }+        let directory = URL(fileURLWithPath: arguments[position + 1], isDirectory: true).resolvingSymlinksInPath()+        let roots = [FileManager.default.temporaryDirectory, URL(fileURLWithPath: "/tmp", isDirectory: true)]+        guard roots.contains(where: {+            directory.path.hasPrefix($0.resolvingSymlinksInPath().path + "/")+        }) else { throw GraphError.invalidReference }+        return directory+    }+}
Halo Family/Halo Family/PersonMergeHistoryView.swift Added +124 / -0
diff --git a/Halo Family/Halo Family/PersonMergeHistoryView.swift b/Halo Family/Halo Family/PersonMergeHistoryView.swiftnew file mode 100644index 0000000..d4ecf6c--- /dev/null+++ b/Halo Family/Halo Family/PersonMergeHistoryView.swift	@@ -0,0 +1,124 @@+import Combine+import CoreData+import SwiftUI++struct PersonMergeHistoryView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    @State private var history: [PersonMergeHistoryRow] = []+    @State private var recoveries: [PersonMergeRecoveryRow] = []+    @State private var failure: String?++    var body: some View {+        List {+            if history.isEmpty && recoveries.isEmpty { Text("No people have been merged in this family.").foregroundStyle(.secondary) }+            ForEach(history) { merge in+                NavigationLink {+                    MergeHistoryDetail(repository: repository, familyID: familyID, merge: merge)+                } label: {+                    VStack(alignment: .leading) {+                        Text("\(merge.sourceName) → \(merge.survivorName)")+                        if let date = merge.createdAt { Text(date.formatted(date: .abbreviated, time: .shortened)).font(.caption) }+                        Text(merge.undone ? "Undone" :+                            (merge.undoAvailable ? "Undo available" : "Affected records changed; undo unavailable"))+                            .font(.caption).foregroundStyle(.secondary)+                    }+                }+            }+            if !recoveries.isEmpty {+                Section("Recovery history") {+                    ForEach(recoveries) { recovery in+                        NavigationLink {+                            MemoryForm {+                                MemorySection("Separate identities recovered") {+                                    Text("Recovery kept the current references and earlier merge audits. " ++                                         "These are the person details observed before clearing the competing aliases.")+                                    ForEach(recovery.people, id: \.id) { person in+                                        if case .text(let name) = person.attributes["displayName"] { Text(name).font(.headline) }+                                        if case .text(let notes) = person.attributes["notes"], !notes.isEmpty { Text(notes) }+                                    }+                                }+                            }.navigationTitle("Merge recovery")+                        } label: {+                            VStack(alignment: .leading) {+                                Text("Separate identities recovered")+                                if let date = recovery.createdAt {+                                    Text(date.formatted(date: .abbreviated, time: .shortened)).font(.caption)+                                }+                            }+                        }+                    }+                }+            }+        }+        .navigationTitle("Merge history")+        .task { reload() }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in reload() }+        .graphFailure($failure)+    }++    private func reload() {+        do {+            let history = try repository.mergeHistory(in: familyID)+            let recoveries = try repository.mergeRecoveryHistory(in: familyID)+            self.history = history; self.recoveries = recoveries+        } catch { failure = error.localizedDescription }+    }+}++private struct MergeHistoryDetail: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    let merge: PersonMergeHistoryRow+    @State private var records: [MergeRecord] = []+    @State private var connections: [GraphRow] = []+    @State private var confirmingUndo = false+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    var body: some View {+        MemoryForm {+            MemorySection("Earlier person details") {+                ForEach(records.filter { $0.entity == "Person" }, id: \.id) { record in+                    if case .text(let name) = record.attributes["displayName"] { Text(name).font(.headline) }+                    if case .text(let notes) = record.attributes["notes"], !notes.isEmpty { Text(notes) }+                }+            }+            if let survivorID = merge.survivorID {+                MemorySection("Kept person") {+                    NavigationLink(merge.survivorName) {+                        PersonDetailView(repository: repository, familyID: familyID, personID: survivorID)+                    }+                }+            }+            if !connections.isEmpty {+                MemorySection("Earlier relationship accounts") {+                    ForEach(connections) { connection in+                        NavigationLink(connection.name) {+                            ConnectionDetailView(repository: repository, familyID: familyID, connection: connection, readOnly: true)+                        }+                    }+                }+            }+            MemorySection("Undo") {+                Text("Undo restores both people and their references only while affected records remain unchanged. " ++                     "A fresh check is made before saving. Unrelated family records are preserved.")+                Button("Undo this merge") { confirmingUndo = true }.disabled(!merge.undoAvailable)+            }+        }+        .navigationTitle("\(merge.sourceName) → \(merge.survivorName)")+        .task {+            do {+                records = try repository.mergePreviousDetails(merge.id)+                connections = try repository.archivedMergeConnections(merge.id)+            } catch { failure = error.localizedDescription }+        }+        .confirmationDialog("Restore both people and their previous references?", isPresented: $confirmingUndo) {+            Button("Undo merge") {+                do { try repository.undoPersonMerge(merge.id); dismiss() } catch { failure = error.localizedDescription }+            }+        }+        .graphFailure($failure)+    }+}
Halo Family/Halo Family/PersonMergeView.swift Added +216 / -0
diff --git a/Halo Family/Halo Family/PersonMergeView.swift b/Halo Family/Halo Family/PersonMergeView.swiftnew file mode 100644index 0000000..3e508a8--- /dev/null+++ b/Halo Family/Halo Family/PersonMergeView.swift	@@ -0,0 +1,216 @@+import CoreData+import SwiftUI++struct PersonMergeView: View {+    let repository: FamilyRepository+    let familyID: NSManagedObjectID+    let sourceID: NSManagedObjectID+    @State private var survivorID: NSManagedObjectID?+    @State private var people: [GraphRow] = []+    @State private var preview: PersonMergePreview?+    @State private var choices = PersonMergeChoices()+    @State private var confirmed = false+    @State private var failure: String?+    @Environment(\.dismiss) private var dismiss++    init(repository: FamilyRepository, familyID: NSManagedObjectID, sourceID: NSManagedObjectID,+         preferredSurvivor: NSManagedObjectID? = nil) {+        self.repository = repository; self.familyID = familyID; self.sourceID = sourceID+        _survivorID = State(initialValue: preferredSurvivor)+    }++    var body: some View {+        NavigationStack {+            MemoryForm {+                MemorySection("Choose the person to keep") {+                    MemoryField("Kept person") {+                        Picker("Kept person", selection: $survivorID) {+                            Text("Choose a person").tag(nil as NSManagedObjectID?)+                            ForEach(people.filter { $0.id != sourceID }) { Text($0.name).tag(Optional($0.id)) }+                        }+                    }+                    Button(preview == nil ? "Preview merge" : "Refresh preview") { prepare() }.disabled(survivorID == nil)+                    Text("Only merge records that represent the same person. Similar names can belong to different people.")+                        .font(.callout).foregroundStyle(.secondary)+                }+                if let preview {+                    personChoices(preview)+                    MemorySection("References and history") {+                        ForEach(preview.referenceCounts.keys.sorted(), id: \.self) { key in+                            Text("\(referenceLabel(key)): \(preview.referenceCounts[key] ?? 0)")+                        }+                        Text("The kept person's identity remains. The other person is retained as a hidden merge record. " ++                             "Existing notes, photos and relationship accounts remain in the records or merge history.")+                        if preview.combinesChildProfiles {+                            Text("Both records are marked as our child. The kept person's child profile remains; " ++                                 "peer relationships are combined and the other profile is archived.")+                        }+                        if preview.selfRelationships > 0 {+                            Text("\(preview.selfRelationships) family facts between these records will be archived, " ++                                 "because they would otherwise describe a person related to themselves.")+                        }+                        if !preview.selfConnections.isEmpty {+                            Text("\(preview.selfConnections.count) child relationships will be archived because they would " ++                                 "otherwise list the child as someone they know. Their accounts remain in history.")+                        }+                        if preview.duplicateEventAccounts > 0 {+                            Text("Existing participation accounts for the same event stay separate, " ++                                 "including their roles, invitations, attendance and notes.")+                        }+                    }+                    ForEach(preview.overlaps) { overlap in overlapChoices(overlap) }+                    MemorySection("Confirm the preview") {+                        Toggle("These records are the same person, and I have reviewed these choices", isOn: $confirmed)+                        Text("Undo is available in merge history while the affected records remain unchanged. " ++                             "A later edit or new reference can make undo unavailable.")+                            .font(.caption).foregroundStyle(.secondary)+                        Button("Merge people") {+                            do { _ = try repository.mergePeople(preview, choices: choices); dismiss() } catch {+                                failure = error.localizedDescription+                            }+                        }.disabled(!confirmed || !complete(preview))+                    }+                }+            }+            .navigationTitle("Merge people")+            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } }+        }+        .frame(minWidth: 340, minHeight: 480)+        .task {+            do { people = try repository.people(in: familyID) } catch { failure = error.localizedDescription }+        }+        .onChange(of: survivorID) { preview = nil; confirmed = false }+        .onChange(of: choices) { confirmed = false }+        .graphFailure($failure)+    }++    @ViewBuilder private func personChoices(_ preview: PersonMergePreview) -> some View {+        MemorySection("\(preview.source.name) → \(preview.survivor.name)") {+            MemoryField("Display name") {+                Picker("Display name", selection: $choices.name) {+                    Text(preview.survivor.name).tag(MergeSide.survivor)+                    Text(preview.source.name).tag(MergeSide.source)+                }+            }+            if !preview.survivor.givenName.isEmpty || !preview.source.givenName.isEmpty {+                nameChoice("Given name", kept: preview.survivor.givenName, other: preview.source.givenName, selection: $choices.givenName)+            }+            if !preview.survivor.familyName.isEmpty || !preview.source.familyName.isEmpty {+                nameChoice("Family name", kept: preview.survivor.familyName, other: preview.source.familyName,+                           selection: $choices.familyName)+            }+            if !preview.source.notes.isEmpty || !preview.survivor.notes.isEmpty {+                MemoryField("Notes") {+                    Picker("Notes", selection: $choices.notes) {+                        ForEach(MergeNotesChoice.allCases) { Text($0.label).tag($0) }+                    }+                }+                if !preview.survivor.notes.isEmpty { Text("Kept person's notes: \(preview.survivor.notes)") }+                if !preview.source.notes.isEmpty { Text("Other person's notes: \(preview.source.notes)") }+            }+            if preview.source.photoID != nil || preview.survivor.photoID != nil {+                MemoryField("Primary photo") {+                    Picker("Primary photo", selection: $choices.photo) {+                        Text("Kept person: \(preview.survivor.photoID == nil ? "no photo" : "photo")").tag(MergeSide.survivor)+                        Text("Other person: \(preview.source.photoID == nil ? "no photo" : "photo")").tag(MergeSide.source)+                    }+                }+            }+            if preview.source.sensitive != preview.survivor.sensitive {+                MemoryField("Sensitive Details") {+                    Picker("Sensitive Details", selection: $choices.sensitive) {+                        Text("Kept person: \(sensitiveLabel(preview.survivor.sensitive))").tag(MergeSide.survivor)+                        Text("Other person: \(sensitiveLabel(preview.source.sensitive))").tag(MergeSide.source)+                    }+                }+            }+        }+    }++    private func nameChoice(_ title: String, kept: String, other: String, selection: Binding<MergeSide>) -> some View {+        MemoryField(title) {+            Picker(title, selection: selection) {+                Text("Kept person: \(kept.isEmpty ? "Not recorded" : kept)").tag(MergeSide.survivor)+                Text("Other person: \(other.isEmpty ? "Not recorded" : other)").tag(MergeSide.source)+            }+        }+    }++    @ViewBuilder private func overlapChoices(_ overlap: MergeConnectionOverlap) -> some View {+        MemorySection("\(overlap.childName) knows \(overlap.personName)") {+            Text("These records contain overlapping child relationships. One connection remains current; " ++                 "the other connections and their accounts remain in merge history.")+            MemoryField("First meeting") {+                Picker("First meeting", selection: connectionBinding(overlap.id, \.originID)) {+                    Text("Choose an account").tag(nil as UUID?)+                    ForEach(overlap.origins) { Text($0.label).tag(Optional($0.id)) }+                }+            }+            ForEach(overlap.origins) { origin in+                if !origin.narrative.isEmpty { Text("\(origin.label) · \(origin.narrative)").font(.caption) }+            }+            if !overlap.closeness.isEmpty {+                MemoryField("Closeness") {+                    Picker("Closeness", selection: connectionBinding(overlap.id, \.closenessID)) {+                        Text("Choose a value").tag(nil as NSManagedObjectID?)+                        ForEach(overlap.closeness) { Text($0.label).tag(Optional($0.id)) }+                    }+                }+            }+            if !overlap.statuses.isEmpty {+                MemoryField("Contact status") {+                    Picker("Contact status", selection: connectionBinding(overlap.id, \.statusID)) {+                        Text("Choose an account").tag(nil as NSManagedObjectID?)+                        ForEach(overlap.statuses) { Text($0.label + ($0.note.isEmpty ? "" : " · " + $0.note)).tag(Optional($0.id)) }+                    }+                }+            }+        }+    }++    private func connectionBinding<Value>(_ id: UUID, _ key: WritableKeyPath<MergeConnectionChoices, Value>) -> Binding<Value> {+        Binding(get: { (choices.connections[id] ?? MergeConnectionChoices())[keyPath: key] }, set: { value in+            var current = choices.connections[id] ?? MergeConnectionChoices()+            current[keyPath: key] = value+            choices.connections[id] = current+            confirmed = false+        })+    }++    private func complete(_ preview: PersonMergePreview) -> Bool {+        preview.overlaps.allSatisfy {+            guard let selected = choices.connections[$0.id] else { return false }+            return selected.originID != nil && ($0.closeness.isEmpty || selected.closenessID != nil) &&+                ($0.statuses.isEmpty || selected.statusID != nil)+        }+    }++    private func prepare() {+        guard let survivorID else { return }+        do {+            preview = try repository.mergePreview(sourceID: sourceID, survivorID: survivorID)+            choices = PersonMergeChoices(); confirmed = false+        } catch { preview = nil; failure = error.localizedDescription }+    }++    private func sensitiveLabel(_ value: SensitiveSnapshot) -> String {+        value.isDeceased ? "Deceased" + (value.date.label.isEmpty ? "" : " · " + value.date.label) : "Not marked deceased"+    }++    private func referenceLabel(_ entity: String) -> String {+        switch entity {+        case "Connection": "Child relationships"+        case "ChildProfile": "Our child profiles"+        case "ContextPerson": "Roles in contexts"+        case "PersonRelationship": "Family facts"+        case "RelationshipAssertion": "Entered family descriptions"+        case "AddressLabel": "Address labels"+        case "GroupMembership": "Group memberships"+        case "EventPerson": "Event participation accounts"+        case "Event": "Event subjects"+        case "GiftRecord": "Gifts"+        case "Asset": "Photos"+        default: "Other references"+        }+    }+}
Halo Family/Halo Family/PhotoAssetViews.swift Added +192 / -0
diff --git a/Halo Family/Halo Family/PhotoAssetViews.swift b/Halo Family/Halo Family/PhotoAssetViews.swiftnew file mode 100644index 0000000..aa166b4--- /dev/null+++ b/Halo Family/Halo Family/PhotoAssetViews.swift	@@ -0,0 +1,192 @@+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. Bound the bytes read even if the file changes.+            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 handle = try FileHandle(forReadingFrom: url)+        defer { try? handle.close() }+        var data = Data()+        while true {+            try Task.checkCancellation()+            let remaining = ImageImport.attachmentLimit + 1 - data.count+            guard let chunk = try handle.read(upToCount: min(65_536, remaining)), !chunk.isEmpty else { break }+            data.append(chunk)+            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)+    }+}
Halo Family/Halo Family/ShareInvitations.swift Added +69 / -0
diff --git a/Halo Family/Halo Family/ShareInvitations.swift b/Halo Family/Halo Family/ShareInvitations.swiftnew file mode 100644index 0000000..c83fcd7--- /dev/null+++ b/Halo Family/Halo Family/ShareInvitations.swift	@@ -0,0 +1,69 @@+import CloudKit+import Observation+import SwiftUI++@MainActor+@Observable+final class ShareInvitations {+    static let shared = ShareInvitations()+    private(set) var issue: String?+    private(set) var isAccepting = false+    private var pending: [CKShare.Metadata] = []++    func receive(_ metadata: CKShare.Metadata) {+        guard metadata.containerIdentifier == StoreConfiguration.cloudContainer else {+            issue = SharingError.wrongContainer.localizedDescription+            return+        }+        guard !pending.contains(where: { $0.share.recordID == metadata.share.recordID }) else { return }+        pending.append(metadata)+        Task { await retry() }+    }++    func retry() async {+        guard !isAccepting, !pending.isEmpty else { return }+        isAccepting = true+        defer { isAccepting = false }+        do {+            let sharing = FamilySharing(stack: try await .production())+            while let metadata = pending.first {+                try await sharing.accept(metadata)+                pending.removeFirst()+            }+            issue = nil+        } catch {+            issue = "Couldn’t accept the family invitation: \(error.localizedDescription)"+        }+    }+}++#if os(iOS)+import UIKit++final class HaloApplicationDelegate: NSObject, UIApplicationDelegate {+    func application(_ application: UIApplication, configurationForConnecting session: UISceneSession,+                     options: UIScene.ConnectionOptions) -> UISceneConfiguration {+        let configuration = UISceneConfiguration(name: session.configuration.name, sessionRole: session.role)+        configuration.delegateClass = HaloSceneDelegate.self+        return configuration+    }+}++final class HaloSceneDelegate: NSObject, UIWindowSceneDelegate {+    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) {+        if let metadata = options.cloudKitShareMetadata { ShareInvitations.shared.receive(metadata) }+    }++    func windowScene(_ windowScene: UIWindowScene, userDidAcceptCloudKitShareWith metadata: CKShare.Metadata) {+        ShareInvitations.shared.receive(metadata)+    }+}+#elseif os(macOS)+import AppKit++final class HaloApplicationDelegate: NSObject, NSApplicationDelegate {+    func application(_ application: NSApplication, userDidAcceptCloudKitShareWith metadata: CKShare.Metadata) {+        ShareInvitations.shared.receive(metadata)+    }+}+#endif
Halo Family/Halo Family/TemporalConflictReview.swift Added +41 / -0
diff --git a/Halo Family/Halo Family/TemporalConflictReview.swift b/Halo Family/Halo Family/TemporalConflictReview.swiftnew file mode 100644index 0000000..9d311fe--- /dev/null+++ b/Halo Family/Halo Family/TemporalConflictReview.swift	@@ -0,0 +1,41 @@+import CoreData+import SwiftUI++struct TemporalConflictReview: View {+    let repository: FamilyRepository+    let connectionID: NSManagedObjectID+    let closeness: Bool+    let resolved: () throws -> Void+    @State private var periods: [StatePeriodRow] = []+    @State private var failure: String?+    var body: some View {+        VStack(alignment: .leading, spacing: 12) {+            Text("Choose the current value. Every earlier account stays in the relationship history.").foregroundStyle(.secondary)+            ForEach(periods) { period in+                VStack(alignment: .leading, spacing: 4) {+                    let label = period.value.map { ClosenessChoice(rawValue: $0)?.label ?? "\($0) of 10" } ?? period.state?.label ?? "Not recorded"+                    Text(label).font(.headline)+                    if !period.note.isEmpty { Text(period.note) }+                    if let date = period.startedAt { Text(date, style: .date).font(.caption).foregroundStyle(.secondary) }+                    Button("Use this value") {+                        do {+                            let reviewed = Set(periods.map(\.id))+                            if let value = period.value {+                                try repository.resolveCloseness(value, connectionID: connectionID, reviewed: reviewed)+                            } else if let state = period.state {+                                try repository.resolveStatus(state, note: period.note, connectionID: connectionID, reviewed: reviewed)+                            }+                            try resolved()+                        } catch { failure = error.localizedDescription }+                    }+                }+            }+        }+        .task {+            do {+                periods = try repository.currentStatePeriods(connectionID, closeness: closeness)+            } catch { failure = error.localizedDescription }+        }+        .graphFailure($failure)+    }+}
Halo Family/Halo Family/WidgetCaptureSheet.swift Added +93 / -0
diff --git a/Halo Family/Halo Family/WidgetCaptureSheet.swift b/Halo Family/Halo Family/WidgetCaptureSheet.swiftnew file mode 100644index 0000000..1e69ec3--- /dev/null+++ b/Halo Family/Halo Family/WidgetCaptureSheet.swift	@@ -0,0 +1,93 @@+import Combine+import SwiftUI++struct WidgetCaptureSheet: View {+    let repository: FamilyRepository+    let route: CaptureRoute+    @Environment(\.dismiss) private var dismiss+    @State private var child: CaptureChoice?+    @State private var contexts: [CaptureChoice] = []+    @State private var selectedContext: String?+    @State private var name = ""+    @State private var failure: String?+    @State private var saving = false+    @FocusState private var nameFocused: Bool++    var body: some View {+        NavigationStack {+            MemoryForm {+                if let child {+                    MemorySection("For \(child.name)") {+                        Text(child.familyName).foregroundStyle(.secondary)+                        MemoryField("Name or description") {+                            TextField("Name or description", text: $name).focused($nameFocused)+                                .accessibilityIdentifier("widgetCapture.name")+                        }+                        MemoryField("Context") {+                            Picker("Context", selection: $selectedContext) {+                                Text("None").tag(nil as String?)+                                ForEach(contexts) { Text($0.name).tag(Optional($0.id)) }+                            }+                        }+                        Text("A name is enough. An optional Context records membership; you can add the first meeting later.")+                            .font(.caption).foregroundStyle(.secondary)+                    }+                } else {+                    Text("This child is unavailable. Verify your library access and choose a current child in the widget.")+                }+                if let failure { Text(failure).foregroundStyle(.red) }+            }+            .navigationTitle("Remember someone")+            .toolbar {+                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+                ToolbarItem(placement: .confirmationAction) {+                    Button("Save person", action: save)+                        .disabled(saving || child == nil || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+                        .accessibilityIdentifier("widgetCapture.save")+                }+            }+        }+        .task {+            selectedContext = route.context?.identifier+            reload()+            nameFocused = child != nil+        }+        .onReceive(NotificationCenter.default.publisher(for: .haloPersistenceDidRefresh, object: repository.stack.container)+            .receive(on: DispatchQueue.main)) { _ in reload() }+        #if os(macOS)+        .frame(minWidth: 480, minHeight: 350)+        #endif+    }++    private func reload() {+        do {+            let capture = CaptureRepository(graph: repository)+            let currentChild = try capture.child(route.child)+            let currentContexts = try capture.contexts(for: route.child)+            if let selectedContext, !currentContexts.contains(where: { $0.id == selectedContext }) {+                // Preserve the failed selection; never silently save without the requested membership.+                child = nil+                failure = "The selected Context is no longer available. Close this form and choose a current widget Context."+                return+            }+            child = currentChild+            contexts = currentContexts+            failure = nil+        } catch {+            child = nil+            contexts = []+            failure = error.localizedDescription+        }+    }++    private func save() {+        guard !saving else { return }+        saving = true+        do {+            let context = selectedContext.flatMap(CaptureReference.init(identifier:))+            guard selectedContext == nil || context != nil else { throw GraphError.invalidReference }+            _ = try CaptureRepository(graph: repository).capture(name: name, child: route.child, context: context)+            dismiss()+        } catch { saving = false; failure = error.localizedDescription }+    }+}
Halo Family/Halo-Family-Info.plist Modified +13 / -0
diff --git a/Halo Family/Halo-Family-Info.plist b/Halo Family/Halo-Family-Info.plistindex ca9a074..8e7d002 100644--- a/Halo Family/Halo-Family-Info.plist	+++ b/Halo Family/Halo-Family-Info.plist	@@ -2,6 +2,19 @@ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict>+    <key>CFBundleURLTypes</key>+    <array>+        <dict>+            <key>CFBundleURLName</key>+            <string>me.nore.ig.halo-family.capture</string>+            <key>CFBundleURLSchemes</key>+            <array><string>halo-family</string></array>+        </dict>+    </array>+    <key>NSContactsUsageDescription</key>+    <string>Link a person to an Apple Contact or save the contact names you choose. Family notes and photos stay in Halo.</string>+	<key>CKSharingSupported</key>+	<true/> 	<key>UIBackgroundModes</key> 	<array> 		<string>remote-notification</string>
Halo Family/HaloFamilyWidgets-Info.plist Added +11 / -0
diff --git a/Halo Family/HaloFamilyWidgets-Info.plist b/Halo Family/HaloFamilyWidgets-Info.plistnew file mode 100644index 0000000..250057e--- /dev/null+++ b/Halo Family/HaloFamilyWidgets-Info.plist	@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="UTF-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>NSExtension</key>+    <dict>+        <key>NSExtensionPointIdentifier</key>+        <string>com.apple.widgetkit-extension</string>+    </dict>+</dict>+</plist>
Halo Family/HaloFamilyWidgets.entitlements Added +14 / -0
diff --git a/Halo Family/HaloFamilyWidgets.entitlements b/Halo Family/HaloFamilyWidgets.entitlementsnew file mode 100644index 0000000..d15cb35--- /dev/null+++ b/Halo Family/HaloFamilyWidgets.entitlements	@@ -0,0 +1,14 @@+<?xml version="1.0" encoding="UTF-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>com.apple.security.network.client</key>+    <true/>+    <key>com.apple.developer.icloud-container-identifiers</key>+    <array><string>iCloud.me.nore.ig.halo-family</string></array>+    <key>com.apple.developer.icloud-services</key>+    <array><string>CloudKit</string></array>+    <key>com.apple.security.application-groups</key>+    <array><string>group.me.nore.ig.halo-family</string></array>+</dict>+</plist>
Halo Family/HaloWidgets/ChildCaptureWidget.swift Added +96 / -0
diff --git a/Halo Family/HaloWidgets/ChildCaptureWidget.swift b/Halo Family/HaloWidgets/ChildCaptureWidget.swiftnew file mode 100644index 0000000..3ae2c35--- /dev/null+++ b/Halo Family/HaloWidgets/ChildCaptureWidget.swift	@@ -0,0 +1,96 @@+import AppIntents+import SwiftUI+import WidgetKit++nonisolated struct CaptureWidgetEntry: TimelineEntry {+    let date: Date+    let child: CaptureChoice?+    let context: CaptureChoice?+    let message: String+    var route: CaptureRoute? { child.map { CaptureRoute(child: $0.reference, context: context?.reference) } }+}++nonisolated struct CaptureWidgetProvider: AppIntentTimelineProvider {+    func placeholder(in context: Context) -> CaptureWidgetEntry {+        CaptureWidgetEntry(date: .now, child: nil, context: nil, message: "Choose a child")+    }++    func snapshot(for configuration: ChildCaptureConfiguration, in context: Context) async -> CaptureWidgetEntry {+        if context.isPreview { return placeholder(in: context) }+        return await entry(for: configuration)+    }++    func timeline(for configuration: ChildCaptureConfiguration, in context: Context) async -> Timeline<CaptureWidgetEntry> {+        let entry = await entry(for: configuration)+        return Timeline(entries: [entry], policy: .after(Date.now.addingTimeInterval(900)))+    }++    @MainActor private func entry(for configuration: ChildCaptureConfiguration) async -> CaptureWidgetEntry {+        guard let selected = configuration.child, let reference = CaptureReference(identifier: selected.id) else {+            return CaptureWidgetEntry(date: .now, child: nil, context: nil, message: "Edit this widget to choose a child.")+        }+        do {+            let stack = try await CaptureCatalog.store(for: reference, role: .widget)+            let repository = CaptureRepository(graph: FamilyRepository(stack: stack))+            let child = try repository.child(reference)+            let context: CaptureChoice?+            if let selected = configuration.context {+                guard let contextRef = CaptureReference(identifier: selected.id),+                      contextRef.namespace == reference.namespace, contextRef.family == reference.family else {+                    throw GraphError.invalidReference+                }+                context = try repository.context(contextRef)+            } else { context = nil }+            try stack.access.check()+            return CaptureWidgetEntry(date: .now, child: child, context: context, message: "")+        } catch {+            return CaptureWidgetEntry(date: .now, child: nil, context: nil,+                                      message: "Open Halo Family to verify access, then choose a current child and context.")+        }+    }+}++struct ChildCaptureWidgetView: View {+    let entry: CaptureWidgetEntry++    var body: some View {+        if let child = entry.child, let url = entry.route?.url {+            Link(destination: url) {+                VStack(alignment: .leading, spacing: 8) {+                    Text(child.name).font(.headline)+                    Text(child.familyName).font(.caption).foregroundStyle(.secondary)+                    if let context = entry.context { Text(context.name).font(.caption).lineLimit(2) }+                    Spacer(minLength: 0)+                    Label("Remember someone", systemImage: "person.badge.plus").font(.callout.weight(.semibold))+                }.frame(maxWidth: .infinity, alignment: .leading)+            }.privacySensitive()+                .containerBackground(.fill.tertiary, for: .widget)+        } else {+            VStack(alignment: .leading, spacing: 8) {+                Label("Halo Family", systemImage: "person.2.circle").font(.headline)+                Text(entry.message).font(.caption).foregroundStyle(.secondary)+            }.frame(maxWidth: .infinity, alignment: .leading)+                .containerBackground(.fill.tertiary, for: .widget)+        }+    }+}++@main+struct HaloFamilyWidgets: WidgetBundle {+    var body: some Widget { ChildCaptureWidget() }+}++struct ChildCaptureWidget: Widget {+    let kind = "HaloFamily.ChildCapture"+    var body: some WidgetConfiguration {+        AppIntentConfiguration(kind: kind, intent: ChildCaptureConfiguration.self, provider: CaptureWidgetProvider()) { entry in+            ChildCaptureWidgetView(entry: entry)+        }+        .configurationDisplayName("Remember their people")+        .description("Open a small capture form for one child, with an optional default context.")+        .supportedFamilies([.systemSmall, .systemMedium])+        #if os(iOS)+        .disfavoredLocations([.standBy, .carPlay], for: [.systemSmall, .systemMedium])+        #endif+    }+}
Halo Family/SharedIntents/CaptureCatalog.swift Added +75 / -0
diff --git a/Halo Family/SharedIntents/CaptureCatalog.swift b/Halo Family/SharedIntents/CaptureCatalog.swiftnew file mode 100644index 0000000..ac378ac--- /dev/null+++ b/Halo Family/SharedIntents/CaptureCatalog.swift	@@ -0,0 +1,75 @@+import Foundation++@MainActor+enum CaptureCatalog {+    static func store(for reference: CaptureReference, role: PersistenceRole) async throws -> PersistenceStack {+        let stack: PersistenceStack+        if reference.namespace == "local" { stack = try await .deviceLibrary(role: role) } else {+            stack = try await .production(role: role)+        }+        guard stack.accountScope?.namespace == reference.namespace else { throw AccessError.accountChanged }+        return stack+    }++    static func children() async throws -> [CaptureChoice] {+        var choices: [CaptureChoice] = []+        for stack in try await readableStores() {+            let suffix = stack.accountScope == .local ? " · On this device" : " · iCloud"+            for choice in try CaptureRepository(graph: FamilyRepository(stack: stack)).children() {+                choices.append(CaptureChoice(reference: choice.reference, name: choice.name, familyName: choice.familyName + suffix))+            }+        }+        return choices.sorted {+            $0.familyName == $1.familyName ? $0.name.localizedStandardCompare($1.name) == .orderedAscending :+                $0.familyName.localizedStandardCompare($1.familyName) == .orderedAscending+        }+    }++    static func contexts(identifiers: [String]) async throws -> [CaptureChoice] {+        guard identifiers.count <= 128 else { throw GraphError.invalidReference }+        let wanted = Set(identifiers.compactMap(CaptureReference.init(identifier:)))+        var choices: [String: CaptureChoice] = [:]+        for stack in await requestedStores(wanted) {+            let repository = CaptureRepository(graph: FamilyRepository(stack: stack))+            for reference in wanted where reference.namespace == repository.namespace {+                // Saved selections resolve only requested identities; suggestions remain child-scoped.+                if let context = try? repository.context(reference) { choices[context.id] = context }+            }+        }+        return choices.values.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }+    }++    static func children(identifiers: [String]) async throws -> [CaptureChoice] {+        guard identifiers.count <= 128 else { throw GraphError.invalidReference }+        let wanted = Set(identifiers.compactMap(CaptureReference.init(identifier:)))+        var choices: [CaptureChoice] = []+        for stack in await requestedStores(wanted) {+            let repository = CaptureRepository(graph: FamilyRepository(stack: stack))+            for reference in wanted where reference.namespace == repository.namespace {+                if let child = try? repository.child(reference) { choices.append(child) }+            }+        }+        return choices.sorted { $0.id < $1.id }+    }++    private static func requestedStores(_ references: Set<CaptureReference>) async -> [PersistenceStack] {+        var stores: [PersistenceStack] = []+        if references.contains(where: { $0.namespace == "local" }), let local = try? await PersistenceStack.deviceLibrary(role: .widget) {+            stores.append(local)+        }+        if references.contains(where: { $0.namespace != "local" }), let account = try? await PersistenceStack.production(role: .widget),+           !stores.contains(where: { $0.accountScope == account.accountScope }) { stores.append(account) }+        return stores+    }++    private static func readableStores() async throws -> [PersistenceStack] {+        var stores: [PersistenceStack] = []+        var accountFailure: Error?+        do { stores.append(try await .production(role: .widget)) } catch { accountFailure = error }+        if !stores.contains(where: { $0.accountScope == .local }), let local = try? await PersistenceStack.deviceLibrary(role: .widget) {+            stores.append(local)+        }+        guard !stores.isEmpty else { throw accountFailure ?? PersistenceError.hostMustPrepareStores }+        return stores+    }+}
Halo Family/SharedIntents/CaptureIntents.swift Added +99 / -0
diff --git a/Halo Family/SharedIntents/CaptureIntents.swift b/Halo Family/SharedIntents/CaptureIntents.swiftnew file mode 100644index 0000000..0cff639--- /dev/null+++ b/Halo Family/SharedIntents/CaptureIntents.swift	@@ -0,0 +1,99 @@+import AppIntents+import Foundation+import WidgetKit++nonisolated struct CaptureChildEntity: AppEntity {+    static let persistentIdentifier = "HaloFamilyCaptureChild"+    static let typeDisplayRepresentation: TypeDisplayRepresentation = "Child"+    static let defaultQuery = CaptureChildQuery()+    let id: String+    let name: String+    let familyName: String+    var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(name)", subtitle: "\(familyName)") }+    init(_ choice: CaptureChoice) { id = choice.id; name = choice.name; familyName = choice.familyName }+}++nonisolated struct CaptureContextEntity: AppEntity {+    static let persistentIdentifier = "HaloFamilyCaptureContext"+    static let typeDisplayRepresentation: TypeDisplayRepresentation = "Context"+    static let defaultQuery = CaptureContextQuery()+    let id: String+    let name: String+    let familyName: String+    var displayRepresentation: DisplayRepresentation { DisplayRepresentation(title: "\(name)", subtitle: "\(familyName)") }+    init(_ choice: CaptureChoice) { id = choice.id; name = choice.name; familyName = choice.familyName }+}++nonisolated struct CaptureChildQuery: EntityQuery {+    static let persistentIdentifier = "HaloFamilyCaptureChildQuery"+    @MainActor func entities(for identifiers: [String]) async throws -> [CaptureChildEntity] {+        try await CaptureCatalog.children(identifiers: identifiers).map(CaptureChildEntity.init)+    }+    @MainActor func suggestedEntities() async throws -> [CaptureChildEntity] {+        try await CaptureCatalog.children().map(CaptureChildEntity.init)+    }+}++nonisolated struct CaptureContextQuery: EntityQuery {+    static let persistentIdentifier = "HaloFamilyCaptureContextQuery"+    @IntentParameterDependency<RememberPersonIntent>(\.$child) private var capture+    @IntentParameterDependency<ChildCaptureConfiguration>(\.$child) private var widget++    @MainActor func entities(for identifiers: [String]) async throws -> [CaptureContextEntity] {+        let wanted = Set(identifiers)+        return try await CaptureCatalog.contexts(identifiers: identifiers).filter { wanted.contains($0.id) }.map(CaptureContextEntity.init)+    }++    @MainActor func suggestedEntities() async throws -> [CaptureContextEntity] {+        guard let child = capture?.child ?? widget?.child, let reference = CaptureReference(identifier: child.id) else { return [] }+        let stack = try await CaptureCatalog.store(for: reference, role: .widget)+        return try CaptureRepository(graph: FamilyRepository(stack: stack)).contexts(for: reference).map(CaptureContextEntity.init)+    }+}++struct RememberPersonIntent: AppIntent {+    nonisolated static let persistentIdentifier = "HaloFamilyRememberPerson"+    nonisolated static let title: LocalizedStringResource = "Remember someone"+    nonisolated static let description = IntentDescription("Save a name or description for a child, with an optional context membership.")+    nonisolated static let authenticationPolicy: IntentAuthenticationPolicy = .requiresLocalDeviceAuthentication+    nonisolated static let openAppWhenRun = false+    nonisolated static let allowedExecutionTargets: IntentExecutionTargets = [.main, .widgetKitExtension]++    @Parameter(title: "Child") var child: CaptureChildEntity+    @Parameter(title: "Name or description") var name: String+    @Parameter(title: "Context", description: "Optional membership. This does not record the first meeting.")+    var context: CaptureContextEntity?++    nonisolated static var parameterSummary: some ParameterSummary {+        Summary("Remember \(\.$name) for \(\.$child)") { \.$context }+    }++    @MainActor func perform() async throws -> some IntentResult & ProvidesDialog {+        guard let child = CaptureReference(identifier: child.id) else { throw GraphError.invalidReference }+        let context: CaptureReference?+        if let selected = self.context {+            guard let reference = CaptureReference(identifier: selected.id) else { throw GraphError.invalidReference }+            context = reference+        } else { context = nil }+        let stack = try await CaptureCatalog.store(for: child, role: .appIntent)+        _ = try CaptureRepository(graph: FamilyRepository(stack: stack)).capture(name: name, child: child, context: context)+        WidgetCenter.shared.reloadTimelines(ofKind: "HaloFamily.ChildCapture")+        if child.namespace == "local" { return .result(dialog: "Saved in your device-only library.") }+        return .result(dialog: "Saved on this device. Open Halo Family to sync with iCloud.")+    }+}++struct ChildCaptureConfiguration: WidgetConfigurationIntent {+    nonisolated static let persistentIdentifier = "HaloFamilyChildCaptureWidget"+    nonisolated static let title: LocalizedStringResource = "Child capture"+    nonisolated static let description = IntentDescription("Choose a child and an optional default context for remembering people.")+    @Parameter(title: "Child") var child: CaptureChildEntity?+    @Parameter(title: "Default context") var context: CaptureContextEntity?+}++nonisolated struct HaloCaptureShortcuts: AppShortcutsProvider {+    static var appShortcuts: [AppShortcut] {+        AppShortcut(intent: RememberPersonIntent(), phrases: ["Remember someone in \(.applicationName)"],+                    shortTitle: "Remember someone", systemImageName: "person.badge.plus")+    }+}
Makefile Modified +2 / -1
diff --git a/Makefile b/Makefileindex 18dde14..b531e3e 100644--- a/Makefile+++ b/Makefile@@ -9,6 +9,7 @@ DERIVED_DATA ?= ./DerivedData IOS_DESTINATION ?= generic/platform=iOS Simulator MAC_DESTINATION ?= platform=macOS APP_NAME ?= Halo Family+TEST_FLAGS ?=  # Match paired devices even when their wireless tunnel is idle. Device names # and product types remain available when devicectl's marketingName is null.@@ -131,4 +132,4 @@ clean:  .PHONY: test test:-	swift test --scratch-path "$(DERIVED_DATA)/swift-tests"+	swift test --scratch-path "$(DERIVED_DATA)/swift-tests" $(TEST_FLAGS)
Tests/HaloPersistenceTests/AccountAccessTests.swift Added +311 / -0
diff --git a/Tests/HaloPersistenceTests/AccountAccessTests.swift b/Tests/HaloPersistenceTests/AccountAccessTests.swiftnew file mode 100644index 0000000..19e0484--- /dev/null+++ b/Tests/HaloPersistenceTests/AccountAccessTests.swift@@ -0,0 +1,311 @@+import CloudKit+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct AccountAccessTests {+    private func directory() -> URL {+        FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)+    }++    @Test func scopeHashesIdentityAndSeparatesCloudEnvironments() throws {+        let first = try AccountScope.verifiedCloud(userRecordName: "synthetic-owner-a", environment: "development")+        let same = try AccountScope.verifiedCloud(userRecordName: "synthetic-owner-a", environment: "development")+        let other = try AccountScope.verifiedCloud(userRecordName: "synthetic-owner-b", environment: "development")+        let release = try AccountScope.verifiedCloud(userRecordName: "synthetic-owner-a", environment: "production")+        #expect(first == same)+        #expect(first != other && first != release && first != .local)+        #expect(!first.namespace.contains("synthetic-owner"))+        #expect(first.namespace.count == 72)+        #expect(throws: AccessError.self) { try AccountScope.verifiedCloud(userRecordName: "") }+    }++    @Test func localAndAccountDirectoriesPreserveUnscopedFiles() throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+        let old = root.appendingPathComponent("Private.sqlite")+        let bytes = Data("unscoped synthetic sentinel".utf8)+        try bytes.write(to: old)+        let cloud = try AccountScope.verifiedCloud(userRecordName: "synthetic-owner")+        #expect(AccountScope.local.directory(in: root) != cloud.directory(in: root))+        #expect(!FileManager.default.fileExists(atPath: cloud.directory(in: root).path))+        #expect(try Data(contentsOf: old) == bytes)+        let local = StoreConfiguration(directory: AccountScope.local.directory(in: root), role: .host,+                                       mirrorsCloud: AccountScope.local.mirrorsCloud, accountScope: .local)+        #expect(local.descriptions().allSatisfy { $0.cloudKitContainerOptions == nil })+    }++    @Test func permissionsFilterListsAndRejectDirectReferences() throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        let stack = try PersistenceStack(directory: root)+        let graph = FamilyRepository(stack: stack)+        let allowed = try graph.createFamily(name: "Visible")+        let hidden = try graph.createFamily(name: "Locked")+        let child = try graph.addChild(name: "Synthetic child", familyID: hidden)+        let person = try graph.personID(for: graph.quickCapture(name: "Synthetic peer", childID: child))+        let id = try #require(stack.container.viewContext.existingObject(with: allowed).value(forKey: "id") as? UUID)+        stack.access.update(readable: [.init(family: id, shared: false)], writable: [.init(family: id, shared: false)])+        #expect(try graph.families().map(\.name) == ["Visible"])+        #expect(try graph.children(in: hidden).isEmpty)+        #expect(throws: AccessError.self) { try graph.person(person) }+        #expect(throws: AccessError.self) { try graph.quickCapture(name: "Denied", childID: child) }+    }++    @Test func readOnlyAllowsReadingButRejectsEveryChangedRow() throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        let stack = try PersistenceStack(directory: root)+        let graph = FamilyRepository(stack: stack)+        let family = try graph.createFamily(name: "Read only")+        let child = try graph.addChild(name: "Synthetic child", familyID: family)+        let id = try #require(stack.container.viewContext.existingObject(with: family).value(forKey: "id") as? UUID)+        stack.access.update(readable: [.init(family: id, shared: false)], writable: [])+        #expect(try graph.children(in: family).count == 1)+        #expect(throws: AccessError.self) { try graph.quickCapture(name: "Denied", childID: child) }+        #expect(throws: AccessError.self) {+            try graph.write { context in+                let root = try context.existingObject(with: family)+                root.setValue("Bypass attempt", forKey: "name")+                return root+            }+        }+        #expect(try graph.families().first?.name == "Read only")+    }++    @Test func invalidationAtSaveBoundaryDiscardsOnlyTheOperation() throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        let stack = try PersistenceStack(directory: root)+        let graph = FamilyRepository(stack: stack)+        let family = try graph.createFamily(name: "Preserved")+        #expect(throws: AccessError.self) {+            try graph.write { context in+                let object = try context.existingObject(with: family)+                object.setValue("Must not save", forKey: "name")+                stack.access.invalidate()+                return object+            }+        }+        let reopened = try PersistenceStack(directory: root)+        #expect(try FamilyRepository(stack: reopened).families().first?.name == "Preserved")+        #expect(throws: AccessError.self) { try graph.families() }+    }++    @Test func extensionManifestRejectsWrongAccountAndPropagatesRevocation() throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+        let family = UUID()+        let identity = FamilyAccessID(family: family, shared: false)+        let value = ExtensionAccess(version: 1, namespace: "synthetic-a", readable: [identity], writable: [identity], locked: false)+        try value.save(in: root)+        let access = StoreAccess()+        access.watchExtensionAccess(directory: root, namespace: "synthetic-a")+        try access.check(family: family, writing: true)+        #expect(throws: AccessError.self) { try ExtensionAccess.read(in: root, namespace: "synthetic-b") }+        try ExtensionAccess(version: 1, namespace: "synthetic-a", readable: [identity], writable: [], locked: false).save(in: root)+        try access.check(family: family)+        #expect(throws: AccessError.self) { try access.check(family: family, writing: true) }+        try Data().write(to: root.appendingPathComponent("AccessLocked"), options: .atomic)+        #expect(throws: AccessError.self) { try access.check(family: family) }+    }++    @Test func extensionManifestFailsClosedForInvalidAndOversizedData() throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+        let file = root.appendingPathComponent("ExtensionAccess.json")+        try Data("invalid".utf8).write(to: file)+        #expect(throws: AccessError.self) { try ExtensionAccess.read(in: root, namespace: "test") }+        try Data(repeating: 0, count: 1_000_001).write(to: file)+        #expect(throws: AccessError.self) { try ExtensionAccess.read(in: root, namespace: "test") }+        let invalid = ExtensionAccess(version: 1, namespace: "test", readable: [],+                                      writable: [.init(family: UUID(), shared: false)], locked: false)+        try invalid.save(in: root)+        #expect(throws: AccessError.self) { try ExtensionAccess.read(in: root, namespace: "test") }+    }++    @Test func lockedAssetsAndExportCannotReadSavedPayloads() async throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        let stack = try PersistenceStack(directory: root)+        let graph = FamilyRepository(stack: stack)+        let family = try graph.createFamily(name: "Synthetic")+        let assets = AssetRepository(stack: stack)+        let asset = try await assets.save(data: Data("synthetic payload".utf8), familyID: family)+        stack.access.invalidate()+        await #expect(throws: AccessError.self) { try await assets.data(for: asset) }+        await #expect(throws: AccessError.self) { try await assets.revision(for: asset) }+        await #expect(throws: AccessError.self) { try await BackupRepository(stack: stack).export(familyID: family) }+        await #expect(throws: AccessError.self) { try await assets.save(data: Data(), familyID: family) }+    }++    @Test func shareDenialsPersistExactShareAndClassifyWrappedRevocation() throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)+        let first = CKRecord.ID(recordName: "synthetic-share-a", zoneID: .init(zoneName: "zone", ownerName: "owner"))+        let other = CKRecord.ID(recordName: "synthetic-share-b", zoneID: first.zoneID)+        var value = ShareDenials()+        value.shares.insert(ShareDenials.key(first))+        try value.save(in: root)+        #expect(try ShareDenials.read(in: root).shares.contains(ShareDenials.key(first)))+        #expect(try !ShareDenials.read(in: root).shares.contains(ShareDenials.key(other)))+        let denied = NSError(domain: CKErrorDomain, code: CKError.permissionFailure.rawValue)+        let wrapped = NSError(domain: NSCocoaErrorDomain, code: 1, userInfo: [NSUnderlyingErrorKey: denied])+        #expect(CloudAccessFailure.removesAccess(wrapped))+        #expect(!CloudAccessFailure.removesAccess(NSError(domain: CKErrorDomain, code: CKError.networkUnavailable.rawValue)))+    }++    @Test func privateGrantCannotAuthorizeSharedRootWithTheSameUUID() throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        let stack = try PersistenceStack(directory: root)+        let graph = FamilyRepository(stack: stack)+        let privateID = try graph.createFamily(name: "Private original")+        let context = stack.container.viewContext+        let uuid = try #require(context.existingObject(with: privateID).value(forKey: "id") as? UUID)+        let shared = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+        context.assign(shared, to: stack.sharedStore)+        shared.setValue(uuid, forKey: "id")+        shared.setValue("Shared original", forKey: "name")+        try context.save()+        let child = try graph.addChild(name: "Synthetic child", familyID: shared.objectID)+        let privateKey = FamilyAccessID(family: uuid, shared: false)+        let sharedKey = FamilyAccessID(family: uuid, shared: true)+        stack.access.update(readable: [privateKey], writable: [privateKey])+        #expect(try graph.families().map(\.name) == ["Private original"])+        #expect(throws: AccessError.self) { try graph.readable(shared.objectID, entity: "FamilySpace") }+        stack.access.update(readable: [privateKey, sharedKey], writable: [privateKey])+        #expect(try graph.families().count == 2)+        #expect(throws: AccessError.self) { try graph.quickCapture(name: "Denied", childID: child) }+        #expect(try graph.addChild(name: "Allowed", familyID: privateID).persistentStore == stack.privateStore)+    }++    @Test func batchStateReadsRetainStoreQualifiedDenialsAndRejectAmbiguousOrForeignIDs() throws {+        let root = directory()+        let foreignRoot = directory()+        defer {+            try? FileManager.default.removeItem(at: root)+            try? FileManager.default.removeItem(at: foreignRoot)+        }+        let stack = try PersistenceStack(directory: root)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        let graph = FamilyRepository(stack: stack)+        let privateID = try graph.createFamily(name: "Synthetic private family")+        let child = try graph.addChild(name: "Synthetic child", familyID: privateID)+        let first = try graph.quickCapture(name: "Synthetic first peer", childID: child)+        let second = try graph.quickCapture(name: "Synthetic second peer", childID: child)+        let context = stack.container.viewContext+        let uuid = try #require(context.existingObject(with: privateID).value(forKey: "id") as? UUID)+        let shared = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+        context.assign(shared, to: stack.sharedStore)+        shared.setValue(uuid, forKey: "id")+        shared.setValue("Synthetic shared family", forKey: "name")+        try context.save()+        let sharedChild = try graph.addChild(name: "Synthetic shared child", familyID: shared.objectID)+        let sharedConnection = try graph.quickCapture(name: "Synthetic shared peer", childID: sharedChild)+        let privateKey = FamilyAccessID(family: uuid, shared: false)+        let sharedKey = FamilyAccessID(family: uuid, shared: true)+        stack.access.update(readable: [privateKey], writable: [privateKey])+        #expect(throws: AccessError.self) { try graph.connectionStates([first, second, sharedConnection]) }+        stack.access.update(readable: [privateKey, sharedKey], writable: [privateKey])+        let all = try graph.connectionStates([first, second, sharedConnection, first])+        #expect(Set(all.keys) == Set([first, second, sharedConnection]))+        let duplicate = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+        context.assign(duplicate, to: stack.sharedStore)+        duplicate.setValue(uuid, forKey: "id")+        duplicate.setValue("Synthetic ambiguous share", forKey: "name")+        try context.save()+        #expect(throws: AccessError.self) { try graph.connectionStates([first, second, sharedConnection]) }+        let unaffected = try graph.connectionStates([first, second])+        #expect(Set(unaffected.keys) == Set([first, second]))+        let foreign = FamilyRepository(stack: try PersistenceStack(directory: foreignRoot))+        foreign.stack.container.viewContext.automaticallyMergesChangesFromParent = false+        let foreignFamily = try foreign.createFamily(name: "Synthetic foreign family")+        let foreignChild = try foreign.addChild(name: "Synthetic foreign child", familyID: foreignFamily)+        let foreignConnection = try foreign.quickCapture(name: "Synthetic foreign peer", childID: foreignChild)+        #expect(throws: GraphError.self) { try graph.connectionStates([first, foreignConnection]) }+    }++    @Test func invalidatedOpeningSignalStopsBeforeCreatingStores() async throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        let access = StoreAccess()+        access.invalidate()+        await #expect(throws: AccessError.self) {+            try await PersistenceStack.open(configuration: StoreConfiguration(directory: root, role: .host, mirrorsCloud: false),+                                            access: access)+        }+        #expect(!FileManager.default.fileExists(atPath: root.path))+    }++    @Test func ambiguousSharedRootsCannotUseOneAnothersGrant() throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        let stack = try PersistenceStack(directory: root)+        let graph = FamilyRepository(stack: stack)+        let privateID = try graph.createFamily(name: "Unaffected private family")+        let context = stack.container.viewContext+        let privateUUID = try #require(context.existingObject(with: privateID).value(forKey: "id") as? UUID)+        let sharedUUID = UUID()+        var roots: [NSManagedObject] = []+        for name in ["Revoked share", "Allowed share"] {+            let family = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+            context.assign(family, to: stack.sharedStore)+            family.setValue(sharedUUID, forKey: "id")+            family.setValue(name, forKey: "name")+            roots.append(family)+        }+        try context.save()+        let privateKey = FamilyAccessID(family: privateUUID, shared: false)+        let sharedKey = FamilyAccessID(family: sharedUUID, shared: true)+        stack.access.update(readable: [privateKey, sharedKey], writable: [privateKey, sharedKey])+        #expect(try graph.families().map(\.name) == ["Unaffected private family"])+        for family in roots {+            #expect(throws: AccessError.self) { try graph.readable(family.objectID, entity: "FamilySpace") }+            #expect(throws: AccessError.self) { try graph.addChild(name: "Denied", familyID: family.objectID) }+        }+        #expect(try graph.addChild(name: "Allowed", familyID: privateID).persistentStore == stack.privateStore)+    }++    @Test func repeatedTeardownCannotRelockAReopenedNamespace() async throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        let stack = try await PersistenceStack.open(+            configuration: StoreConfiguration(directory: root, role: .host, mirrorsCloud: false, accountScope: .local)+        )+        _ = try FamilyRepository(stack: stack).createFamily(name: "Retained")+        stack.lockSession()+        let marker = root.appendingPathComponent("AccessLocked")+        #expect(FileManager.default.fileExists(atPath: marker.path))+        try FileManager.default.removeItem(at: marker)+        stack.lockSession()+        #expect(!FileManager.default.fileExists(atPath: marker.path))+        let reopened = try PersistenceStack(directory: root)+        #expect(try FamilyRepository(stack: reopened).families().first?.name == "Retained")+    }++    @Test func explicitReinvitationClearsOnlyItsDenialWithoutCachedReinsertion() async throws {+        let root = directory()+        defer { try? FileManager.default.removeItem(at: root) }+        let stack = try await PersistenceStack.open(+            configuration: StoreConfiguration(directory: root, role: .host, mirrorsCloud: false, accountScope: .local)+        )+        let first = CKRecord.ID(recordName: "synthetic-reinvited")+        let other = CKRecord.ID(recordName: "synthetic-still-revoked")+        let firstKey = ShareDenials.key(first), otherKey = ShareDenials.key(other)+        var value = ShareDenials()+        value.shares = [firstKey, otherKey]+        value.permissions[firstKey] = false+        try value.save(in: root)+        try stack.didAcceptInvitation(first)+        try stack.refreshAccess()+        let retained = try ShareDenials.read(in: root)+        #expect(retained.shares == [otherKey])+        #expect(retained.permissions[firstKey] == nil)+    }+}
Tests/HaloPersistenceTests/ApprovedDefaultsTests.swift Added +327 / -0
diff --git a/Tests/HaloPersistenceTests/ApprovedDefaultsTests.swift b/Tests/HaloPersistenceTests/ApprovedDefaultsTests.swiftnew file mode 100644index 0000000..4c97947--- /dev/null+++ b/Tests/HaloPersistenceTests/ApprovedDefaultsTests.swift@@ -0,0 +1,327 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct ApprovedDefaultsTests {+    private func withConnection(_ test: (PersistenceStack, FamilyRepository, NSManagedObjectID, NSManagedObjectID) throws -> Void) throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let stack = try PersistenceStack(directory: directory)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        let graph = FamilyRepository(stack: stack)+        let family = try graph.createFamily(name: "Synthetic family")+        let child = try graph.addChild(name: "Child", familyID: family)+        let connection = try graph.quickCapture(name: "Friend", childID: child)+        try test(stack, graph, family, connection)+    }++    /// Models an imported immutable proposal made by another offline observer of this predecessor.+    /// This is a causal branch fixture, not live CloudKit transport evidence.+    private func importedProposal(stack: PersistenceStack, connectionID: NSManagedObjectID, predecessor: NSManagedObjectID,+                                  narrative: String, cleared: Bool = false) throws -> NSManagedObjectID {+        let context = stack.container.viewContext+        let connection = try context.existingObject(with: connectionID)+        let family = try #require(connection.value(forKey: "familySpace") as? NSManagedObject)+        let parent = try context.existingObject(with: predecessor)+        let proposal = NSEntityDescription.insertNewObject(forEntityName: "OriginProposal", into: context)+        context.assign(proposal, to: try #require(family.objectID.persistentStore))+        proposal.setValue(UUID(), forKey: "id")+        proposal.setValue(family, forKey: "familySpace")+        proposal.setValue(connection, forKey: "connection")+        proposal.setValue(narrative, forKey: "narrative")+        proposal.setValue(cleared, forKey: "isCleared")+        proposal.setValue(Date(timeIntervalSince1970: 1), forKey: "createdAt")+        proposal.setValue(Set([parent]), forKey: "predecessors")+        try context.save()+        return proposal.objectID+    }++    @Test func simultaneousFirstOriginAccountsRemainSeparateWithoutAPredecessor() throws {+        try withConnection { stack, graph, _, connection in+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Birthday"), expectedOrigin: nil)+            let first = try #require(try graph.originHistory(for: connection).first)+            let second = try importedProposal(stack: stack, connectionID: connection, predecessor: first.id, narrative: "Swimming")+            let object = try stack.container.viewContext.existingObject(with: second)+            object.setValue(Set<NSManagedObject>(), forKey: "predecessors")+            try stack.container.viewContext.save()+            let conflicts = try graph.originOverview(for: connection)+            #expect(Set(conflicts.conflicts.map(\.narrative)) == ["Birthday", "Swimming"])+            try graph.resolveOrigin(connectionID: connection, choosing: second, expectedHeads: conflicts.headIDs)+            #expect(try graph.origin(for: connection)?.narrative == "Swimming")+            #expect(try graph.originHistory(for: connection).count == 3)+        }+    }++    @Test func contextMembershipRowsKeepChildIdentityAndHistoryForOneSharedPerson() throws {+        try withConnection { _, graph, family, connection in+            let person = try graph.personID(for: connection)+            let sibling = try graph.addChild(name: "Sibling", familyID: family)+            let second = try graph.connect(personID: person, childID: sibling)+            let source = try graph.createContext(name: "Swimming", familyID: family)+            let old = try graph.addMembership(connectionID: connection, contextID: source)+            _ = try graph.addMembership(connectionID: second, contextID: source)+            try graph.endMembership(old, at: Date())+            let rows = try graph.contextConnections(source)+            #expect(Set(rows.map(\.childName)) == ["Child", "Sibling"])+            #expect(Set(rows.map(\.connectionID)) == [connection, second])+            #expect(rows.first(where: { $0.connectionID == connection })?.endedAt != nil)+            #expect(rows.first(where: { $0.connectionID == second })?.endedAt == nil)+        }+    }++    @Test func reviewQueriesAreFamilyScopedAndOriginResolutionClearsTheItem() throws {+        try withConnection { stack, graph, family, connection in+            let otherFamily = try graph.createFamily(name: "Other synthetic family")+            let child = try graph.addChild(name: "Other child", familyID: otherFamily)+            let otherConnection = try graph.quickCapture(name: "Other friend", childID: child)+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Birthday"), expectedOrigin: nil)+            let first = try #require(try graph.originHistory(for: connection).first)+            let second = try importedProposal(stack: stack, connectionID: connection, predecessor: first.id, narrative: "Swimming")+            let object = try stack.container.viewContext.existingObject(with: second)+            object.setValue(Set<NSManagedObject>(), forKey: "predecessors")+            try stack.container.viewContext.save()+            let items = try graph.reviewConnections(in: family)+            #expect(items.map(\.id) == [connection])+            #expect(items.first?.childName == "Child")+            #expect(items.first?.originNeedsReview == true)+            #expect(try graph.reviewConnections(in: otherFamily).isEmpty)+            try graph.setCloseness(.friend, connectionID: connection, expectedID: nil)+            try graph.setCloseness(.bff, connectionID: otherConnection, expectedID: nil)+            let batch = try graph.connectionStates([connection, connection, otherConnection])+            #expect(batch.count == 2)+            #expect(batch[connection]?.closeness == .friend)+            #expect(batch[otherConnection]?.closeness == .bff)+            let heads = try graph.originOverview(for: connection).headIDs+            try graph.resolveOrigin(connectionID: connection, choosing: second, expectedHeads: heads)+            #expect(try graph.reviewConnections(in: family).isEmpty)+        }+    }++    @Test func competingOriginsNeedReviewAndResolutionRetainsEveryAlternative() throws {+        try withConnection { stack, graph, _, connection in+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Original meeting"), expectedOrigin: nil)+            let root = try #require(try graph.originHistory(for: connection).first)+            let initial = try #require(try graph.origin(for: connection))+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Birthday"), expectedOrigin: initial)+            let swimming = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Swimming")+            let conflicts = try graph.originOverview(for: connection)+            #expect(Set(conflicts.conflicts.map(\.narrative)) == ["Birthday", "Swimming"])+            #expect(conflicts.origin == nil)+            #expect(throws: GraphError.self) { try graph.origin(for: connection) }+            #expect(throws: GraphError.self) {+                try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Overwrite"), expectedOrigin: nil)+            }+            try graph.resolveOrigin(connectionID: connection, choosing: swimming, expectedHeads: conflicts.headIDs)+            #expect(try graph.origin(for: connection)?.narrative == "Swimming")+            #expect(try graph.originOverview(for: connection).conflicts.isEmpty)+            let history = try graph.originHistory(for: connection)+            #expect(history.count == 4)+            #expect(Set(history.map(\.narrative)) == ["Original meeting", "Birthday", "Swimming"])+            #expect(Set(history.map(\.stableID)).count == 4)+        }+    }++    @Test func clearCompetingWithEditAndLateArrivalRemainReviewable() throws {+        try withConnection { stack, graph, _, connection in+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Playground"), expectedOrigin: nil)+            let original = try #require(try graph.origin(for: connection))+            let root = try #require(try graph.originHistory(for: connection).first)+            try graph.clearOrigin(connectionID: connection, expectedOrigin: original)+            #expect(try graph.origin(for: connection) == nil)+            _ = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Party")+            let conflicts = try graph.originOverview(for: connection)+            let clear = try #require(conflicts.conflicts.first(where: { $0.isCleared }))+            try graph.resolveOrigin(connectionID: connection, choosing: clear.id, expectedHeads: conflicts.headIDs)+            #expect(try graph.origin(for: connection) == nil)+            _ = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Late swimming account")+            #expect(try graph.originOverview(for: connection).conflicts.count == 2)+            #expect(try graph.originHistory(for: connection).count == 5)+        }+    }++    @Test func staleResolutionDoesNotConsumeANewlyArrivedAccount() throws {+        try withConnection { stack, graph, _, connection in+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Original"), expectedOrigin: nil)+            let root = try #require(try graph.originHistory(for: connection).first)+            let original = try #require(try graph.origin(for: connection))+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Birthday"), expectedOrigin: original)+            let first = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Swimming")+            let old = try graph.originOverview(for: connection)+            _ = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "School")+            #expect(throws: GraphError.self) {+                try graph.resolveOrigin(connectionID: connection, choosing: first, expectedHeads: old.headIDs)+            }+            #expect(try graph.originOverview(for: connection).conflicts.count == 3)+            #expect(try graph.originHistory(for: connection).count == 4)+        }+    }++    @Test func aBlankEditorCannotAcknowledgeAnUnseenClear() throws {+        try withConnection { _, graph, _, connection in+            let blank = try graph.originOverview(for: connection)+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Meeting"), expectedOrigin: nil)+            try graph.clearOrigin(connectionID: connection, expectedOrigin: #require(try graph.origin(for: connection)))+            #expect(throws: GraphError.self) {+                try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Stale draft"),+                                     expectedOrigin: nil, expectedHeads: blank.headIDs)+            }+            let reopened = try graph.originOverview(for: connection)+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "New account"),+                                 expectedOrigin: nil, expectedHeads: reopened.headIDs)+            #expect(try graph.origin(for: connection)?.narrative == "New account")+            #expect(try graph.originHistory(for: connection).count == 3)+        }+    }++    @Test func malformedImportedHistoryIsPreservedWithoutInventingValues() throws {+        try withConnection { stack, graph, _, connection in+            try graph.setCloseness(.friend, connectionID: connection, expectedID: nil)+            let id = try #require(try graph.connectionState(connection).closenessID)+            let period = try stack.container.viewContext.existingObject(with: id)+            period.setValue(Int16(0), forKey: "value")+            try stack.container.viewContext.save()+            #expect(throws: GraphError.self) { try graph.connectionState(connection) }+            #expect((period.value(forKey: "value") as? NSNumber)?.int16Value == 0)+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Meeting"), expectedOrigin: nil)+            let proposal = try #require(try graph.originHistory(for: connection).first)+            let object = try stack.container.viewContext.existingObject(with: proposal.id)+            object.setValue(Set([object]), forKey: "predecessors")+            try stack.container.viewContext.save()+            #expect(throws: GraphError.self) { try graph.originOverview(for: connection) }+            #expect(try stack.container.viewContext.count(for: NSFetchRequest<NSManagedObject>(entityName: "OriginProposal")) == 1)+        }+    }++    @Test func aCycleAlongsideAValidHeadCannotBeDisplayedAsAnUnambiguousOrigin() throws {+        try withConnection { stack, graph, _, connection in+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Root"), expectedOrigin: nil)+            let root = try #require(try graph.originHistory(for: connection).first)+            let second = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Second")+            let third = try importedProposal(stack: stack, connectionID: connection, predecessor: root.id, narrative: "Valid head")+            let context = stack.container.viewContext+            let firstObject = try context.existingObject(with: root.id)+            let secondObject = try context.existingObject(with: second)+            firstObject.setValue(Set([secondObject]), forKey: "predecessors")+            try context.save()+            #expect(throws: GraphError.self) { try graph.originOverview(for: connection) }+            #expect(try context.existingObject(with: third).value(forKey: "narrative") as? String == "Valid head")+            #expect(try context.count(for: NSFetchRequest<NSManagedObject>(entityName: "OriginProposal")) == 3)+        }+    }++    @Test func closenessOnlyCreatesHistoryForExplicitValueChanges() throws {+        try withConnection { stack, graph, _, connection in+            #expect(ClosenessChoice.allCases.map(\.rawValue) == [1, 3, 5, 7, 10])+            #expect(ClosenessChoice(rawValue: 0) == nil)+            #expect(try graph.connectionState(connection).closeness == nil)+            for value: Int16 in [0, 11] {+                #expect(throws: GraphError.self) { try graph.setClosenessValue(value, connectionID: connection, expectedID: nil) }+            }+            try graph.setCloseness(.friend, connectionID: connection, expectedID: nil)+            let first = try graph.connectionState(connection)+            try graph.setCloseness(.friend, connectionID: connection, expectedID: first.closenessID)+            let request = NSFetchRequest<NSManagedObject>(entityName: "ConnectionClosenessPeriod")+            #expect(try stack.container.viewContext.count(for: request) == 1)+            try graph.setCloseness(.goodFriend, connectionID: connection, expectedID: first.closenessID)+            let second = try graph.connectionState(connection)+            try graph.setCloseness(.bff, connectionID: connection, expectedID: second.closenessID)+            #expect(throws: GraphError.self) { try graph.setCloseness(.metOnce, connectionID: connection, expectedID: first.closenessID) }+            let history = try stack.container.viewContext.fetch(request)+            #expect(Set(history.compactMap { ($0.value(forKey: "value") as? NSNumber)?.int16Value }) == [5, 7, 10])+            #expect(history.filter { $0.value(forKey: "endedAt") == nil }.count == 1)+            #expect(try graph.connectionState(connection).closeness == .bff)+            #expect(history.allSatisfy { $0.objectID.persistentStore == connection.persistentStore })+        }+    }++    @Test func numericClosenessDomainPreservesValuesBetweenTheFiveUIPositions() throws {+        try withConnection { _, graph, _, connection in+            try graph.setClosenessValue(2, connectionID: connection, expectedID: nil)+            let snapshot = try graph.connectionState(connection)+            #expect(snapshot.closenessValue == 2)+            #expect(snapshot.closeness == nil)+            #expect(!snapshot.closenessNeedsReview)+        }+    }++    @Test func lostContactAndReconnectPreserveConnectionPersonAndCloseness() throws {+        try withConnection { stack, graph, _, connection in+            let person = try graph.personID(for: connection)+            try graph.setCloseness(.goodFriend, connectionID: connection, expectedID: nil)+            try graph.setConnectionState(.lostContact, note: "Moved away", connectionID: connection, expectedID: nil)+            let lost = try graph.connectionState(connection)+            #expect(lost.state == .lostContact)+            #expect(lost.note == "Moved away")+            try graph.setConnectionState(.active, note: "Reconnected", connectionID: connection, expectedID: lost.statusID)+            #expect(try graph.personID(for: connection) == person)+            #expect(try graph.connectionState(connection).closeness == .goodFriend)+            #expect(try graph.connectionState(connection).state == .active)+            let periods = try stack.container.viewContext.fetch(NSFetchRequest<NSManagedObject>(entityName: "ConnectionStatusPeriod"))+            #expect(periods.count == 2)+            #expect(periods.filter { $0.value(forKey: "endedAt") == nil }.count == 1)+        }+    }++    @Test func multipleCustomDatedRolesReusePersonAndRejectInvalidRange() throws {+        try withConnection { _, graph, family, connection in+            let source = try graph.createContext(name: "Swimming", familyID: family)+            let adult = try graph.addPerson(name: "Adult", familyID: family)+            let start = Date(timeIntervalSince1970: 10)+            let end = Date(timeIntervalSince1970: 20)+            let teacher = try graph.associatePerson(adult, contextID: source, role: "Teacher", startedAt: start, endedAt: end)+            let repeated = try graph.associatePerson(adult, contextID: source, role: "Teacher", startedAt: start, endedAt: end)+            _ = try graph.associatePerson(adult, contextID: source, role: "Coach")+            #expect(teacher == repeated)+            #expect(throws: GraphError.self) {+                try graph.associatePerson(adult, contextID: source, role: "Invalid", startedAt: end, endedAt: start)+            }+            try graph.archiveContext(source, archived: true)+            let roles = try graph.contextPeople(source)+            #expect(Set(roles.map(\.role)) == ["Teacher", "Coach"])+            #expect(roles.allSatisfy { $0.personID == adult })+            #expect(roles.first(where: { $0.role == "Teacher" })?.endedAt == end)+            #expect(try graph.personID(for: connection) != adult)+        }+    }++    @Test func editingRoleDatesKeepsIdentityAndRejectsStaleEdits() throws {+        try withConnection { _, graph, family, _ in+            let source = try graph.createContext(name: "Swimming", familyID: family)+            let adult = try graph.addPerson(name: "Adult", familyID: family)+            let roleID = try graph.associatePerson(adult, contextID: source, role: "Coach")+            let old = try #require(try graph.contextPeople(source).first)+            let end = Date()+            try graph.updateRole(roleID, role: "Former coach", startedAt: nil, endedAt: end, expected: old)+            #expect(throws: GraphError.self) {+                try graph.updateRole(roleID, role: "Stale role", startedAt: nil, endedAt: nil, expected: old)+            }+            let changed = try #require(try graph.contextPeople(source).first)+            #expect(changed.id == roleID && changed.personID == adult && changed.contextID == source)+            #expect(changed.role == "Former coach" && changed.endedAt == end)+        }+    }++    @Test func overlappingTemporalEditsRemainRetainedAndAreNotGivenAnAutomaticWinner() throws {+        try withConnection { stack, graph, familyID, connection in+            try graph.setCloseness(.friend, connectionID: connection, expectedID: nil)+            let context = stack.container.viewContext+            let root = try context.existingObject(with: connection)+            let family = try #require(root.value(forKey: "familySpace") as? NSManagedObject)+            let other = NSEntityDescription.insertNewObject(forEntityName: "ConnectionClosenessPeriod", into: context)+            context.assign(other, to: try #require(connection.persistentStore))+            other.setValue(UUID(), forKey: "id")+            other.setValue(root, forKey: "connection")+            other.setValue(family, forKey: "familySpace")+            other.setValue(Int16(10), forKey: "value")+            other.setValue(Date(), forKey: "startedAt")+            try context.save()+            let state = try graph.connectionState(connection)+            #expect(state.closenessNeedsReview)+            #expect(state.closeness == nil)+            #expect(throws: GraphError.self) { try graph.setCloseness(.goodFriend, connectionID: connection, expectedID: nil) }+            #expect(try context.count(for: NSFetchRequest<NSManagedObject>(entityName: "ConnectionClosenessPeriod")) == 2)+            #expect(try graph.reviewConnections(in: familyID).first?.relationshipNeedsReview == true)+        }+    }+}
Tests/HaloPersistenceTests/ArchiveTests.swift Added +161 / -0
diff --git a/Tests/HaloPersistenceTests/ArchiveTests.swift b/Tests/HaloPersistenceTests/ArchiveTests.swiftnew file mode 100644index 0000000..4117af6--- /dev/null+++ b/Tests/HaloPersistenceTests/ArchiveTests.swift@@ -0,0 +1,161 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct ArchiveTests {+    private func withStore(_ operation: (FamilyRepository) throws -> Void) throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let stack = try PersistenceStack(directory: directory)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        try operation(FamilyRepository(stack: stack))+    }++    @Test func personArchiveRetainsRelationshipsOriginsAndIdentityForRestore() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic"), child = try graph.addChild(name: "Child", familyID: family)+            let connection = try graph.quickCapture(name: "Peer", childID: child)+            let person = try graph.personID(for: connection)+            let context = try graph.createContext(name: "Swimming", familyID: family)+            _ = try graph.addMembership(connectionID: connection, contextID: context)+            try graph.saveOrigin(connectionID: connection, input: OriginInput(contextID: context, narrative: "First lesson"),+                                 expectedOrigin: nil)+            let uuid = try graph.stable(graph.readable(person, entity: "Person"))+            let original = try graph.person(person)+            try graph.setArchived(graph.archiveSnapshot(person), archived: true)+            #expect(try graph.person(person).isArchived)+            #expect(try graph.people(in: family).contains { $0.id == person } == false)+            #expect(try graph.people(in: family, includeArchived: true).first { $0.id == person }?.isArchived == true)+            #expect(try graph.connections(for: child).isEmpty)+            #expect(try graph.memberships(for: connection).count == 1 && graph.origin(for: connection)?.narrative == "First lesson")+            #expect(throws: MergeError.self) {+                try graph.updatePerson(person, name: "Stale", notes: "", needsReview: false, expected: original)+            }+            try graph.setArchived(graph.archiveSnapshot(person), archived: false)+            #expect(try graph.stable(graph.readable(person, entity: "Person")) == uuid)+            #expect(try graph.person(person).name == "Peer" && graph.connections(for: child).count == 1)+        }+    }++    @Test func childProfileArchiveRetainsPersonAndHistoryAndStopsCapture() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic"), child = try graph.addChild(name: "Child", familyID: family)+            let connection = try graph.quickCapture(name: "Peer", childID: child)+            let object = try graph.readable(child, entity: "ChildProfile")+            let person = try #require(object.value(forKey: "person") as? NSManagedObject)+            let uuid = try graph.stable(object)+            try graph.setArchived(graph.archiveSnapshot(child), archived: true)+            #expect(try graph.children(in: family).isEmpty)+            #expect(try graph.children(in: family, includeArchived: true).map(\.id) == [child])+            #expect(!graph.canCapture(child))+            #expect(try CaptureRepository(graph: graph).children().isEmpty)+            #expect(throws: MergeError.self) { try graph.quickCapture(name: "Denied", childID: child) }+            #expect(try graph.connections(for: child).map(\.id) == [connection])+            #expect(try graph.person(person.objectID).isArchived == false)+            try graph.setArchived(graph.archiveSnapshot(child), archived: false)+            #expect(graph.canCapture(child))+            #expect(try graph.stable(graph.readable(child, entity: "ChildProfile")) == uuid)+            #expect(try graph.children(in: family).map(\.id) == [child])+        }+    }++    @Test func groupArchiveRetainsMembersGiftPartiesAndAddressLabels() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic"), person = try graph.addPerson(name: "Peer", familyID: family)+            let group = try graph.createGroup(name: "Our household", familyID: family)+            try graph.addGroupMember(person, groupID: group, role: "Member")+            try graph.addAddressLabel(targetID: person, label: "Auntie", usedByGroup: group)+            let event = try graph.createEvent(title: "Birthday", date: Date(), notes: "", familyID: family)+            try graph.saveGift(eventID: event, input: GiftInput(description: "Book", groups: [group], recipients: [person]), expected: nil)+            try graph.setArchived(graph.archiveSnapshot(group), archived: true)+            #expect(try graph.groups(in: family).isEmpty)+            #expect(try graph.groups(in: family, includeArchived: true).first?.isArchived == true)+            #expect(try graph.groupMembers(group).map(\.personID) == [person])+            #expect(try graph.addressLabels(for: person).first?.usedBy == "Our household")+            #expect(try graph.gifts(event).first?.groupIDs == [group])+            #expect(throws: MergeError.self) { try graph.addGroupMember(person, groupID: group) }+            try graph.setArchived(graph.archiveSnapshot(group), archived: false)+            #expect(try graph.groups(in: family).map(\.id) == [group])+        }+    }++    @Test func openedRoleEditorRejectsArchivedPersonButAllowsArchivedContextHistory() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic"), person = try graph.addPerson(name: "Coach", familyID: family)+            let context = try graph.createContext(name: "Swimming", familyID: family)+            _ = try graph.associatePerson(person, contextID: context, role: "Coach")+            let original = try #require(try graph.contextPeople(context).first)+            try graph.setArchived(graph.archiveSnapshot(person), archived: true)+            #expect(throws: MergeError.self) {+                try graph.updateRole(original.id, role: "Stale", startedAt: nil, endedAt: nil, expected: original)+            }+            #expect(try graph.contextPeople(context).first?.role == "Coach")+            try graph.setArchived(graph.archiveSnapshot(person), archived: false)+            try graph.archiveContext(context, archived: true)+            try graph.updateRole(original.id, role: "Former coach", startedAt: nil,+                                 endedAt: Date(timeIntervalSince1970: 1000), expected: original)+            #expect(try graph.contextPeople(context).first?.role == "Former coach")+        }+    }++    @Test func queuedMembershipEndRejectsArchivedGroupAndPreservesHistory() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic"), person = try graph.addPerson(name: "Peer", familyID: family)+            let group = try graph.createGroup(name: "Household", familyID: family)+            try graph.addGroupMember(person, groupID: group)+            let original = try #require(try graph.groupMembers(group).first)+            try graph.setArchived(graph.archiveSnapshot(group), archived: true)+            #expect(throws: MergeError.self) { try graph.endGroupMembership(original.id, at: Date()) }+            #expect(try graph.groupMembers(group).first?.endedAt == nil)+            try graph.setArchived(graph.archiveSnapshot(group), archived: false)+            let endedAt = Date(timeIntervalSince1970: 1000)+            try graph.endGroupMembership(original.id, at: endedAt)+            #expect(try graph.groupMembers(group).first?.id == original.id)+            #expect(try graph.groupMembers(group).first?.endedAt == endedAt)+        }+    }++    @Test func staleAndRepeatedArchiveSnapshotsCannotOverrideLaterChanges() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic"), person = try graph.addPerson(name: "Peer", familyID: family)+            let original = try graph.archiveSnapshot(person)+            try graph.updatePerson(person, name: "Current", notes: "", needsReview: false, expected: graph.person(person))+            #expect(throws: MemoryError.self) { try graph.setArchived(original, archived: true) }+            let current = try graph.archiveSnapshot(person)+            try graph.setArchived(current, archived: true)+            #expect(throws: MemoryError.self) { try graph.setArchived(current, archived: true) }+            #expect(try graph.person(person).name == "Current" && graph.person(person).isArchived)+        }+    }++    @Test func readOnlyAndInvalidatedFamiliesRejectArchiveAndRestore() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic"), person = try graph.addPerson(name: "Peer", familyID: family)+            let snapshot = try graph.archiveSnapshot(person)+            let identity = try StoreAccess.identity(graph.readable(person, entity: "Person"))+            graph.stack.access.update(readable: [identity], writable: [])+            #expect(!graph.canArchive(snapshot))+            #expect(throws: AccessError.self) { try graph.setArchived(snapshot, archived: true) }+            graph.stack.access.update(readable: [identity], writable: [identity])+            try graph.setArchived(snapshot, archived: true)+            let archived = try graph.archiveSnapshot(person)+            graph.stack.access.update(readable: [identity], writable: [])+            #expect(throws: AccessError.self) { try graph.setArchived(archived, archived: false) }+            graph.stack.access.invalidate()+            #expect(throws: AccessError.self) { try graph.archiveSnapshot(person) }+        }+    }++    @Test func ordinaryRestoreCannotUndoAMergeAlias() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic")+            let source = try graph.addPerson(name: "Peer", familyID: family), kept = try graph.addPerson(name: "Peer", familyID: family)+            _ = try graph.mergePeople(graph.mergePreview(sourceID: source, survivorID: kept), choices: PersonMergeChoices())+            let archived = try graph.archiveSnapshot(source)+            #expect(!graph.canArchive(archived))+            #expect(throws: MergeError.self) { try graph.setArchived(archived, archived: false) }+            #expect(try graph.mergedPersonTarget(source) == kept)+        }+    }+}
Tests/HaloPersistenceTests/CaptureTests.swift Added +221 / -0
diff --git a/Tests/HaloPersistenceTests/CaptureTests.swift b/Tests/HaloPersistenceTests/CaptureTests.swiftnew file mode 100644index 0000000..0184ed7--- /dev/null+++ b/Tests/HaloPersistenceTests/CaptureTests.swift@@ -0,0 +1,221 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct CaptureTests {+    private func withStack(_ test: (PersistenceStack, FamilyRepository, URL) throws -> Void) throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let stack = try PersistenceStack(directory: directory)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        try test(stack, FamilyRepository(stack: stack), directory)+    }++    private func reference(_ id: NSManagedObjectID, stack: PersistenceStack) throws -> CaptureReference {+        let object = try stack.container.viewContext.existingObject(with: id)+        let graph = FamilyRepository(stack: stack)+        return CaptureReference(namespace: CaptureRepository(graph: graph).namespace, family: try StoreAccess.identity(object),+                                record: try graph.stable(object))+    }++    @Test func routesRoundTripScopedIdentitiesWithoutNames() throws {+        let family = FamilyAccessID(family: UUID(), shared: true)+        let child = CaptureReference(namespace: "account-synthetic", family: family, record: UUID())+        let context = CaptureReference(namespace: child.namespace, family: family, record: UUID())+        let url = try #require(CaptureRoute(child: child, context: context).url)+        let route = try #require(CaptureRoute(url: url))+        #expect(route.child == child && route.context == context)+        #expect(CaptureReference(identifier: child.identifier) == child)+        #expect(url.query?.contains("name") == false)+        #expect(CaptureRoute(url: try #require(CaptureRoute(child: child).url))?.context == nil)+    }++    @Test func routesRejectMalformedOrAmbiguousSelections() throws {+        let family = FamilyAccessID(family: UUID(), shared: false)+        let child = CaptureReference(namespace: "local", family: family, record: UUID())+        let base = try #require(CaptureRoute(child: child).url).absoluteString+        for suffix in ["&child=invalid", "&context=invalid", "&unknown=value", "#fragment"] {+            #expect(CaptureRoute(url: try #require(URL(string: base + suffix))) == nil)+        }+        for invalid in ["local:foreign:\(family.family):\(child.record)", ":private:\(family.family):\(child.record)",+                        "lócál:private:\(family.family):\(child.record)", String(repeating: "a", count: 257)] {+            #expect(CaptureReference(identifier: invalid) == nil)+        }+        let other = CaptureReference(namespace: "account-other", family: family, record: UUID())+        #expect(CaptureRoute(url: try #require(CaptureRoute(child: child, context: other).url)) == nil)+        #expect(CaptureRoute(url: try #require(URL(string: base.replacingOccurrences(of: "capture?", with: "capture/path?")))) == nil)+    }++    @Test func independentIntentCoordinatorCapturesMembershipWithoutInventingOrigin() 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: "Synthetic child", familyID: family)+        let context = try graph.createContext(name: "Swimming", familyID: family)+        let childRef = try reference(child, stack: host), contextRef = try reference(context, stack: host)+        let intent = try PersistenceStack(directory: directory, role: .appIntent)+        intent.container.viewContext.automaticallyMergesChangesFromParent = false+        #expect(!(intent.container is NSPersistentCloudKitContainer))+        let capture = CaptureRepository(graph: FamilyRepository(stack: intent))+        #expect(capture.namespace == childRef.namespace)+        _ = try capture.capture(name: " Synthetic friend ", child: childRef, context: contextRef)+        let history = HistoryProcessor(container: host.container, directory: directory.appendingPathComponent("history"), consumer: "test")+        _ = try await history.process()+        let connection = try #require(graph.connections(for: child).first)+        #expect(connection.name == "Synthetic friend")+        #expect(try graph.memberships(for: connection.id).count == 1)+        #expect(try graph.origin(for: connection.id) == nil)+        #expect(try graph.originHistory(for: connection.id).isEmpty)+        #expect(try graph.person(graph.personID(for: connection.id)).needsReview)+    }++    @Test func minimalCaptureKeepsDuplicateNamesAndNoDefaultMembership() throws {+        try withStack { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic")+            let child = try graph.addChild(name: "Child", familyID: family)+            let capture = CaptureRepository(graph: graph), selected = try reference(child, stack: stack)+            let first = try capture.capture(name: "Friend", child: selected, context: nil)+            let second = try capture.capture(name: "Friend", child: selected, context: nil)+            #expect(first != second)+            #expect(try graph.connections(for: child).count == 2)+            #expect(try graph.memberships(for: first).isEmpty)+            #expect(throws: GraphError.self) { try capture.capture(name: " \n ", child: selected, context: nil) }+            #expect(try graph.connections(for: child).count == 2)+        }+    }++    @Test func archivedContextRejectsSavedSelectionWithoutPartialCapture() throws {+        try withStack { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic")+            let child = try graph.addChild(name: "Child", familyID: family)+            let context = try graph.createContext(name: "Old class", familyID: family)+            let childRef = try reference(child, stack: stack), contextRef = try reference(context, stack: stack)+            try graph.archiveContext(context, archived: true)+            let capture = CaptureRepository(graph: graph)+            #expect(try capture.contexts(for: childRef).isEmpty)+            #expect(throws: GraphError.self) { try capture.capture(name: "Denied", child: childRef, context: contextRef) }+            #expect(throws: GraphError.self) { try graph.quickCapture(name: "Denied", childID: child, contextID: context) }+            #expect(try graph.connections(for: child).isEmpty)+            #expect(try stack.container.viewContext.count(for: NSFetchRequest<NSManagedObject>(entityName: "Person")) == 1)+        }+    }++    @Test func crossFamilyContextCannotBeUsedByDomainOrScopedCapture() throws {+        try withStack { stack, graph, _ in+            let family = try graph.createFamily(name: "First"), other = try graph.createFamily(name: "Second")+            let child = try graph.addChild(name: "Child", familyID: family)+            let context = try graph.createContext(name: "Other class", familyID: other)+            let capture = CaptureRepository(graph: graph)+            #expect(throws: GraphError.self) {+                try capture.capture(name: "Denied", child: reference(child, stack: stack), context: reference(context, stack: stack))+            }+            #expect(throws: GraphError.self) { try graph.quickCapture(name: "Denied", childID: child, contextID: context) }+            #expect(try graph.connections(for: child).isEmpty)+        }+    }++    @Test func archivedDeceasedAndMergedChildrenRejectStaleCapture() throws {+        try withStack { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic")+            let child = try graph.addChild(name: "Child", familyID: family)+            let selected = try reference(child, stack: stack)+            let context = stack.container.viewContext+            let profile = try context.existingObject(with: child)+            let person = try #require(profile.value(forKey: "person") as? NSManagedObject)+            let target = try graph.addPerson(name: "Retained target", familyID: family)+            for state in 0..<4 {+                profile.setValue(state == 0 ? Date() : nil, forKey: "archivedAt")+                person.setValue(state == 1 ? Date() : nil, forKey: "archivedAt")+                person.setValue(state == 2, forKey: "isDeceased")+                person.setValue(state == 3 ? try context.existingObject(with: target) : nil, forKey: "mergedInto")+                try context.save()+                #expect(throws: GraphError.self) { try CaptureRepository(graph: graph).child(selected) }+                #expect(throws: Error.self) { try graph.quickCapture(name: "Denied", childID: child) }+            }+            #expect(try context.count(for: NSFetchRequest<NSManagedObject>(entityName: "Connection")) == 0)+        }+    }++    @Test func currentLabelsAndPermissionsReplaceSerializedEntityDisplay() throws {+        try withStack { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic")+            let child = try graph.addChild(name: "Old label", familyID: family)+            let selected = try reference(child, stack: stack)+            let object = try stack.container.viewContext.existingObject(with: child)+            let person = try #require(object.value(forKey: "person") as? NSManagedObject)+            let previous = try graph.person(person.objectID)+            try graph.updatePerson(person.objectID, name: "Current label", notes: previous.notes,+                                   needsReview: previous.needsReview, expected: previous)+            let capture = CaptureRepository(graph: graph)+            #expect(try capture.child(selected).name == "Current label")+            stack.access.update(readable: [selected.family], writable: [])+            #expect(try capture.children().isEmpty)+            #expect(throws: AccessError.self) { try capture.capture(name: "Denied", child: selected, context: nil) }+            #expect(try graph.connections(for: child).isEmpty)+        }+    }++    @Test func readOnlyWidgetCoordinatorCannotCapture() throws {+        try withStack { stack, graph, directory in+            let family = try graph.createFamily(name: "Synthetic")+            let child = try graph.addChild(name: "Child", familyID: family)+            let selected = try reference(child, stack: stack)+            let widget = try PersistenceStack(directory: directory, role: .widget)+            #expect(!(widget.container is NSPersistentCloudKitContainer))+            #expect(try CaptureRepository(graph: FamilyRepository(stack: widget)).child(selected).name == "Child")+            #expect(throws: GraphError.self) {+                try CaptureRepository(graph: FamilyRepository(stack: widget)).capture(name: "Denied", child: selected, context: nil)+            }+            #expect(try graph.connections(for: child).isEmpty)+        }+    }++    @Test func namespaceAndStoreQualifierCannotSelectAnotherLibrary() throws {+        try withStack { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic"), child = try graph.addChild(name: "Child", familyID: family)+            let selected = try reference(child, stack: stack)+            let otherAccount = CaptureReference(namespace: "account-other", family: selected.family, record: selected.record)+            let otherStore = CaptureReference(namespace: selected.namespace,+                family: FamilyAccessID(family: selected.family.family, shared: true), record: selected.record)+            let capture = CaptureRepository(graph: graph)+            #expect(throws: AccessError.self) { try capture.child(otherAccount) }+            #expect(throws: GraphError.self) { try capture.child(otherStore) }+            #expect(try graph.connections(for: child).isEmpty)+        }+    }++    @Test func ambiguousRecordUUIDCannotSelectOneArbitraryChild() throws {+        try withStack { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic"), first = try graph.addChild(name: "First", familyID: family)+            let second = try graph.addChild(name: "Second", familyID: family)+            let selected = try reference(first, stack: stack)+            let object = try stack.container.viewContext.existingObject(with: second)+            object.setValue(selected.record, forKey: "id")+            try stack.container.viewContext.save()+            #expect(throws: GraphError.self) { try CaptureRepository(graph: graph).child(selected) }+            #expect(try graph.connections(for: first).isEmpty && graph.connections(for: second).isEmpty)+        }+    }++    @Test func manifestRevocationStopsPreparedIntentBeforeSave() throws {+        try withStack { stack, graph, directory in+            let family = try graph.createFamily(name: "Synthetic"), child = try graph.addChild(name: "Child", familyID: family)+            let selected = try reference(child, stack: stack)+            let granted = ExtensionAccess(version: 1, namespace: selected.namespace, readable: [selected.family],+                                          writable: [selected.family], locked: false)+            try granted.save(in: directory)+            let intent = try PersistenceStack(directory: directory, role: .appIntent)+            intent.access.watchExtensionAccess(directory: directory, namespace: selected.namespace)+            let capture = CaptureRepository(graph: FamilyRepository(stack: intent))+            _ = try capture.child(selected)+            try ExtensionAccess(version: 1, namespace: selected.namespace, readable: [selected.family], writable: [], locked: false)+                .save(in: directory)+            #expect(throws: AccessError.self) { try capture.capture(name: "Denied", child: selected, context: nil) }+            #expect(try graph.connections(for: child).isEmpty)+        }+    }+}
Tests/HaloPersistenceTests/ContextCategoryTests.swift Added +95 / -0
diff --git a/Tests/HaloPersistenceTests/ContextCategoryTests.swift b/Tests/HaloPersistenceTests/ContextCategoryTests.swiftnew file mode 100644index 0000000..d211166--- /dev/null+++ b/Tests/HaloPersistenceTests/ContextCategoryTests.swift@@ -0,0 +1,95 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct ContextCategoryTests {+    private func withStore(_ operation: (FamilyRepository, URL) throws -> Void) throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let stack = try PersistenceStack(directory: directory)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        try operation(FamilyRepository(stack: stack), directory)+    }++    @Test func newFamilyHasOrdinaryEditableScopedStarterCategories() throws {+        try withStore { graph, _ in+            let family = try graph.createFamily(name: "Synthetic family"), other = try graph.createFamily(name: "Other")+            let categories = try graph.contextCategories(in: family)+            #expect(Set(categories.map(\.name)) == Set(FamilyRepository.starterCategories))+            let otherCategories = try graph.contextCategories(in: other)+            #expect(Set(categories.map(\.id)).isDisjoint(with: otherCategories.map(\.id)))+            let school = try #require(categories.first { $0.name == "School" })+            try graph.updateCategory(school, name: "Learning", archived: false)+            #expect(try graph.contextCategories(in: family).first { $0.id == school.id }?.name == "Learning")+            #expect(try graph.contextCategories(in: other).contains { $0.name == "School" })+        }+    }++    @Test func archivingRetainsExistingLinkAndRejectsNewAssignment() throws {+        try withStore { graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let context = try graph.createContext(name: "Class", familyID: family)+            let category = try #require(try graph.contextCategories(in: family).first)+            try graph.setContextCategory(context, categoryID: category.id, expectedID: nil)+            try graph.updateCategory(category, name: category.name, archived: true)+            #expect(try graph.contextCategory(context) == category.id)+            let fresh = try graph.createContext(name: "New class", familyID: family)+            #expect(throws: MemoryError.self) { try graph.setContextCategory(fresh, categoryID: category.id, expectedID: nil) }+            #expect(try graph.contextCategory(fresh) == nil)+            try graph.setContextCategory(context, categoryID: nil, expectedID: category.id)+            #expect(try graph.contextCategory(context) == nil)+        }+    }++    @Test func staleCategoryAndContextEditsRetainNewerChoice() throws {+        try withStore { graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let context = try graph.createContext(name: "Class", familyID: family)+            let categories = try graph.contextCategories(in: family), first = try #require(categories.first)+            try graph.updateCategory(first, name: "Changed", archived: false)+            #expect(throws: MemoryError.self) { try graph.updateCategory(first, name: "Stale", archived: true) }+            try graph.setContextCategory(context, categoryID: first.id, expectedID: nil)+            #expect(throws: MemoryError.self) { try graph.setContextCategory(context, categoryID: nil, expectedID: nil) }+            #expect(try graph.contextCategory(context) == first.id)+        }+    }++    @Test func foreignCategoryAndBlankNameRejectWithoutWrites() throws {+        try withStore { graph, _ in+            let family = try graph.createFamily(name: "Synthetic family"), other = try graph.createFamily(name: "Other")+            let context = try graph.createContext(name: "Class", familyID: family)+            let foreign = try #require(try graph.contextCategories(in: other).first)+            #expect(throws: GraphError.self) { try graph.setContextCategory(context, categoryID: foreign.id, expectedID: nil) }+            #expect(throws: GraphError.self) { try graph.createCategory(name: " ", familyID: family) }+            #expect(try graph.contextCategory(context) == nil)+            #expect(try graph.contextCategories(in: family).count == 5)+        }+    }++    @Test func explicitStarterActionDoesNotReviveArchivedOrDuplicateExistingLabels() throws {+        try withStore { graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let category = try #require(try graph.contextCategories(in: family).first)+            try graph.updateCategory(category, name: category.name, archived: true)+            try graph.addStarterCategories(familyID: family); try graph.addStarterCategories(familyID: family)+            #expect(try graph.contextCategories(in: family).count == 5)+            #expect(try graph.contextCategories(in: family).first { $0.id == category.id }?.isArchived == true)+        }+    }++    @Test func existingMigratedFamilyReceivesNoImplicitCategoryWrites() throws {+        try withStore { _, directory in+            let oldDirectory = directory.appendingPathComponent("Old")+            do {+                let old = try PersistenceStack(directory: oldDirectory, model: PersistenceStack.loadModel(version: "HaloModelV4"))+                _ = try FamilyRepository(stack: old).createFamily(name: "Earlier synthetic family")+            }+            let current = try PersistenceStack(directory: oldDirectory), graph = FamilyRepository(stack: current)+            let family = try #require(try graph.families().first)+            #expect(try graph.contextCategories(in: family.id).isEmpty)+            try graph.addStarterCategories(familyID: family.id)+            #expect(try graph.contextCategories(in: family.id).count == 5)+        }+    }+}
Tests/HaloPersistenceTests/DefaultsMigrationHistoryTests.swift Added +107 / -0
diff --git a/Tests/HaloPersistenceTests/DefaultsMigrationHistoryTests.swift b/Tests/HaloPersistenceTests/DefaultsMigrationHistoryTests.swiftnew file mode 100644index 0000000..2b36010--- /dev/null+++ b/Tests/HaloPersistenceTests/DefaultsMigrationHistoryTests.swift@@ -0,0 +1,107 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct DefaultsMigrationHistoryTests {+    @Test func bothV3StoresMigrateAndTheFirstEditRetainsLegacyOriginIdentityAndAccount() throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let old = try PersistenceStack(directory: directory, model: PersistenceStack.loadModel(version: "HaloModelV3"))+        old.container.viewContext.automaticallyMergesChangesFromParent = false+        let graph = FamilyRepository(stack: old)+        let privateFamily = try graph.createFamily(name: "Synthetic owner")+        let context = old.container.viewContext+        let shared = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+        context.assign(shared, to: old.sharedStore)+        shared.setValue(UUID(), forKey: "id")+        shared.setValue("Synthetic participant", forKey: "name")+        try context.save()+        var originIDs: Set<UUID> = []+        for familyID in [privateFamily, shared.objectID] {+            let child = try graph.addChild(name: "Child", familyID: familyID)+            let connectionID = try graph.quickCapture(name: "Friend", childID: child)+            let sourceID = try graph.createContext(name: "Playgroup", familyID: familyID)+            let family = try context.existingObject(with: familyID)+            let origin = NSEntityDescription.insertNewObject(forEntityName: "ConnectionOrigin", into: context)+            context.assign(origin, to: try #require(familyID.persistentStore))+            let id = UUID()+            originIDs.insert(id)+            origin.setValue(id, forKey: "id")+            origin.setValue(family, forKey: "familySpace")+            origin.setValue(try context.existingObject(with: connectionID), forKey: "connection")+            origin.setValue(try context.existingObject(with: sourceID), forKey: "context")+            origin.setValue("First lesson", forKey: "originDescription")+            let adultID = try graph.addPerson(name: "Teacher", familyID: familyID)+            let association = NSEntityDescription.insertNewObject(forEntityName: "ContextPerson", into: context)+            context.assign(association, to: try #require(familyID.persistentStore))+            association.setValue(UUID(), forKey: "id")+            association.setValue(family, forKey: "familySpace")+            association.setValue(try context.existingObject(with: sourceID), forKey: "context")+            association.setValue(try context.existingObject(with: adultID), forKey: "person")+            try context.save()+        }+        context.reset()+        for store in old.container.persistentStoreCoordinator.persistentStores {+            try old.container.persistentStoreCoordinator.remove(store)+        }+        let current = try PersistenceStack(directory: directory)+        current.container.viewContext.automaticallyMergesChangesFromParent = false+        let migrated = FamilyRepository(stack: current)+        let origins = try current.container.viewContext.fetch(NSFetchRequest<NSManagedObject>(entityName: "ConnectionOrigin"))+        #expect(Set(origins.compactMap { $0.value(forKey: "id") as? UUID }) == originIDs)+        for family in try migrated.families() {+            let child = try #require(try migrated.children(in: family.id).first)+            let connection = try #require(try migrated.connections(for: child.id).first)+            let legacy = try #require(try migrated.origin(for: connection.id))+            #expect(legacy.narrative == "First lesson")+            #expect(try migrated.originHistory(for: connection.id).isEmpty)+            let sourceID = try #require(legacy.contextID)+            let roles = try migrated.contextPeople(sourceID)+            #expect(roles.count == 1 && roles.first?.role == "")+            try migrated.saveOrigin(connectionID: connection.id, input: OriginInput(narrative: "Updated account"),+                                    expectedOrigin: legacy)+            #expect(try migrated.origin(for: connection.id)?.id == legacy.id)+            let history = try migrated.originHistory(for: connection.id)+            #expect(Set(history.map(\.narrative)) == ["First lesson", "Updated account"])+            #expect(history.allSatisfy { $0.id.persistentStore == family.id.persistentStore })+            #expect(try migrated.connectionState(connection.id).closeness == nil)+        }+    }++    @Test func secondCoordinatorProposalAndRelationshipWritesRefreshTogether() async throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let host = try PersistenceStack(directory: directory)+        host.container.viewContext.automaticallyMergesChangesFromParent = false+        let graph = FamilyRepository(stack: host)+        let family = try graph.createFamily(name: "Synthetic family")+        let child = try graph.addChild(name: "Child", familyID: family)+        let connection = try graph.quickCapture(name: "Friend", childID: child)+        try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Playground"), expectedOrigin: nil)+        let original = try #require(try graph.origin(for: connection))+        let processor = HistoryProcessor(container: host.container,+                                         directory: directory.appendingPathComponent("History"), consumer: "host")+        _ = try await processor.process()+        let writer = try await PersistenceStack.open(+            configuration: StoreConfiguration(directory: directory, role: .appIntent, mirrorsCloud: false)+        )+        writer.container.viewContext.automaticallyMergesChangesFromParent = false+        let external = FamilyRepository(stack: writer)+        let writerFamily = try #require(try external.families().first)+        let writerChild = try #require(try external.children(in: writerFamily.id).first)+        let writerConnection = try #require(try external.connections(for: writerChild.id).first)+        let baseline = try #require(try external.origin(for: writerConnection.id))+        try external.saveOrigin(connectionID: writerConnection.id, input: OriginInput(narrative: "Birthday"), expectedOrigin: baseline)+        try external.setCloseness(.friend, connectionID: writerConnection.id, expectedID: nil)+        try external.setConnectionState(.lostContact, note: "Moved", connectionID: writerConnection.id, expectedID: nil)+        #expect(try await processor.process() == 3)+        #expect(try graph.origin(for: connection)?.narrative == "Birthday")+        #expect(try graph.originHistory(for: connection).count == 2)+        #expect(try graph.connectionState(connection).closeness == .friend)+        #expect(try graph.connectionState(connection).state == .lostContact)+        #expect(throws: GraphError.self) {+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Stale account"), expectedOrigin: original)+        }+    }+}
Tests/HaloPersistenceTests/FamilyBackupTests.swift Added +344 / -0
diff --git a/Tests/HaloPersistenceTests/FamilyBackupTests.swift b/Tests/HaloPersistenceTests/FamilyBackupTests.swiftnew file mode 100644index 0000000..d7e598b--- /dev/null+++ b/Tests/HaloPersistenceTests/FamilyBackupTests.swift@@ -0,0 +1,344 @@+import CoreData+import CoreGraphics+import ImageIO+import Testing+import UniformTypeIdentifiers+@testable import HaloPersistence++@MainActor+struct FamilyBackupTests {+    private func withStore(_ body: (PersistenceStack, FamilyRepository, URL) async throws -> Void) async throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let stack = try PersistenceStack(directory: directory)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        try await body(stack, FamilyRepository(stack: stack), directory)+    }++    @Test func portableRoundTripRetainsSparseGraphPayloadsAndStableIdentities() async throws {+        try await withStore { stack, graph, directory in+            let family = try graph.createFamily(name: "Synthetic source")+            let child = try graph.addChild(name: "Child", familyID: family)+            let connection = try graph.quickCapture(name: "Peer", childID: child)+            let context = try graph.createContext(name: "Class", familyID: family)+            _ = try graph.addMembership(connectionID: connection, contextID: context)+            let payload = Data([1, 3, 5, 7])+            let asset = try await AssetRepository(stack: stack).save(data: payload, familyID: family)+            let service = BackupRepository(stack: stack)+            let archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            #expect(preview.peopleCount == 2); #expect(preview.payloadBytes == 4)+            let originalFamily = try #require(try graph.readable(family, entity: "FamilySpace").value(forKey: "id") as? UUID)+            let target = try PersistenceStack(directory: directory.appendingPathComponent("Restore"))+            let restored = try await BackupRepository(stack: target).restore(preview, asNewCopy: false)+            let restoredGraph = FamilyRepository(stack: target)+            #expect(try restoredGraph.readable(restored, entity: "FamilySpace").value(forKey: "id") as? UUID == originalFamily)+            #expect(try restoredGraph.people(in: restored).map(\.name) == ["Child", "Peer"])+            let request = NSFetchRequest<NSManagedObject>(entityName: "Asset")+            let imported = try #require(try target.container.viewContext.fetch(request).first)+            let originalAssetID = try graph.readable(asset, entity: "Asset").value(forKey: "id") as? UUID+            #expect(imported.value(forKey: "id") as? UUID == originalAssetID)+            #expect(try await AssetRepository(stack: target).data(for: imported.objectID) == payload)+            let reopened = try PersistenceStack(directory: directory.appendingPathComponent("Restore"))+            #expect(try FamilyRepository(stack: reopened).families().count == 1)+        }+    }++    @Test func existingIdentityStopsRestoreWithoutPartialRowsOrOverwrite() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            _ = try graph.addPerson(name: "Original", familyID: family)+            let service = BackupRepository(stack: stack)+            let archive = try await service.export(familyID: family, readable: false)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            await #expect(throws: BackupError.self) { try await service.restore(preview, asNewCopy: false) }+            #expect(try graph.families().count == 1); #expect(try graph.people(in: family).map(\.name) == ["Original"])+            let copy = try await service.restore(preview, asNewCopy: true)+            #expect(copy != family); #expect(try graph.families().map(\.name) == ["Synthetic family", "Synthetic family (copy)"])+            #expect(try graph.people(in: copy).map(\.name) == ["Original"])+        }+    }++    @Test func changedPreviewAndParallelImportGuardCannotCreateRows() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let service = BackupRepository(stack: stack)+            let archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            let handle = try FileHandle(forWritingTo: archive)+            try handle.seekToEnd(); try handle.write(contentsOf: Data([0])); try handle.close()+            await #expect(throws: BackupError.self) { try await service.restore(preview, asNewCopy: true) }+            stack.importingBackup = true+            await #expect(throws: BackupError.self) { try await service.restore(preview, asNewCopy: true) }+            stack.importingBackup = false+            #expect(try graph.families().count == 1)+        }+    }++    @Test func copiedMergeHistoryUsesNewNamespaceAndRestoreRetainsGuardedUndo() async throws {+        try await withStore { stack, graph, directory in+            let family = try graph.createFamily(name: "Synthetic family")+            let source = try graph.addPerson(name: "Source", familyID: family)+            let kept = try graph.addPerson(name: "Kept", familyID: family)+            let audit = try graph.mergePeople(graph.mergePreview(sourceID: source, survivorID: kept), choices: PersonMergeChoices())+            let service = BackupRepository(stack: stack)+            let archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            let originalIDs = Set(preview.backup.records.map(\.id))+            let copy = try await service.restore(preview, asNewCopy: true)+            let copiedObject = try graph.readable(copy, entity: "FamilySpace")+            let copiedRows = try MergeSnapshot.records(family: copiedObject, in: stack.container.viewContext)+            #expect(originalIDs.isDisjoint(with: copiedRows.map(\.id)))+            let request = NSFetchRequest<NSManagedObject>(entityName: "PersonMerge")+            request.predicate = NSPredicate(format: "familySpace == %@", copy)+            let copiedAudit = try #require(try stack.container.viewContext.fetch(request).first)+            #expect(copiedAudit.value(forKey: "undoUnavailableAt") != nil)+            let history = try MergeSnapshot.decode(copiedAudit.value(forKey: "beforeData") as? Data)+            #expect(originalIDs.isDisjoint(with: history.map(\.id)))+            #expect(history.allSatisfy { $0.links["familySpace"] == [copiedObject.value(forKey: "id") as? UUID].compactMap { $0 } })+            #expect(try graph.mergeConflicts(in: copy).isEmpty)+            #expect(throws: MergeError.self) { try graph.undoPersonMerge(copiedAudit.objectID) }+            let restoredStack = try PersistenceStack(directory: directory.appendingPathComponent("Restore"))+            let restored = try await BackupRepository(stack: restoredStack).restore(preview, asNewCopy: false)+            let restoredRequest = NSFetchRequest<NSManagedObject>(entityName: "PersonMerge")+            restoredRequest.predicate = NSPredicate(format: "familySpace == %@", restored)+            let restoredAudit = try #require(try restoredStack.container.viewContext.fetch(restoredRequest).first)+            let originalAuditID = try graph.readable(audit, entity: "PersonMerge").value(forKey: "id") as? UUID+            #expect(restoredAudit.value(forKey: "id") as? UUID == originalAuditID)+            try FamilyRepository(stack: restoredStack).undoPersonMerge(restoredAudit.objectID)+            #expect(try FamilyRepository(stack: restoredStack).people(in: restored).count == 2)+        }+    }++    @Test func exportExcludesDeviceContactMappingsAndOtherFamilies() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family"), other = try graph.createFamily(name: "Other family")+            let person = try graph.addPerson(name: "Included", familyID: family)+            _ = try graph.addPerson(name: "Excluded", familyID: other)+            let identity = try graph.contactIdentity(person)+            _ = try await stack.localContactLinks().link("synthetic-device-secret", familyID: identity.familyID,+                                                       personID: identity.personID)+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            #expect(preview.peopleCount == 1)+            let encoded = try #require(String(data: PortableGraph.encode(preview.backup), encoding: .utf8))+            #expect(!encoded.contains("Excluded")); #expect(!encoded.contains("synthetic-device-secret"))+        }+    }++    @Test func malformedGraphAndHistoryCannotReachImport() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let person = try graph.addPerson(name: "Synthetic person", familyID: family)+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            var records = preview.backup.records+            let index = try #require(records.firstIndex { $0.entity == "Person" })+            records[index].relationships["familySpace"] = [UUID()]+            let malformed = FamilyBackup(formatVersion: 1, modelVersion: 6, familyID: preview.backup.familyID,+                                         createdAt: Date(), records: records)+            #expect(throws: BackupError.self) { try BackupValidation.validate(malformed, model: stack.container.managedObjectModel) }+            let row = try MergeSnapshot.record(graph.readable(person, entity: "Person"))+            let invalid = MergeRecord(id: row.id, entity: row.entity, attributes: row.attributes,+                                      links: row.links.merging(["familySpace": [UUID()]]) { _, next in next })+            let historyRecord = PortableRecord(id: UUID(), entity: "MergeConnectionReview",+                                               attributes: ["reviewedData": .binary("synthetic")], relationships: [:])+            let history = FamilyBackup(formatVersion: 1, modelVersion: 6, familyID: preview.backup.familyID, createdAt: Date(),+                                       records: preview.backup.records + [historyRecord])+            #expect(throws: BackupError.self) {+                try BackupHistory(backup: history, model: stack.container.managedObjectModel) { _ in try MergeSnapshot.encode([invalid]) }+            }+        }+    }++    @Test func zipRejectsTraversalTruncationExtraMembersAndCorruptPayload() async throws {+        try await withStore { stack, graph, directory in+            let source = directory.appendingPathComponent("Synthetic.txt")+            try Data("hello".utf8).write(to: source)+            #expect(throws: BackupError.self) {+                try BackupArchive.write([BackupFile(name: "../outside", url: source)], to: directory.appendingPathComponent("bad.zip"))+            }+            let zip = directory.appendingPathComponent("valid.zip")+            try BackupArchive.write([BackupFile(name: "Synthetic.txt", url: source)], to: zip)+            let member = try #require(try BackupArchive.members(in: zip).first)+            let handle = try FileHandle(forWritingTo: zip)+            try handle.seek(toOffset: 30 + UInt64(member.name.utf8.count)); try handle.write(contentsOf: Data([255])); try handle.close()+            #expect(throws: BackupError.self) { try BackupArchive.read(member, from: zip, limit: 100) }+            try Data([1, 2, 3]).write(to: zip)+            #expect(throws: BackupError.self) { try BackupArchive.members(in: zip) }+            let family = try graph.createFamily(name: "Synthetic family")+            let service = BackupRepository(stack: stack)+            let archive = try await service.export(familyID: family, readable: false)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let manifest = try #require(try BackupArchive.members(in: archive).first)+            let json = directory.appendingPathComponent("family.json")+            try BackupArchive.read(manifest, from: archive, limit: 32_000_000).write(to: json)+            let extra = directory.appendingPathComponent("extra.zip")+            let files = [BackupFile(name: "family.json", url: json), BackupFile(name: "unexpected.txt", url: source)]+            try BackupArchive.write(files, to: extra)+            await #expect(throws: BackupError.self) { try await service.preview(extra) }+        }+    }++    @Test func widgetAndIntentCannotExportOrRestoreFamily() async throws {+        try await withStore { stack, graph, directory in+            let family = try graph.createFamily(name: "Synthetic family")+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            for role in [PersistenceRole.widget, .appIntent] {+                let other = try PersistenceStack(directory: directory, role: role)+                let restricted = BackupRepository(stack: other)+                await #expect(throws: GraphError.self) { try await restricted.export(familyID: family) }+                await #expect(throws: GraphError.self) { try await restricted.restore(preview, asNewCopy: true) }+            }+        }+    }++    @Test func photoOwnershipEnforcesPayloadPresenceAndSizeDespiteSpoofedKind() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let person = try graph.addPerson(name: "Synthetic person", familyID: family)+            let assetID = try await AssetRepository(stack: stack).save(data: Data([1]), familyID: family)+            let object = try graph.readable(person, entity: "Person")+            object.setValue(try graph.readable(assetID, entity: "Asset"), forKey: "primaryPhoto")+            try stack.container.viewContext.save()+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            var records = preview.backup.records+            let index = try #require(records.firstIndex { $0.entity == "Asset" })+            records[index].attributes["kind"] = .text("generic")+            #expect(throws: BackupError.self) {+                try BackupValidation.payload(Data(repeating: 1, count: ImageImport.photoLimit + 1), key: "data", record: records[index])+            }+            records[index].attributes["data"] = nil+            let malformed = FamilyBackup(formatVersion: 1, modelVersion: 6, familyID: preview.backup.familyID,+                                         createdAt: Date(), records: records)+            #expect(throws: BackupError.self) { try BackupValidation.validate(malformed, model: stack.container.managedObjectModel) }+        }+    }++    @Test func copiedArchivedAccountsDoNotAppearAsNewLateImports() async throws {+        try await withStore { stack, graph, _ in+            let family = try graph.createFamily(name: "Synthetic family")+            let child = try graph.addChild(name: "Child", familyID: family)+            let source = try graph.addPerson(name: "Source", familyID: family), kept = try graph.addPerson(name: "Kept", familyID: family)+            let first = try graph.connect(personID: source, childID: child)+            _ = try graph.connect(personID: kept, childID: child)+            for index in 0..<8 {+                let context = try graph.createContext(name: "Context \(index)", familyID: family)+                _ = try graph.addMembership(connectionID: first, contextID: context)+            }+            let merge = try graph.mergePreview(sourceID: source, survivorID: kept)+            let overlap = try #require(merge.overlaps.first)+            var choice = PersonMergeChoices()+            choice.connections[overlap.id] = MergeConnectionChoices(originID: overlap.origins.first?.id,+                closenessID: overlap.closeness.first?.id, statusID: overlap.statuses.first?.id)+            _ = try graph.mergePeople(merge, choices: choice)+            #expect(try graph.lateMergeAccounts(in: family).isEmpty)+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            let copy = try await service.restore(preview, asNewCopy: true)+            #expect(try graph.lateMergeAccounts(in: copy).isEmpty)+        }+    }++    @Test func completeSharedMemoryRestoresIntoPrivateStorageWithoutLosingAccounts() async throws {+        try await withStore { stack, graph, directory in+            let records = try await sharedMemory(stack: stack, graph: graph)+            let family = try #require(records["family"])+            let before = try MergeSnapshot.records(family: graph.readable(family, entity: "FamilySpace"), in: stack.container.viewContext)+            let assets = AssetRepository(stack: stack)+            let photoBytes = try await assets.data(for: #require(records["photo"]))+            let pdfBytes = try await assets.data(for: #require(records["pdf"]))+            let service = BackupRepository(stack: stack), archive = try await service.export(familyID: family)+            defer { try? FileManager.default.removeItem(at: archive.deletingLastPathComponent()) }+            let preview = try await service.preview(archive)+            let target = try PersistenceStack(directory: directory.appendingPathComponent("Restored memory"))+            let restored = try await BackupRepository(stack: target).restore(preview, asNewCopy: false)+            #expect(restored.persistentStore == target.privateStore)+            let imported = FamilyRepository(stack: target)+            #expect(try MergeSnapshot.records(family: imported.readable(restored, entity: "FamilySpace"),+                                             in: target.container.viewContext) == before)+            let people = try imported.people(in: restored)+            let peer = try #require(people.first { $0.name == "Peer" })+            #expect(try imported.sensitiveDetails(peer.id).date == PartialDate(year: 2024, month: 2))+            #expect(try imported.addressLabels(for: peer.id).first?.label == "Family nickname")+            let connection = try #require(try imported.connections(to: peer.id).first)+            #expect(try imported.originHistory(for: connection.id).count == 2)+            #expect(try imported.origin(for: connection.id)?.narrative == "Met at the party")+            let event = try #require(try imported.events(in: restored).first)+            #expect(try imported.participants(event.id).first?.attendance == .attended)+            #expect(try imported.participants(event.id).first?.invitation == .unknown)+            #expect(try imported.gifts(event.id).first?.description == "Book")+            #expect(try imported.gifts(event.id).first?.recipients == ["Peer"])+            let context = try #require(try imported.contexts(in: restored).first)+            #expect(try imported.contextPeople(context.id).first?.role == "Coach")+            let restoredAssets = AssetRepository(stack: target)+            #expect(try await restoredAssets.data(for: #require(imported.primaryPhoto(peer.id))) == photoBytes)+            let attachment = try #require(try imported.attachments(event.id).first)+            #expect(try await restoredAssets.data(for: attachment.assetID) == pdfBytes)+        }+    }++    private func sharedMemory(stack: PersistenceStack, graph: FamilyRepository) async throws -> [String: NSManagedObjectID] {+        let context = stack.container.viewContext+        let family = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+        context.assign(family, to: stack.sharedStore)+        family.setValue(UUID(), forKey: "id"); family.setValue("Synthetic shared memory", forKey: "name")+        try context.save()+        let familyID = family.objectID+        let child = try graph.addChild(name: "Child", familyID: familyID)+        let peer = try graph.addPerson(name: "Peer", familyID: familyID), coach = try graph.addPerson(name: "Coach", familyID: familyID)+        let connection = try graph.connect(personID: peer, childID: child)+        let source = try graph.createContext(name: "Class", familyID: familyID)+        _ = try graph.addMembership(connectionID: connection, contextID: source)+        _ = try graph.associatePerson(coach, contextID: source, role: "Coach")+        let event = try graph.createEvent(title: "Party", date: Date(timeIntervalSince1970: 1000), familyID: familyID)+        try graph.saveOrigin(connectionID: connection, input: OriginInput(contextID: source, narrative: "First account"),+                             expectedOrigin: nil)+        try graph.saveOrigin(connectionID: connection, input: OriginInput(eventID: event, narrative: "Met at the party"),+                             expectedOrigin: graph.origin(for: connection))+        try graph.setSensitiveDetails(peer, deceased: true, date: PartialDate(year: 2024, month: 2), expected: graph.sensitiveDetails(peer))+        try graph.addFamilyFact(sourceID: coach, targetID: peer, kind: .parentOf)+        try graph.addFamilyFact(sourceID: coach, targetID: peer, kind: nil, label: "Entered title")+        try graph.addAddressLabel(targetID: peer, label: "Family nickname")+        let group = try graph.createGroup(name: "Household", familyID: familyID)+        try graph.addGroupMember(peer, groupID: group, role: "Member")+        try graph.saveParticipant(eventID: event, personID: peer, roles: ["Guest"], invitation: .unknown, attendance: .attended)+        let assets = AssetRepository(stack: stack)+        let photo = try await assets.importPhoto(Self.imageData(), filename: "Synthetic.png", personID: peer)+        let pdf = try await assets.importAttachment(Self.pdfData(), filename: "Synthetic invitation.pdf", eventID: event)+        let attachment = try #require(try graph.attachments(event).first)+        try graph.addGift(eventID: event, input: GiftInput(description: "Book", givers: [coach], groups: [group],+                                                         recipients: [peer], attachments: [attachment.id], note: "Synthetic note"))+        return ["family": familyID, "photo": photo, "pdf": pdf]+    }++    private static func imageData() throws -> Data {+        let bitmap = try #require(CGContext(data: nil, width: 8, height: 8, bitsPerComponent: 8, bytesPerRow: 32,+                                           space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))+        bitmap.setFillColor(CGColor(gray: 0.5, alpha: 1)); bitmap.fill(CGRect(x: 0, y: 0, width: 8, height: 8))+        let image = try #require(bitmap.makeImage()), data = NSMutableData()+        let output = try #require(CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil))+        CGImageDestinationAddImage(output, image, nil)+        #expect(CGImageDestinationFinalize(output))+        return data as Data+    }++    private static func pdfData() throws -> Data {+        let data = NSMutableData(), consumer = try #require(CGDataConsumer(data: data))+        var page = CGRect(x: 0, y: 0, width: 100, height: 100)+        let pdf = try #require(CGContext(consumer: consumer, mediaBox: &page, nil))+        pdf.beginPDFPage(nil); pdf.setFillColor(CGColor(gray: 0.5, alpha: 1)); pdf.fill(page); pdf.endPDFPage(); pdf.closePDF()+        return data as Data+    }+}
Tests/HaloPersistenceTests/FamilyMemoryTests.swift Added +419 / -0
diff --git a/Tests/HaloPersistenceTests/FamilyMemoryTests.swift b/Tests/HaloPersistenceTests/FamilyMemoryTests.swiftnew file mode 100644index 0000000..e1a0216--- /dev/null+++ b/Tests/HaloPersistenceTests/FamilyMemoryTests.swift@@ -0,0 +1,419 @@+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 archivedPersonRetainsPhotoAndRejectsNewImportUntilRestored() async throws {+        try await withFixture { fixture, _ in+            let assets = AssetRepository(stack: fixture.stack)+            let photo = try await assets.importPhoto(Self.imageData(), filename: "Original.jpg", personID: fixture.person)+            let payload = try await assets.data(for: photo)+            try fixture.graph.setArchived(fixture.graph.archiveSnapshot(fixture.person), archived: true)+            await #expect(throws: MergeError.self) {+                try await assets.importPhoto(Self.imageData(width: 64), filename: "New.jpg", personID: fixture.person)+            }+            #expect(try fixture.graph.primaryPhoto(fixture.person) == photo)+            #expect(try await assets.data(for: photo) == payload)+            #expect(try fixture.stack.container.viewContext.count(for: NSFetchRequest<NSManagedObject>(entityName: "Asset")) == 1)+            try fixture.graph.setArchived(fixture.graph.archiveSnapshot(fixture.person), archived: false)+            let replacement = try await assets.importPhoto(Self.imageData(width: 64), filename: "New.jpg", personID: fixture.person)+            #expect(replacement != photo)+            #expect(try fixture.graph.primaryPhoto(fixture.person) == replacement)+            #expect(try await assets.data(for: photo) == payload)+        }+    }++    @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+    }+}
Tests/HaloPersistenceTests/GraphMigrationHistoryTests.swift Added +94 / -0
diff --git a/Tests/HaloPersistenceTests/GraphMigrationHistoryTests.swift b/Tests/HaloPersistenceTests/GraphMigrationHistoryTests.swiftnew file mode 100644index 0000000..24dd4a4--- /dev/null+++ b/Tests/HaloPersistenceTests/GraphMigrationHistoryTests.swift@@ -0,0 +1,94 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct GraphMigrationHistoryTests {+    @Test func bothV2StoresMigrateToCurrentModelPreservingGraphAndAssetIdentity() async throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let old = try PersistenceStack(directory: directory, model: PersistenceStack.loadModel(version: "HaloModelV2"))+        let graph = FamilyRepository(stack: old)+        let privateFamily = try graph.createFamily(name: "Synthetic owner")+        let context = old.container.viewContext+        let shared = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+        context.assign(shared, to: old.sharedStore)+        shared.setValue(UUID(), forKey: "id")+        shared.setValue("Synthetic participant", forKey: "name")+        try context.save()+        let payload = Data(repeating: 42, count: 100_000)+        for familyID in [privateFamily, shared.objectID] {+            let child = try graph.addChild(name: "Child", familyID: familyID)+            _ = try graph.quickCapture(name: "Friend", childID: child)+            _ = try await AssetRepository(stack: old).save(data: payload, familyID: familyID)+        }+        let before = try identities(in: old)+        for store in old.container.persistentStoreCoordinator.persistentStores {+            try old.container.persistentStoreCoordinator.remove(store)+        }+        let current = try PersistenceStack(directory: directory)+        #expect(try identities(in: current) == before)+        let currentGraph = FamilyRepository(stack: current)+        for family in try currentGraph.families() {+            let child = try #require(try currentGraph.children(in: family.id).first)+            let connection = try #require(try currentGraph.connections(for: child.id).first)+            #expect(try currentGraph.origin(for: connection.id) == nil)+            let source = try currentGraph.createContext(name: "New context", familyID: family.id)+            #expect(source.persistentStore == family.id.persistentStore)+        }+        let assets = try current.container.viewContext.fetch(NSFetchRequest<NSManagedObject>(entityName: "Asset"))+        #expect(assets.count == 2)+        for asset in assets { #expect(try await AssetRepository(stack: current).data(for: asset.objectID) == payload) }+    }++    @Test func secondCoordinatorGraphEditsRefreshOriginMembershipAndContextQueries() async throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let host = try PersistenceStack(directory: directory)+        let graph = FamilyRepository(stack: host)+        let family = try graph.createFamily(name: "Synthetic family")+        let child = try graph.addChild(name: "Child", familyID: family)+        let connection = try graph.quickCapture(name: "Friend", childID: child)+        let processor = HistoryProcessor(container: host.container,+                                         directory: directory.appendingPathComponent("History"), consumer: "host")+        _ = try await processor.process()+        let writer = try await PersistenceStack.open(+            configuration: StoreConfiguration(directory: directory, role: .appIntent, mirrorsCloud: false)+        )+        let external = FamilyRepository(stack: writer)+        let writerFamily = try #require(try external.families().first)+        let writerChild = try #require(try external.children(in: writerFamily.id).first)+        let writerConnection = try #require(try external.connections(for: writerChild.id).first)+        let source = try external.createContext(name: "Swimming", familyID: writerFamily.id)+        let membership = try external.addMembership(connectionID: writerConnection.id, contextID: source)+        try external.saveOrigin(connectionID: writerConnection.id, input: OriginInput(contextID: source, narrative: "First lesson"),+                                expectedOrigin: nil)+        #expect(try await processor.process() == 3)+        #expect(try graph.memberships(for: connection).map(\.name) == ["Swimming"])+        let origin = try #require(try graph.origin(for: connection))+        #expect(origin.narrative == "First lesson")+        let writerOrigin = try #require(try external.origin(for: writerConnection.id))+        try external.saveOrigin(connectionID: writerConnection.id, input: OriginInput(narrative: "Actually, at a playground"),+                                expectedOrigin: writerOrigin)+        try external.endMembership(membership, at: Date())+        try external.archiveContext(source, archived: true)+        #expect(try await processor.process() == 3)+        #expect(try graph.origin(for: connection)?.narrative == "Actually, at a playground")+        #expect(try graph.origin(for: connection)?.contextID == nil)+        #expect(try graph.memberships(for: connection).first?.endedAt != nil)+        #expect(try graph.contexts(in: family, includeArchived: false).isEmpty)+        try external.clearOrigin(connectionID: writerConnection.id, expectedOrigin: #require(try external.origin(for: writerConnection.id)))+        #expect(try await processor.process() == 1)+        #expect(try graph.origin(for: connection) == nil)+        #expect(try graph.connections(for: child).count == 1)+    }++    private func identities(in stack: PersistenceStack) throws -> [String: Set<UUID>] {+        var identities: [String: Set<UUID>] = [:]+        for entity in ["FamilySpace", "Person", "ChildProfile", "Connection", "Asset"] {+            let objects = try stack.container.viewContext.fetch(NSFetchRequest<NSManagedObject>(entityName: entity))+            identities[entity] = Set(objects.compactMap { $0.value(forKey: "id") as? UUID })+        }+        return identities+    }+}
Tests/HaloPersistenceTests/LocalContactLinksTests.swift Added +114 / -0
diff --git a/Tests/HaloPersistenceTests/LocalContactLinksTests.swift b/Tests/HaloPersistenceTests/LocalContactLinksTests.swiftnew file mode 100644index 0000000..3a417d5--- /dev/null+++ b/Tests/HaloPersistenceTests/LocalContactLinksTests.swift@@ -0,0 +1,114 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct LocalContactLinksTests {+    private func withStore(_ operation: (LocalContactLinks, URL) async throws -> Void) async throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        try await operation(LocalContactLinks(file: directory.appendingPathComponent("DeviceLinks/contacts.json")), directory)+    }++    @Test func linksAreLocalScopedAndSurviveReopening() async throws {+        try await withStore { store, directory in+            let family = UUID(), person = UUID(), foreign = UUID()+            let first = try await store.link("synthetic-contact-1", label: "Synthetic contact", familyID: family, personID: person)+            _ = try await store.link("synthetic-contact-2", familyID: foreign, personID: person)+            let reopened = LocalContactLinks(file: directory.appendingPathComponent("DeviceLinks/contacts.json"))+            let visible = try await reopened.links(familyID: family, personIDs: [person])+            #expect(visible == [first])+            #expect(visible.first?.label == "Synthetic contact")+            let differentPerson = try await reopened.links(familyID: family, personIDs: [UUID()])+            #expect(differentPerson.isEmpty)+        }+    }++    @Test func duplicateLinkIsIdempotentAndUnlinkPreservesOtherMappings() async throws {+        try await withStore { store, _ in+            let family = UUID(), person = UUID(), other = UUID()+            let first = try await store.link("synthetic", familyID: family, personID: person)+            let repeated = try await store.link("synthetic", familyID: family, personID: person)+            let sibling = try await store.link("synthetic", familyID: family, personID: other)+            #expect(first == repeated)+            try await store.unlink(first)+            let remaining = try await store.links(familyID: family, personIDs: [person, other])+            #expect(remaining == [sibling])+        }+    }++    @Test func malformedFileAndInvalidIdentifiersCannotOverwriteLinks() async throws {+        try await withStore { store, directory in+            let family = UUID(), person = UUID()+            await #expect(throws: LocalContactError.self) { try await store.link(" ", familyID: family, personID: person) }+            _ = try await store.link("synthetic", familyID: family, personID: person)+            let file = directory.appendingPathComponent("DeviceLinks/contacts.json")+            let invalid = Data("malformed synthetic links".utf8)+            try invalid.write(to: file, options: .atomic)+            await #expect(throws: LocalContactError.self) { try await store.link("next", familyID: family, personID: person) }+            #expect(try Data(contentsOf: file) == invalid)+            let oversized = Data(repeating: 0, count: 4_000_001)+            try oversized.write(to: file, options: .atomic)+            await #expect(throws: LocalContactError.self) { try await store.links(familyID: family, personIDs: [person]) }+            #expect(try file.resourceValues(forKeys: [.fileSizeKey]).fileSize == oversized.count)+        }+    }++    @Test func sharedActorSerializesConcurrentWindowLinks() async throws {+        try await withStore { store, _ in+            let family = UUID(), person = UUID()+            try await withThrowingTaskGroup(of: Void.self) { group in+                for number in 0..<20 {+                    group.addTask { _ = try await store.link("synthetic-\(number)", familyID: family, personID: person) }+                }+                try await group.waitForAll()+            }+            let links = try await store.links(familyID: family, personIDs: [person])+            #expect(links.count == 20)+            #expect(Set(links.map(\.contactIdentifier)).count == 20)+        }+    }++    @Test func mergeAndUndoPreserveBothContactMappingsWithoutGraphData() async throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let stack = try PersistenceStack(directory: directory)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        let graph = FamilyRepository(stack: stack)+        let familyID = try graph.createFamily(name: "Synthetic family")+        let source = try graph.addPerson(name: "Source", familyID: familyID)+        let survivor = try graph.addPerson(name: "Kept", familyID: familyID)+        let store = try stack.localContactLinks()+        let first = try graph.contactIdentity(source), second = try graph.contactIdentity(survivor)+        let family = try graph.readable(familyID, entity: "FamilySpace")+        let before = try MergeSnapshot.records(family: family, in: stack.container.viewContext)+        let sourceLink = try await store.link("synthetic-source", familyID: first.familyID, personID: first.personID)+        let survivorLink = try await store.link("synthetic-survivor", familyID: second.familyID, personID: second.personID)+        #expect(try MergeSnapshot.records(family: family, in: stack.container.viewContext) == before)+        let preview = try graph.mergePreview(sourceID: source, survivorID: survivor)+        let audit = try graph.mergePeople(preview, choices: PersonMergeChoices())+        let merged = try graph.contactIdentity(survivor)+        let links = try await store.links(familyID: merged.familyID, personIDs: merged.aliases)+        #expect(Set(links.map(\.id)) == [sourceLink.id, survivorLink.id])+        #expect(throws: MergeError.self) { try graph.contactIdentity(source) }+        try graph.undoPersonMerge(audit)+        let restoredSource = try graph.contactIdentity(source), restoredSurvivor = try graph.contactIdentity(survivor)+        let firstAgain = try await store.links(familyID: first.familyID, personIDs: restoredSource.aliases)+        let secondAgain = try await store.links(familyID: second.familyID, personIDs: restoredSurvivor.aliases)+        #expect(firstAgain == [sourceLink]); #expect(secondAgain == [survivorLink])+    }++    @Test func extensionRolesCannotOpenDeviceContactLinks() 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 person = try graph.addPerson(name: "Synthetic person", familyID: family)+        for role in [PersistenceRole.widget, .appIntent] {+            let extensionStack = try PersistenceStack(directory: directory, role: role)+            #expect(throws: GraphError.self) { try extensionStack.localContactLinks() }+            #expect(throws: GraphError.self) { try FamilyRepository(stack: extensionStack).contactIdentity(person) }+        }+    }+}
Tests/HaloPersistenceTests/MemoryMigrationTests.swift Added +74 / -0
diff --git a/Tests/HaloPersistenceTests/MemoryMigrationTests.swift b/Tests/HaloPersistenceTests/MemoryMigrationTests.swiftnew file mode 100644index 0000000..dfe8676--- /dev/null+++ b/Tests/HaloPersistenceTests/MemoryMigrationTests.swift@@ -0,0 +1,74 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct MemoryMigrationTests {+    @Test func bothV4StoresMigrateWithoutLosingOriginsRolesAndTemporalHistory() throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let previous = try PersistenceStack(directory: directory, model: PersistenceStack.loadModel(version: "HaloModelV4"))+        previous.container.viewContext.automaticallyMergesChangesFromParent = false+        let old = FamilyRepository(stack: previous)+        let owned = try old.createFamily(name: "Owner")+        let context = previous.container.viewContext+        let shared = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+        context.assign(shared, to: previous.sharedStore)+        shared.setValue(UUID(), forKey: "id")+        shared.setValue("Participant", forKey: "name")+        try context.save()+        var stablePeople: Set<UUID> = []+        for family in [owned, shared.objectID] {+            let child = try old.addChild(name: "Child", familyID: family)+            let connection = try old.quickCapture(name: "Friend", childID: child)+            let person = try old.personID(for: connection)+            stablePeople.insert(try #require(try context.existingObject(with: person).value(forKey: "id") as? UUID))+            let source = try old.createContext(name: "Swimming", familyID: family)+            _ = try old.associatePerson(person, contextID: source, role: "Coach")+            try old.saveOrigin(connectionID: connection, input: OriginInput(contextID: source, narrative: "First lesson"),+                expectedOrigin: nil)+            try old.setCloseness(.friend, connectionID: connection, expectedID: nil)+            try old.setConnectionState(.lostContact, note: "Moved", connectionID: connection, expectedID: nil)+        }+        for store in previous.container.persistentStoreCoordinator.persistentStores {+            try previous.container.persistentStoreCoordinator.remove(store)+        }+        let migrated = try PersistenceStack(directory: directory)+        migrated.container.viewContext.automaticallyMergesChangesFromParent = false+        let graph = FamilyRepository(stack: migrated)+        for family in try graph.families() {+            let child = try #require(try graph.children(in: family.id).first)+            let connection = try #require(try graph.connections(for: child.id).first)+            let person = try graph.personID(for: connection.id)+            let personUUID = try #require(try migrated.container.viewContext.existingObject(with: person).value(forKey: "id") as? UUID)+            #expect(stablePeople.contains(personUUID))+            #expect(try graph.sensitiveDetails(person).isDeceased == false)+            #expect(try graph.primaryPhoto(person) == nil)+            #expect(try graph.origin(for: connection.id)?.narrative == "First lesson")+            #expect(try graph.connectionState(connection.id).closeness == .friend)+            #expect(try graph.connectionState(connection.id).state == .lostContact)+            let source = try #require(try graph.contexts(in: family.id).first)+            #expect(try graph.contextPeople(source.id).first?.role == "Coach")+            let group = try graph.createGroup(name: "Household", familyID: family.id)+            try graph.addGroupMember(person, groupID: group)+            #expect(try graph.groupMembers(group).first?.id.persistentStore == family.id.persistentStore)+        }+    }++    @Test func currentModelKeepsCloudCompatibleOptionalInversesAndExternalBinaryStorage() throws {+        let model = try PersistenceStack.loadModel()+        for entity in model.entities {+            #expect(entity.uniquenessConstraints.isEmpty)+            for property in entity.properties { #expect(property.isOptional) }+            for relationship in entity.relationshipsByName.values {+                #expect(relationship.inverseRelationship != nil)+                #expect(relationship.deleteRule == .nullifyDeleteRule)+                #expect(!relationship.isOrdered)+            }+        }+        #expect(model.entitiesByName["Asset"]?.attributesByName["data"]?.allowsExternalBinaryDataStorage == true)+        #expect(model.entitiesByName["EventAttachment"]?.relationshipsByName["asset"]?.maxCount == 1)+        #expect(model.entitiesByName["Person"]?.relationshipsByName["primaryPhoto"]?.maxCount == 1)+        #expect(model.entitiesByName["GiftRecord"]?.relationshipsByName["givers"]?.isToMany == true)+    }+}
Tests/HaloPersistenceTests/PeopleSearchTests.swift Added +167 / -0
diff --git a/Tests/HaloPersistenceTests/PeopleSearchTests.swift b/Tests/HaloPersistenceTests/PeopleSearchTests.swiftnew file mode 100644index 0000000..c92cc9a--- /dev/null+++ b/Tests/HaloPersistenceTests/PeopleSearchTests.swift@@ -0,0 +1,167 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+struct PeopleSearchTests {+    private func withStore(_ operation: (FamilyRepository) throws -> Void) throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        let stack = try PersistenceStack(directory: directory)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        try operation(FamilyRepository(stack: stack))+    }++    @Test func structuredNamesEnrichTheSamePersonAndRoundTripSearch() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic"), person = try graph.addPerson(name: "Mia T", familyID: family)+            let before = try graph.person(person)+            try graph.updatePerson(person, input: PersonInput(name: before.name, notes: " Known at swimming ",+                needsReview: false, givenName: " Mia ", familyName: " Tran "), expected: before)+            let enriched = try graph.person(person)+            #expect(enriched.id == person && enriched.name == "Mia T")+            #expect(enriched.givenName == "Mia" && enriched.familyName == "Tran" && enriched.notes == "Known at swimming")+            #expect(!enriched.needsReview)+            let directory = try #require(graph.stack.privateStore.url?.deletingLastPathComponent())+            let reopened = FamilyRepository(stack: try PersistenceStack(directory: directory))+            let root = try #require(reopened.families().first)+            let found = try #require(reopened.people(in: root.id, search: "tra").first)+            let restored = try reopened.person(found.id)+            #expect(restored.givenName == "Mia" && restored.familyName == "Tran" && restored.name == "Mia T")+        }+    }++    @Test func staleStructuredNameEditorCannotOverwriteAnyPersonFields() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic"), person = try graph.addPerson(name: "Mia", familyID: family)+            let original = try graph.person(person)+            try graph.updatePerson(person, input: PersonInput(name: original.name, familyName: "Chen"), expected: original)+            #expect(throws: GraphError.self) {+                try graph.updatePerson(person, input: PersonInput(name: "Stale display", notes: "Stale note",+                    needsReview: false, givenName: "Stale given", familyName: "Stale family"), expected: original)+            }+            let current = try graph.person(person)+            #expect(current.name == "Mia" && current.familyName == "Chen" && current.notes.isEmpty && current.needsReview)+        }+    }++    @Test func lightweightEditsPreserveNamesAndExplicitBlankClearsWithoutChangingDisplay() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic")+            let person = try graph.addPerson(name: "Girl from swimming", familyID: family)+            try graph.updatePerson(person, input: PersonInput(name: "Girl from swimming", givenName: "Mia", familyName: "Chen"),+                                   expected: graph.person(person))+            try graph.updatePerson(person, name: "Girl from swimming", notes: "Blue swim cap", needsReview: false,+                                   expected: graph.person(person))+            #expect(try graph.person(person).givenName == "Mia" && graph.person(person).familyName == "Chen")+            try graph.updatePerson(person, input: PersonInput(name: "Girl from swimming", givenName: " \n ", familyName: ""),+                                   expected: graph.person(person))+            let current = try graph.person(person)+            #expect(current.givenName.isEmpty && current.familyName.isEmpty && current.name == "Girl from swimming")+            #expect(try graph.people(in: family, search: "Chen").isEmpty)+        }+    }++    @Test func legacyNameOnlyModelsPreserveTheirExistingEditContract() throws {+        for version in ["HaloModelV1", "HaloModelV2"] {+            let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+            defer { try? FileManager.default.removeItem(at: directory) }+            let model = try PersistenceStack.loadModel(version: version)+            let stack = try PersistenceStack(directory: directory, model: model)+            stack.container.viewContext.automaticallyMergesChangesFromParent = false+            let graph = FamilyRepository(stack: stack)+            let family = try graph.createFamily(name: "Synthetic"), person = try graph.addPerson(name: "Sparse", familyID: family)+            let original = try graph.person(person)+            #expect(original.notes.isEmpty)+            #expect(throws: GraphError.self) {+                try graph.updatePerson(person, name: "Must not change", notes: "Unavailable note", needsReview: false, expected: original)+            }+            #expect(try graph.person(person) == original)+            try graph.updatePerson(person, name: "Enriched", notes: "", needsReview: false, expected: original)+            let current = try graph.person(person)+            #expect(current.name == "Enriched" && current.givenName.isEmpty && current.familyName.isEmpty)+            #expect(throws: GraphError.self) {+                try graph.updatePerson(person, input: PersonInput(name: "Must not change", givenName: "New"), expected: current)+            }+            #expect(try graph.person(person) == current)+        }+    }++    @Test func namesEnteredTitlesAndHouseholdsMatchWithoutCrossFamilyResults() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic family"), other = try graph.createFamily(name: "Other")+            let person = try graph.addPerson(name: "Sofía", familyID: family)+            _ = try graph.addPerson(name: "Sofía", familyID: other)+            let child = try graph.addPerson(name: "Child", familyID: family)+            try graph.addAddressLabel(targetID: person, label: "姨姨")+            try graph.addFamilyFact(sourceID: person, targetID: child, kind: nil, label: "Auntie May")+            let group = try graph.createGroup(name: "River household", familyID: family)+            try graph.addGroupMember(person, groupID: group)+            _ = try graph.write { context in+                let object = try graph.record(person, entity: "Person", in: context)+                object.setValue("Chen", forKey: "familyName")+                return object+            }+            // A related person's display name deliberately matches both ends of the entered fact.+            #expect(try Set(graph.people(in: family, search: "sofi").map(\.id)) == [person, child])+            for term in ["姨", "Auntie", "River", "chen"] {+                #expect(try graph.people(in: family, search: term).map(\.id) == [person])+            }+        }+    }++    @Test func nestedContextsFindPeersAndRolesWithHistoricalMembershipRetained() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic family")+            let child = try graph.addChild(name: "Child", familyID: family)+            let connection = try graph.quickCapture(name: "Peer", childID: child)+            let peer = try graph.personID(for: connection), adult = try graph.addPerson(name: "Adult", familyID: family)+            let school = try graph.createContext(name: "River school", familyID: family)+            let classroom = try graph.createContext(name: "Prep A", familyID: family, parentID: school)+            let membership = try graph.addMembership(connectionID: connection, contextID: classroom)+            _ = try graph.associatePerson(adult, contextID: classroom, role: "Teacher")+            for term in ["Prep", "River school"] {+                #expect(try Set(graph.people(in: family, search: term).map(\.id)) == [peer, adult])+            }+            #expect(try graph.people(in: family, search: "teacher").map(\.id) == [adult])+            try graph.endMembership(membership, at: Date())+            try graph.archiveContext(classroom, archived: true)+            #expect(try Set(graph.people(in: family, search: "Prep").map(\.id)) == [peer, adult])+        }+    }++    @Test func relatedNamesSearchRetainsDeceasedExplicitlyAndExcludesRoutineSuggestions() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic family")+            let parent = try graph.addPerson(name: "Adult", familyID: family), child = try graph.addPerson(name: "Noah", familyID: family)+            try graph.addFamilyFact(sourceID: parent, targetID: child, kind: .parentOf)+            #expect(try Set(graph.people(in: family, search: "Noah").map(\.id)) == [parent, child])+            #expect(try graph.people(in: family, search: "parentOf").map(\.id) == [parent])+            #expect(try graph.people(in: family, search: "Parent of").map(\.id) == [parent])+            try graph.setSensitiveDetails(parent, deceased: true, date: PartialDate(year: 2024), expected: graph.sensitiveDetails(parent))+            #expect(try graph.people(in: family, search: "Parent").contains { $0.id == parent })+            #expect(try graph.people(in: family, search: "Parent", includeDeceased: false).contains { $0.id == parent } == false)+        }+    }++    @Test func personRolesShowMultipleDatedAndArchivedAssociationsWithStaleEditGuard() throws {+        try withStore { graph in+            let family = try graph.createFamily(name: "Synthetic family")+            let person = try graph.addPerson(name: "Adult", familyID: family)+            let context = try graph.createContext(name: "Swimming", familyID: family)+            _ = try graph.associatePerson(person, contextID: context, role: "Coach", startedAt: Date(timeIntervalSince1970: 1000))+            _ = try graph.associatePerson(person, contextID: context, role: "Parent")+            let roles = try graph.personContextRoles(person)+            #expect(Set(roles.map { $0.association.role }) == ["Coach", "Parent"])+            let original = try #require(roles.first { $0.association.role == "Coach" }?.association)+            try graph.archiveContext(context, archived: true)+            #expect(try graph.personContextRoles(person).allSatisfy(\.isArchived))+            try graph.updateRole(original.id, role: "Head coach", startedAt: original.startedAt,+                                          endedAt: nil, expected: original)+            #expect(throws: GraphError.self) {+                try graph.updateRole(original.id, role: "Stale", startedAt: nil, endedAt: nil, expected: original)+            }+            #expect(try graph.personContextRoles(person).contains { $0.association.role == "Head coach" })+        }+    }+}
Tests/HaloPersistenceTests/PersonMergeTests.swift Added +599 / -0
diff --git a/Tests/HaloPersistenceTests/PersonMergeTests.swift b/Tests/HaloPersistenceTests/PersonMergeTests.swiftnew file mode 100644index 0000000..5e07228--- /dev/null+++ b/Tests/HaloPersistenceTests/PersonMergeTests.swift@@ -0,0 +1,599 @@+import CoreData+import Testing+@testable import HaloPersistence++@MainActor+private struct MergeFixture {+    let stack: PersistenceStack+    let graph: FamilyRepository+    let family: NSManagedObjectID+    let source: NSManagedObjectID+    let survivor: NSManagedObjectID++    init(directory: URL, shared: Bool = false, model: NSManagedObjectModel? = nil) throws {+        stack = try PersistenceStack(directory: directory, model: model)+        stack.container.viewContext.automaticallyMergesChangesFromParent = false+        graph = FamilyRepository(stack: stack)+        if shared {+            let context = stack.container.viewContext+            let family = NSEntityDescription.insertNewObject(forEntityName: "FamilySpace", into: context)+            context.assign(family, to: stack.sharedStore)+            family.setValue(UUID(), forKey: "id"); family.setValue("Synthetic shared family", forKey: "name")+            try context.save(); self.family = family.objectID+        } else { family = try graph.createFamily(name: "Synthetic family") }+        source = try graph.addPerson(name: "Sophie C", familyID: family)+        survivor = try graph.addPerson(name: "Sophie Chen", familyID: family)+    }+}++@MainActor+struct PersonMergeTests {+    private func withFixture(shared: Bool = false,+                             _ body: @MainActor (MergeFixture, URL) async throws -> Void) async throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        try await body(MergeFixture(directory: directory, shared: shared), directory)+    }++    private func choices(_ preview: PersonMergePreview) -> PersonMergeChoices {+        var choices = PersonMergeChoices()+        for overlap in preview.overlaps {+            choices.connections[overlap.id] = MergeConnectionChoices(originID: overlap.origins.first?.id,+                closenessID: overlap.closeness.first?.id, statusID: overlap.statuses.first?.id)+        }+        return choices+    }++    @Test func structuredNameChoicesRemainSearchableAndUndoRestoresBothPeople() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            try graph.updatePerson(fixture.source,+                input: PersonInput(name: "Sophie C", givenName: "Sophia", familyName: "Chen"), expected: graph.person(fixture.source))+            try graph.updatePerson(fixture.survivor,+                input: PersonInput(name: "Sophie T", givenName: "Sophie", familyName: "Tran"), expected: graph.person(fixture.survivor))+            let beforeSource = try graph.person(fixture.source), beforeSurvivor = try graph.person(fixture.survivor)+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            #expect(preview.source.givenName == "Sophia" && preview.survivor.familyName == "Tran")+            var selected = choices(preview)+            selected.name = .source; selected.givenName = .survivor; selected.familyName = .source+            let audit = try graph.mergePeople(preview, choices: selected)+            let kept = try graph.person(fixture.survivor)+            #expect(kept.name == "Sophie C" && kept.givenName == "Sophie" && kept.familyName == "Chen")+            #expect(try graph.people(in: fixture.family, search: "Chen").map(\.id) == [fixture.survivor])+            try graph.undoPersonMerge(audit)+            #expect(try graph.person(fixture.source) == beforeSource)+            #expect(try graph.person(fixture.survivor) == beforeSurvivor)+        }+    }++    @Test func suggestionsNeverMergeOrSuppressValidSameNamePeople() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let sameName = try graph.addPerson(name: "Sophie Chen", familyID: fixture.family)+            let before = try graph.people(in: fixture.family)+            let pairs = try graph.likelyDuplicates(in: fixture.family)+            #expect(pairs.contains { Set([$0.source.id, $0.survivor.id]) == [fixture.source, fixture.survivor] })+            #expect(pairs.contains { Set([$0.source.id, $0.survivor.id]) == [fixture.survivor, sameName] })+            #expect(try graph.people(in: fixture.family) == before)+            #expect(try graph.mergeHistory(in: fixture.family).isEmpty)+            try graph.setSensitiveDetails(sameName, deceased: true, date: PartialDate(), expected: graph.sensitiveDetails(sameName))+            #expect(try graph.likelyDuplicates(in: fixture.family).allSatisfy { $0.source.id != sameName && $0.survivor.id != sameName })+        }+    }++    @Test func mergeRepointsAllReferenceKindsAndUndoRestoresStableRecordsInBothStores() async throws {+        for shared in [false, true] {+            try await withFixture(shared: shared) { fixture, _ in+                let graph = fixture.graph, source = fixture.source, survivor = fixture.survivor+                let firstChild = try graph.addChild(name: "Alex", familyID: fixture.family)+                let secondChild = try graph.addChild(name: "Robin", familyID: fixture.family)+                let first = try graph.connect(personID: source, childID: firstChild)+                let second = try graph.connect(personID: survivor, childID: secondChild)+                let contextID = try graph.createContext(name: "Swimming", familyID: fixture.family)+                let role = try graph.associatePerson(source, contextID: contextID, role: "Coach")+                try graph.saveOrigin(connectionID: first, input: OriginInput(contextID: contextID, narrative: "Lesson"),+                                     expectedOrigin: nil)+                let relative = try graph.addPerson(name: "Relative", familyID: fixture.family)+                try graph.addFamilyFact(sourceID: source, targetID: relative, kind: .parentOf)+                try graph.addFamilyFact(sourceID: relative, targetID: source, kind: nil, label: "Auntie")+                let group = try graph.createGroup(name: "Household", familyID: fixture.family)+                try graph.addGroupMember(source, groupID: group)+                try graph.addAddressLabel(targetID: source, label: "Auntie Sophie", usedByPerson: relative)+                let event = try graph.createEvent(title: "Party", date: Date(), familyID: fixture.family)+                let originalEvent = try graph.event(event)+                try graph.updateEvent(event, title: originalEvent.title, date: originalEvent.date, notes: "",+                                      links: (source, contextID), expected: originalEvent)+                try graph.saveParticipant(eventID: event, personID: source,+                    roles: ["guest"], invitation: .accepted, attendance: .didNotAttend)+                try graph.addGift(eventID: event,+                                  input: GiftInput(description: "Book", givers: [source, survivor], recipients: [relative, source]))+                let assets = AssetRepository(stack: fixture.stack)+                let photo = try await assets.save(data: Data([1, 2, 3]), familyID: fixture.family)+                let otherPhoto = try await assets.save(data: Data([4, 5]), familyID: fixture.family)+                _ = try graph.write { context in+                    let sourcePerson = try graph.record(source, entity: "Person", in: context)+                    let survivorPerson = try graph.record(survivor, entity: "Person", in: context)+                    sourcePerson.setValue(try graph.record(photo, entity: "Asset", in: context), forKey: "primaryPhoto")+                    survivorPerson.setValue(try graph.record(otherPhoto, entity: "Asset", in: context), forKey: "primaryPhoto")+                    sourcePerson.setValue("Source note", forKey: "notes"); survivorPerson.setValue("Kept note", forKey: "notes")+                    return sourcePerson+                }+                let family = try graph.readable(fixture.family, entity: "FamilySpace")+                let before = try MergeSnapshot.records(family: family, in: fixture.stack.container.viewContext)+                let preview = try graph.mergePreview(sourceID: source, survivorID: survivor)+                #expect(preview.overlaps.isEmpty)+                var selection = choices(preview); selection.photo = .source+                let audit = try graph.mergePeople(preview, choices: selection)+                #expect(try graph.people(in: fixture.family).contains { $0.id == source } == false)+                #expect(try graph.mergedPersonTarget(source) == survivor)+                #expect(try Set(graph.connections(to: survivor).map(\.id)) == [first, second])+                #expect(try graph.origin(for: first)?.narrative == "Lesson")+                #expect(try graph.contextPeople(contextID).first?.id == role)+                #expect(try graph.contextPeople(contextID).first?.personID == survivor)+                #expect(try graph.familyFacts(for: survivor).count == 2)+                #expect(try graph.groupMembers(group).first?.personID == survivor)+                #expect(try graph.addressLabels(for: survivor).first?.label == "Auntie Sophie")+                #expect(try graph.event(event).subjectID == survivor)+                #expect(try graph.participants(event).first?.personID == survivor)+                #expect(try graph.gifts(event).first?.giverIDs == [survivor])+                #expect(try graph.primaryPhoto(survivor) == photo)+                #expect(try graph.person(survivor).notes == "Kept note\n\nSource note")+                #expect(try await assets.data(for: otherPhoto) == Data([4, 5]))+                #expect(audit.persistentStore == fixture.family.persistentStore)+                try graph.undoPersonMerge(audit)+                #expect(try MergeSnapshot.records(family: family, in: fixture.stack.container.viewContext) == before)+                #expect(try await assets.data(for: photo) == Data([1, 2, 3]))+                #expect(try graph.mergeHistory(in: fixture.family).first?.undone == true)+                #expect(throws: MergeError.self) { try graph.undoPersonMerge(audit) }+            }+        }+    }++    @Test func overlappingConnectionsRequireChoicesAndRetainAllOriginsMembershipsAndStateHistory() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let child = try graph.addChild(name: "Child", familyID: fixture.family)+            let first = try graph.connect(personID: fixture.source, childID: child)+            let second = try graph.connect(personID: fixture.survivor, childID: child)+            let source = try graph.createContext(name: "School", familyID: fixture.family)+            let other = try graph.createContext(name: "Playgroup", familyID: fixture.family)+            try graph.addMembership(connectionID: first, contextID: source)+            try graph.addMembership(connectionID: second, contextID: other)+            try graph.saveOrigin(connectionID: first, input: OriginInput(contextID: source, narrative: "First lesson"), expectedOrigin: nil)+            try graph.saveOrigin(connectionID: second, input: OriginInput(contextID: other, narrative: "First playdate"),+                                 expectedOrigin: nil)+            try graph.setCloseness(.knowThem, connectionID: first, expectedID: nil)+            try graph.setCloseness(.goodFriend, connectionID: second, expectedID: nil)+            try graph.setConnectionState(.lostContact, note: "Moved away", connectionID: first, expectedID: nil)+            try graph.setConnectionState(.active, note: "See at school", connectionID: second, expectedID: nil)+            let originalHead = try #require(try graph.originHistory(for: first).first)+            let family = try graph.readable(fixture.family, entity: "FamilySpace")+            let before = try MergeSnapshot.records(family: family, in: fixture.stack.container.viewContext)+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            let overlap = try #require(preview.overlaps.first)+            #expect(throws: MergeError.self) { try graph.mergePeople(preview, choices: PersonMergeChoices()) }+            #expect(try MergeSnapshot.records(family: family, in: fixture.stack.container.viewContext) == before)+            var selected = choices(preview)+            selected.connections[overlap.id] = MergeConnectionChoices(+                originID: overlap.origins.first { $0.contextID == source }?.id,+                closenessID: overlap.closeness.first { $0.value == 7 }?.id,+                statusID: overlap.statuses.first { $0.state == .lostContact }?.id)+            let audit = try graph.mergePeople(preview, choices: selected)+            #expect(try graph.connections(for: child).map(\.id) == [second])+            #expect(try graph.memberships(for: second).count == 2)+            #expect(try graph.origin(for: second)?.contextID == source)+            #expect(try graph.originHistory(for: first).first?.stableID == originalHead.stableID)+            #expect(try graph.originHistory(for: second).count == 3)+            #expect(try graph.connectionState(second).closeness == .goodFriend)+            #expect(try graph.connectionState(second).note == "Moved away")+            #expect(try graph.archivedMergeConnections(audit).map(\.id) == [first])+            try graph.undoPersonMerge(audit)+            #expect(try MergeSnapshot.records(family: family, in: fixture.stack.container.viewContext) == before)+            #expect(try graph.origin(for: second)?.contextID == other)+        }+    }++    @Test func childProfileMergeConsolidatesPeerConnectionsAndUndoRestoresBothProfiles() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let firstChild = try graph.addChild(name: "Alex old capture", familyID: fixture.family)+            let keptChild = try graph.addChild(name: "Alex", familyID: fixture.family)+            let firstProfile = try graph.readable(firstChild, entity: "ChildProfile")+            let keptProfile = try graph.readable(keptChild, entity: "ChildProfile")+            let firstPerson = try #require(firstProfile.value(forKey: "person") as? NSManagedObject)+            let keptPerson = try #require(keptProfile.value(forKey: "person") as? NSManagedObject)+            let peer = try graph.addPerson(name: "Peer", familyID: fixture.family)+            let first = try graph.connect(personID: peer, childID: firstChild)+            let kept = try graph.connect(personID: peer, childID: keptChild)+            try graph.saveOrigin(connectionID: first, input: OriginInput(narrative: "Playgroup"), expectedOrigin: nil)+            try graph.saveOrigin(connectionID: kept, input: OriginInput(narrative: "School"), expectedOrigin: nil)+            let preview = try graph.mergePreview(sourceID: firstPerson.objectID, survivorID: keptPerson.objectID)+            #expect(preview.combinesChildProfiles)+            #expect(preview.overlaps.count == 1)+            let audit = try graph.mergePeople(preview, choices: choices(preview))+            #expect(try graph.children(in: fixture.family).map(\.id) == [keptChild])+            #expect(try graph.connections(for: keptChild).map(\.id) == [kept])+            #expect(try graph.readable(firstChild, entity: "ChildProfile").value(forKey: "archivedAt") != nil)+            try graph.undoPersonMerge(audit)+            #expect(Set(try graph.children(in: fixture.family).map(\.id)) == [firstChild, keptChild])+            #expect(try graph.connections(for: firstChild).map(\.id) == [first])+        }+    }++    @Test func stalePreviewRejectsChangesButUnrelatedEditsAfterMergeSurviveUndo() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let other = try graph.addPerson(name: "Other", familyID: fixture.family)+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            try graph.updatePerson(other, name: "Other", notes: "Independent before merge", needsReview: false,+                                   expected: graph.person(other))+            #expect(throws: MergeError.self) { try graph.mergePeople(preview, choices: choices(preview)) }+            let fresh = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            let audit = try graph.mergePeople(fresh, choices: choices(fresh))+            try graph.updatePerson(other, name: "Other", notes: "Independent after merge", needsReview: false,+                                   expected: graph.person(other))+            #expect(try graph.mergeHistory(in: fixture.family).first?.undoAvailable == true)+            try graph.undoPersonMerge(audit)+            #expect(try graph.person(other).notes == "Independent after merge")+        }+    }++    @Test func affectedEditsAndNewReferencesMakeUndoUnavailable() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            let audit = try graph.mergePeople(preview, choices: choices(preview))+            let child = try graph.addChild(name: "Child", familyID: fixture.family)+            let connection = try graph.connect(personID: fixture.survivor, childID: child)+            #expect(try graph.mergeHistory(in: fixture.family).first?.undoAvailable == false)+            #expect(throws: MergeError.self) { try graph.undoPersonMerge(audit) }+            #expect(try graph.connections(for: child).map(\.id) == [connection])+            #expect(try graph.mergedPersonTarget(fixture.source) == fixture.survivor)+            #expect(throws: MergeError.self) {+                try graph.updatePerson(fixture.source, name: "Stale hidden person", notes: "", needsReview: false,+                                       expected: graph.person(fixture.source))+            }+        }+    }++    @Test func selfFactsAreArchivedAndCompetingEventAccountsRemainSeparate() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            try graph.addFamilyFact(sourceID: fixture.source, targetID: fixture.survivor, kind: .parentOf)+            let event = try graph.createEvent(title: "Party", date: Date(), familyID: fixture.family)+            try graph.saveParticipant(eventID: event, personID: fixture.source,+                roles: ["host"], invitation: .accepted, attendance: .attended, note: "First account")+            try graph.saveParticipant(eventID: event, personID: fixture.survivor,+                roles: ["guest"], invitation: .declined, attendance: .didNotAttend, note: "Second account")+            let before = try graph.participants(event)+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            #expect(preview.selfRelationships == 1)+            #expect(preview.duplicateEventAccounts == 1)+            let audit = try graph.mergePeople(preview, choices: choices(preview))+            #expect(try graph.familyFacts(for: fixture.survivor).isEmpty)+            #expect(try graph.familyFacts(for: fixture.survivor, includeArchived: true).first?.isArchived == true)+            #expect(try graph.derivedKinship(for: fixture.survivor).isEmpty)+            let after = try graph.participants(event)+            #expect(Set(after.map(\.id)) == Set(before.map(\.id)))+            #expect(Set(after.map(\.note)) == ["First account", "Second account"])+            #expect(after.allSatisfy { $0.personID == fixture.survivor })+            try graph.undoPersonMerge(audit)+            #expect(try graph.familyFacts(for: fixture.source).first?.targetID == fixture.survivor)+            #expect(Set(try graph.participants(event).map(\.personID)) == [fixture.source, fixture.survivor])+        }+    }++    @Test func invalidFamilyAndReadOnlyMergeNeverWrite() async throws {+        try await withFixture { fixture, directory in+            let graph = fixture.graph+            let foreignFamily = try graph.createFamily(name: "Other family")+            let foreign = try graph.addPerson(name: "Other Sophie", familyID: foreignFamily)+            #expect(throws: GraphError.self) { try graph.mergePreview(sourceID: fixture.source, survivorID: foreign) }+            #expect(throws: MergeError.self) { try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.source) }+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            let widget = try PersistenceStack(directory: directory, role: .widget)+            #expect(throws: GraphError.self) { try FamilyRepository(stack: widget).mergePeople(preview, choices: choices(preview)) }+            #expect(try graph.mergeHistory(in: fixture.family).isEmpty)+        }+    }++    @Test func corruptedUndoHistoryCannotDeleteOrChangePeople() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            let audit = try graph.mergePeople(preview, choices: choices(preview))+            _ = try graph.write { context in+                let row = try graph.record(audit, entity: "PersonMerge", in: context)+                row.setValue(Data("corrupted history".utf8), forKey: "beforeData")+                return row+            }+            #expect(throws: MergeError.self) { try graph.undoPersonMerge(audit) }+            #expect(try graph.mergedPersonTarget(fixture.source) == fixture.survivor)+            #expect(try graph.people(in: fixture.family).map(\.id) == [fixture.survivor])+        }+    }++    @Test func staleConnectionEditorsAndMergedChildCaptureCannotWriteHiddenRecords() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let firstChild = try graph.addChild(name: "Child", familyID: fixture.family)+            let secondChild = try graph.addChild(name: "Child duplicate", familyID: fixture.family)+            let source = try #require(try graph.readable(firstChild, entity: "ChildProfile").value(forKey: "person") as? NSManagedObject)+            let survivor = try #require(try graph.readable(secondChild, entity: "ChildProfile").value(forKey: "person") as? NSManagedObject)+            let first = try graph.connect(personID: fixture.source, childID: firstChild)+            let second = try graph.connect(personID: fixture.source, childID: secondChild)+            let context = try graph.createContext(name: "Class", familyID: fixture.family)+            let membership = try graph.addMembership(connectionID: first, contextID: context)+            let preview = try graph.mergePreview(sourceID: source.objectID, survivorID: survivor.objectID)+            _ = try graph.mergePeople(preview, choices: choices(preview))+            #expect(throws: MergeError.self) { try graph.quickCapture(name: "Stale capture", childID: firstChild) }+            #expect(throws: MergeError.self) {+                try graph.saveOrigin(connectionID: first, input: OriginInput(narrative: "Stale draft"), expectedOrigin: nil)+            }+            #expect(throws: MergeError.self) { try graph.setCloseness(.bff, connectionID: first, expectedID: nil) }+            #expect(try graph.connections(for: secondChild).map(\.id) == [second])+            // Memberships move to the kept connection, so their own retained ID remains useful.+            try graph.endMembership(membership, at: Date())+            #expect(try graph.memberships(for: second).first?.endedAt != nil)+        }+    }++    @Test func childPeerDuplicateBecomesArchivedSelfConnectionAndUndoRestoresIt() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let child = try graph.addChild(name: "Child", familyID: fixture.family)+            let childPerson = try #require(try graph.readable(child, entity: "ChildProfile").value(forKey: "person") as? NSManagedObject)+            let connection = try graph.connect(personID: fixture.source, childID: child)+            try graph.saveOrigin(connectionID: connection, input: OriginInput(narrative: "Earlier account"), expectedOrigin: nil)+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: childPerson.objectID)+            #expect(preview.selfConnections == [connection])+            let audit = try graph.mergePeople(preview, choices: choices(preview))+            #expect(try graph.connections(for: child).isEmpty)+            #expect(try graph.origin(for: connection)?.narrative == "Earlier account")+            #expect(throws: MergeError.self) { try graph.setConnectionState(.active, note: "", connectionID: connection, expectedID: nil) }+            #expect(try graph.archivedMergeConnections(audit).map(\.id) == [connection])+            try graph.undoPersonMerge(audit)+            #expect(try graph.connections(for: child).map(\.id) == [connection])+            #expect(try graph.personID(for: connection) == fixture.source)+        }+    }++    @Test func lateImportedAccountsStayVisibleAndBecomeReviewableAlternatives() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let child = try graph.addChild(name: "Child", familyID: fixture.family)+            let first = try graph.connect(personID: fixture.source, childID: child)+            let kept = try graph.connect(personID: fixture.survivor, childID: child)+            try graph.saveOrigin(connectionID: first, input: OriginInput(narrative: "First account"), expectedOrigin: nil)+            try graph.saveOrigin(connectionID: kept, input: OriginInput(narrative: "Kept account"), expectedOrigin: nil)+            try graph.setConnectionState(.active, note: "", connectionID: first, expectedID: nil)+            try graph.setConnectionState(.active, note: "", connectionID: kept, expectedID: nil)+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            _ = try graph.mergePeople(preview, choices: choices(preview))+            #expect(try graph.lateMergeAccounts(in: fixture.family).isEmpty)+            // Simulate imported rows; local editors are intentionally unable to write this archived connection.+            let late = try graph.write { context in+                let connection = try context.existingObject(with: first)+                let proposal = try graph.makeProposal(input: OriginInput(narrative: "Offline account"), cleared: false,+                    connection: connection, predecessors: [], in: context)+                let family = try graph.family(of: connection)+                let period = graph.insert("ConnectionStatusPeriod", in: context, store: try graph.owningStore(of: family))+                period.setValue(family, forKey: "familySpace"); period.setValue(connection, forKey: "connection")+                period.setValue(Date(), forKey: "startedAt"); period.setValue(ConnectionState.lostContact.rawValue, forKey: "state")+                period.setValue("Offline status", forKey: "note")+                return proposal+            }+            let review = try #require(try graph.lateMergeAccounts(in: fixture.family).first)+            #expect(review.id == first && review.targetID == kept)+            _ = try graph.write { context in+                try graph.makeProposal(input: OriginInput(narrative: "Another unseen account"), cleared: false,+                    connection: context.existingObject(with: first), predecessors: [], in: context)+            }+            #expect(throws: MergeError.self) { try graph.reviewLateMergeAccounts(review) }+            let freshReview = try #require(try graph.lateMergeAccounts(in: fixture.family).first)+            try graph.reviewLateMergeAccounts(freshReview)+            #expect(try graph.lateMergeAccounts(in: fixture.family).isEmpty)+            let copied = try graph.originHistory(for: kept).map(\.id)+            #expect(throws: MergeError.self) { try graph.reviewLateMergeAccounts(freshReview) }+            #expect(try graph.originHistory(for: kept).map(\.id) == copied)+            #expect(try graph.originHistory(for: first).contains { $0.id == late })+            #expect(try graph.originOverview(for: kept).conflicts.contains { $0.narrative == "Offline account" })+            #expect(try graph.connectionState(kept).statusNeedsReview)+            #expect(try graph.reviewConnections(in: fixture.family).contains { $0.id == kept })+            #expect(throws: MergeError.self) { try graph.undoPersonMerge(try #require(graph.mergeHistory(in: fixture.family).first?.id)) }+        }+    }++    @Test func opposingOfflineMergesExposePeopleAndRecoverWithoutOverwritingReferences() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+            defer { try? FileManager.default.removeItem(at: directory) }+            let peer = try MergeFixture(directory: directory)+            let originalFamily = try graph.readable(fixture.family, entity: "FamilySpace")+            let sourceUUID = try graph.stable(graph.readable(fixture.source, entity: "Person"))+            let survivorUUID = try graph.stable(graph.readable(fixture.survivor, entity: "Person"))+            _ = try peer.graph.write { context in+                let family = try context.existingObject(with: peer.family)+                family.setValue(try graph.stable(originalFamily), forKey: "id")+                try context.existingObject(with: peer.source).setValue(sourceUUID, forKey: "id")+                try context.existingObject(with: peer.survivor).setValue(survivorUUID, forKey: "id")+                return family+            }+            let first = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            let opposite = try peer.graph.mergePreview(sourceID: peer.survivor, survivorID: peer.source)+            let firstAudit = try graph.mergePeople(first, choices: choices(first))+            let peerAuditID = try peer.graph.mergePeople(opposite, choices: choices(opposite))+            let peerAudit = try peer.graph.readable(peerAuditID, entity: "PersonMerge")+            let child = try graph.addChild(name: "Unrelated child", familyID: fixture.family)+            let connection = try graph.connect(personID: fixture.survivor, childID: child)+            _ = try graph.write { context in+                let family = try context.existingObject(with: fixture.family)+                let audit = graph.insert("PersonMerge", in: context, store: try graph.owningStore(of: family))+                for key in peerAudit.entity.attributesByName.keys { audit.setValue(peerAudit.value(forKey: key), forKey: key) }+                audit.setValue(family, forKey: "familySpace")+                let survivor = try context.existingObject(with: fixture.survivor)+                survivor.setValue(try context.existingObject(with: fixture.source), forKey: "mergedInto")+                survivor.setValue(Date(), forKey: "archivedAt")+                return audit+            }+            let conflict = try #require(try graph.mergeConflicts(in: fixture.family).first)+            #expect(Set(conflict.people.map(\.id)) == [fixture.source, fixture.survivor])+            #expect(try graph.people(in: fixture.family).contains { $0.id == fixture.source })+            #expect(try graph.people(in: fixture.family).contains { $0.id == fixture.survivor })+            #expect(throws: MergeError.self) { try graph.undoPersonMerge(firstAudit) }+            _ = try graph.addPerson(name: "Intervening independent capture", familyID: fixture.family)+            #expect(throws: MergeError.self) { try graph.recoverCompetingMerges(conflict) }+            let refreshed = try #require(try graph.mergeConflicts(in: fixture.family).first)+            try graph.recoverCompetingMerges(refreshed)+            #expect(try graph.mergeConflicts(in: fixture.family).isEmpty)+            #expect(try graph.mergedPersonTarget(fixture.source) == nil)+            #expect(try graph.mergedPersonTarget(fixture.survivor) == nil)+            #expect(try graph.personID(for: connection) == fixture.survivor)+            #expect(try graph.mergeHistory(in: fixture.family).count == 2)+            #expect(try graph.mergeHistory(in: fixture.family).allSatisfy { !$0.undone })+        }+    }++    @Test func sequentialMergesRemainValidWithoutInventingAConflict() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let third = try graph.addPerson(name: "Third identity", familyID: fixture.family)+            let first = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            _ = try graph.mergePeople(first, choices: choices(first))+            let next = try graph.mergePreview(sourceID: fixture.survivor, survivorID: third)+            _ = try graph.mergePeople(next, choices: choices(next))+            #expect(try graph.mergeConflicts(in: fixture.family).isEmpty)+            #expect(try graph.mergedPersonTarget(fixture.source) == third)+        }+    }++    @Test func aliasesBeforeAuditsAndDelayedRecoveryAliasesCannotHidePeople() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            _ = try graph.write { context in+                let source = try context.existingObject(with: fixture.source)+                let survivor = try context.existingObject(with: fixture.survivor)+                source.setValue(survivor, forKey: "mergedInto"); survivor.setValue(source, forKey: "mergedInto")+                source.setValue(Date(), forKey: "archivedAt"); survivor.setValue(Date(), forKey: "archivedAt")+                return source+            }+            let conflict = try #require(try graph.mergeConflicts(in: fixture.family).first)+            #expect(conflict.mergeIDs.isEmpty)+            #expect(try graph.people(in: fixture.family).count == 2)+            try graph.recoverCompetingMerges(conflict)+            #expect(try graph.mergeConflicts(in: fixture.family).isEmpty)+            _ = try graph.write { context in+                let source = try context.existingObject(with: fixture.source)+                source.setValue(try context.existingObject(with: fixture.survivor), forKey: "mergedInto")+                source.setValue(Date(), forKey: "archivedAt")+                return source+            }+            let delayed = try #require(try graph.mergeConflicts(in: fixture.family).first)+            #expect(try graph.people(in: fixture.family).count == 2)+            try graph.recoverCompetingMerges(delayed)+            // A new explicit merge acknowledges both recoveries and is allowed; old aliases cannot do so.+            let fresh = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            _ = try graph.mergePeople(fresh, choices: choices(fresh))+            #expect(try graph.mergeConflicts(in: fixture.family).isEmpty)+            #expect(try graph.people(in: fixture.family).map(\.id) == [fixture.survivor])+        }+    }++    @Test func repeatedOriginOnlyReviewsPreserveUnchangedPeriodsAndMemberships() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let child = try graph.addChild(name: "Child", familyID: fixture.family)+            let first = try graph.connect(personID: fixture.source, childID: child)+            let kept = try graph.connect(personID: fixture.survivor, childID: child)+            try graph.saveOrigin(connectionID: first, input: OriginInput(narrative: "Earlier"), expectedOrigin: nil)+            try graph.saveOrigin(connectionID: kept, input: OriginInput(narrative: "Kept"), expectedOrigin: nil)+            try graph.setCloseness(.knowThem, connectionID: first, expectedID: nil)+            try graph.setCloseness(.goodFriend, connectionID: kept, expectedID: nil)+            try graph.setConnectionState(.lostContact, note: "", connectionID: first, expectedID: nil)+            try graph.setConnectionState(.active, note: "", connectionID: kept, expectedID: nil)+            let group = try graph.createContext(name: "Class", familyID: fixture.family)+            _ = try graph.addMembership(connectionID: first, contextID: group)+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            _ = try graph.mergePeople(preview, choices: choices(preview))+            let statuses = try graph.currentStatePeriods(kept, closeness: false).map(\.id)+            let closeness = try graph.currentStatePeriods(kept, closeness: true).map(\.id)+            let memberships = try graph.memberships(for: kept).map(\.id)+            for narrative in ["Late one", "Late two"] {+                _ = try graph.write { context in+                    try graph.makeProposal(input: OriginInput(narrative: narrative), cleared: false,+                        connection: context.existingObject(with: first), predecessors: [], in: context)+                }+                let review = try #require(try graph.lateMergeAccounts(in: fixture.family).first)+                try graph.reviewLateMergeAccounts(review)+                #expect(try graph.currentStatePeriods(kept, closeness: false).map(\.id) == statuses)+                #expect(try graph.currentStatePeriods(kept, closeness: true).map(\.id) == closeness)+                #expect(try graph.memberships(for: kept).map(\.id) == memberships)+            }+        }+    }++    @Test func lateStatusWithoutOriginDoesNotInventAFirstMeetingClear() async throws {+        try await withFixture { fixture, _ in+            let graph = fixture.graph+            let child = try graph.addChild(name: "Child", familyID: fixture.family)+            let first = try graph.connect(personID: fixture.source, childID: child)+            let kept = try graph.connect(personID: fixture.survivor, childID: child)+            try graph.saveOrigin(connectionID: kept, input: OriginInput(narrative: "Known first meeting"), expectedOrigin: nil)+            try graph.setConnectionState(.active, note: "", connectionID: first, expectedID: nil)+            try graph.setConnectionState(.active, note: "", connectionID: kept, expectedID: nil)+            let preview = try graph.mergePreview(sourceID: fixture.source, survivorID: fixture.survivor)+            let overlap = try #require(preview.overlaps.first)+            var selected = choices(preview)+            selected.connections[overlap.id]?.originID = overlap.origins.first { $0.narrative == "Known first meeting" }?.id+            _ = try graph.mergePeople(preview, choices: selected)+            let originalHeads = try graph.originOverview(for: kept).headIDs+            _ = try graph.write { context in+                let connection = try context.existingObject(with: first)+                let family = try graph.family(of: connection)+                let period = graph.insert("ConnectionStatusPeriod", in: context, store: try graph.owningStore(of: family))+                period.setValue(family, forKey: "familySpace"); period.setValue(connection, forKey: "connection")+                period.setValue(Date(), forKey: "startedAt"); period.setValue(ConnectionState.lostContact.rawValue, forKey: "state")+                return period+            }+            let late = try #require(try graph.lateMergeAccounts(in: fixture.family).first)+            try graph.reviewLateMergeAccounts(late)+            #expect(try graph.originOverview(for: kept).headIDs == originalHeads)+            #expect(try graph.origin(for: kept)?.narrative == "Known first meeting")+            #expect(try graph.connectionState(kept).statusNeedsReview)+        }+    }++    @Test func bothV5StoresMigrateWithStableRecordsAndMergeSurvivesRelaunch() async throws {+        for shared in [false, true] {+            let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+            defer { try? FileManager.default.removeItem(at: directory) }+            let old = try MergeFixture(directory: directory, shared: shared, model: PersistenceStack.loadModel(version: "HaloModelV5"))+            let uuids = try [old.source, old.survivor].map { try old.graph.stable(old.graph.readable($0, entity: "Person")) }+            for store in old.stack.container.persistentStoreCoordinator.persistentStores {+                try old.stack.container.persistentStoreCoordinator.remove(store)+            }+            let migrated = try PersistenceStack(directory: directory)+            migrated.container.viewContext.automaticallyMergesChangesFromParent = false+            let graph = FamilyRepository(stack: migrated)+            let family = try #require(try graph.families().first)+            let people = try graph.people(in: family.id)+            let ids = try people.map { try graph.stable(graph.readable($0.id, entity: "Person")) }+            #expect(Set(ids) == Set(uuids))+            let source = try #require(people.first { $0.name == "Sophie C" })+            let survivor = try #require(people.first { $0.name == "Sophie Chen" })+            let preview = try graph.mergePreview(sourceID: source.id, survivorID: survivor.id)+            _ = try graph.mergePeople(preview, choices: choices(preview))+            let reopened = try PersistenceStack(directory: directory)+            reopened.container.viewContext.automaticallyMergesChangesFromParent = false+            let reloaded = FamilyRepository(stack: reopened)+            let familyAgain = try #require(try reloaded.families().first)+            #expect(try reloaded.people(in: familyAgain.id).count == 1)+            let audit = try #require(try reloaded.mergeHistory(in: familyAgain.id).first)+            #expect(audit.undoAvailable)+            try reloaded.undoPersonMerge(audit.id)+            #expect(try reloaded.people(in: familyAgain.id).count == 2)+        }+    }++}
Tests/HaloPersistenceTests/RelationshipGraphTests.swift Added +258 / -0
diff --git a/Tests/HaloPersistenceTests/RelationshipGraphTests.swift b/Tests/HaloPersistenceTests/RelationshipGraphTests.swiftnew file mode 100644index 0000000..815e03f--- /dev/null+++ b/Tests/HaloPersistenceTests/RelationshipGraphTests.swift@@ -0,0 +1,258 @@+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 staleMembershipEndPreservesTheRecordedDateAndIdentity() throws {+        try withGraph { fixture, _ in+            let graph = fixture.graph+            let source = try graph.createContext(name: "Past playgroup", familyID: fixture.family)+            let membership = try graph.addMembership(connectionID: fixture.connection, contextID: source,+                                                     startedAt: Date(timeIntervalSince1970: 10))+            try graph.archiveContext(source, archived: true)+            let endedAt = Date(timeIntervalSince1970: 20)+            try graph.endMembership(membership, at: endedAt)+            #expect(throws: MemoryError.changed) {+                try graph.endMembership(membership, at: Date(timeIntervalSince1970: 30))+            }+            let retained = try #require(try graph.memberships(for: fixture.connection).first)+            #expect(retained.id == membership && retained.contextID == source)+            #expect(retained.endedAt == endedAt)+            #expect(try graph.connections(for: fixture.child).map(\.id) == [fixture.connection])+        }+    }++    @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)+    }+}

Docs (13)

CHANGELOG.md Modified +122 / -0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5e9e9b6..45e829d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,80 @@  ### Added +- Optional structured-name editing with atomic stale-edit checks, explicit merge+  choices and retained name undo/search behavior, including legacy-model support.+- Ordinary Person/ChildProfile/PersonGroup archive/restore with retained identities,+  links/history/assets, Include archived controls and stale/permission safeguards.+- Fourteen further synthetic name/archive/photo cases: current source declares+  146 tests/17 suites; strict lint 0/89 files, current test/build gate pending.+- Consolidated approved-plan source status and remaining runtime/release checklist.++- Native per-child WidgetKit extension, scoped typed child/Context entities, compact+  host capture form and authenticated local Shortcuts action on iOS and macOS.+- Atomic optional Context membership during capture, current-reference validation,+  bounded entity resolution and protection against repeated form submission.+- Twelve synthetic widget/capture cases: 132 declared tests/16 suites; strict lint+  0/86 files and valid project/plist syntax. New compilation, both builds and native+  extension/runtime verification await the shared Mac slot.++- Verified account/environment store namespaces and an explicit device-only library;+  old unscoped stores remain unattached until owner provenance is established.+- Store-qualified family access, serialized save checks, idempotent account teardown,+  background publication guards and bounded cross-process extension manifests.+- Scoped server share verification, retained exact-share denials and reinvitation+  handling; unrelated shares are not permanently denied by one store-level error.+- Fourteen synthetic account/access cases: 120 declared tests/15 suites and strict+  lint 0/79 files; new compilation/runtime gates await the shared test slot.++- Versioned family JSON/payload ZIP backup, optional readable summary and native+  preview with atomic absent-family or explicit fresh-identity copy import.+- Guarded historical identity remapping, retained merge accounts, ownership-derived+  asset limits, bounded ZIP validation and cancellation cleanup of owned staging.+- Editable Context categories with scoped starters, retained archived links and stale+  edit checks; richer People search and Person-level dated Context role visibility.+- Eleven backup, six category and four search synthetic cases. With Contacts the+  current source batch declares 106 cases/14 suites, pending its scheduled runtime gate.+++- Optional native Apple Contacts link/create controls and device-only linked-state/+  unlink UI; bounded host-only mappings retain both contacts through Person merge.+- Six synthetic local contact-link cases; this source checkpoint has 85 declared+  tests/11 suites with build/test/runtime pending, and strict lint 0/60 files.++- V6 duplicate suggestions, explicit merge previews and choices, retained reference/+  account history, affected-record undo and conservative recovery of competing merges.+- Read-only archived relationships, stale editor/capture guards and explicit transfer+  of unreviewed late accounts as alternatives without duplicating unchanged values.+- Eighteen additional synthetic merge/recovery/migration test cases. V6 source+  passes 79 cases/10 suites, strict lint (0/55) and both Debug platform builds.++- V5 family facts/assertions, groups, editable scoped address labels and conservative+  date-aware kinship paths; partial deceased dates in deliberate Sensitive Details.+- Social-event participation with independent invitations/attendance, multiple roles,+  multi-party gifts and Event-owned attachment references.+- Bounded background primary-photo/Event imports, image metadata removal, retained+  replaced assets, versioned thumbnails and cancellable document previews.+- Explicit reviewed-set resolution for closeness/status conflicts, preserving every period.+- Eighteen additional synthetic memory/image/temporal/migration test cases;+  all 61 cases pass with strict lint and both Debug platform builds.++- Retained causal first-meeting proposals with explicit conflict review, stale-resolution+  guards and late-arrival preservation.+- Five closeness choices, numeric 1...10 validation, explicit retained relationship+  history, and active/lost-contact controls.+- Multiple custom dated roles per Person/Context, guarded role/date editing, and+  child-qualified membership links.+- Seventeen additional synthetic conflict, defaults, review, V3 migration and refresh tests.+- Native Children/People/Contexts/Events/Review workspace with Mac sidebar and iOS tabs,+  family selection, focused name-only capture and a consolidated review queue.++- Native FamilySpace sharing controls, share reuse, invitation acceptance and retry.+- Nested Contexts, independent membership history, optional first-meeting memory,+  minimal dated Events and relevant-person Context associations in model V3.+- People search/review, sparse record enrichment and existing-person reuse across children.+- Twelve additional local graph, stale-edit, migration and cross-coordinator tests.+- Debug-only synthetic-store launch path for isolated UI checks.+ - Family and child selection with name-only Person capture and direct Connection lists. - Versioned Core Data graph and generic Asset payload storage, including V1-to-V2 migration. - App Group Private/Shared stores with host-owned CloudKit mirroring, local-only@@ -22,6 +96,54 @@  ### Changed +- Record final application source `ed6991f`: 148 cases/17 suites pass in 7.923+  seconds, full package coverage archived, strict lint 0/89 and both Debug builds+  pass. Focused native layout/names/archive/disabled-Contacts/relaunch case passes+  in 54.147 seconds with runner exit 0. Keep warm URL OS confirmation and broader+  native/live gates explicit; release the owned simulator/test slot.+++- Place the library menu and invitation notice in a separate vertical header after+  synthetic native checks showed tab-bar and collapsed-title overlap. Preserve the executed `804b98b` gate:+  148 cases/17 suites, strict lint 0/89 and both Debug builds. Record the native+  failed case, bounded teardown stall and unconfirmed synthetic payload diagnostic.+++- Reject stale membership-end actions, retain first end dates and historical Context+  membership behavior, and validate duplicate roots once per synchronous state-read+  batch with per-record permissions intact. Bound native file-provider reads to the+  20 MB attachment limit plus one byte, with cancellation and cleanup.+- Add two behavioral regressions: 148 declared cases/17 suites. Strict lint 0/89;+  new tests/builds await the shared slot. Preserve the executed `f7a6afd` 146-case gate.+- Reconcile current/historical evidence and define isolated native acceptance steps+  and required user actions; record the empty-remote draft-publication prerequisite.++- Pass the current 146-case/17-suite gate, strict lint 0/89, and both Debug builds;+  validate native host/widget metadata extraction and embedded extensions.+- Correct narrow first-use missing-file handling, legacy Person field guards and+  deleted-row family permission checks discovered by execution, retaining all cases.+- Fix actual category/backup/legacy/search fixture errors, macOS Contacts picker API,+  and typed intent identifiers/static metadata isolation; preserve Xcode normalization.+- Record failed/aborted attempts separately and retain native/account/schema gates.++- Keep dynamic persistence errors private in logs, explicitly request iOS store+  protection after first unlock, and avoid CloudKit containers for device-only stacks.++- Select model V6 while retaining V1–V5. Keep merge/recovery audits metadata-only+  and preserve existing encoded photo/attachment assets.++- Preserve all earlier models while migrating both stores to V5; retain existing+  Event identity, references and unknown dates during enrichment.++- Preserve V1–V3 models while migrating both stores to V4; retain each legacy origin+  account when first edited in the proposal model.+- Use a native macOS Grid relationship form with calm fields and section glass.++- Preserve prior models while migrating both stores to V3; merge local repository+  changes explicitly and reject stale Person/origin edits.+- Scope graph refresh notifications to the owning stack and show dates/notes for Events.+- Allow structured test/coverage options through the Makefile test target.+ - Configure the production bundle ID, CloudKit container, App Group, and notification   capabilities; share one host coordinator across app windows. - Include test sources in strict SwiftLint validation.
README.md Modified +153 / -17
diff --git a/README.md b/README.mdindex 629988f..52fe2b7 100644--- a/README.md+++ b/README.md@@ -1,7 +1,8 @@ # Halo Family -SwiftUI app for iPhone, iPad, and macOS. The repository currently contains the-capture UI and persistence foundation and the [design pack](docs/halo_family_design_pack/README.md).+SwiftUI app for iPhone, iPad, and macOS, with quick capture, People, Contexts,+first-meeting memory, family knowledge, social-event memory, photos and native family-sharing plumbing.+The [design pack](docs/halo_family_design_pack/README.md) tracks the staged scope.  ## Setup @@ -32,7 +33,7 @@ make lint          # SwiftLint; warnings count as failures make build-ios     # Generic iOS Simulator build; no simulator boot required make build-macos   # macOS build make check         # Lint and build both platforms-make test          # Local persistence/history/Asset/migration tests on macOS+make test          # Local synthetic persistence/domain/history/Asset/migration tests on macOS make build-release # Release builds make clean         # Remove local build output ```@@ -46,35 +47,106 @@ The Swift package compiles the same persistence sources and versioned model as the app. `make test` runs Swift Testing against temporary SQLite stores on macOS; it does not test iOS UI or CloudKit. Test artifacts use `DerivedData/swift-tests`. -## Try the first increment+## Try the app  Run the shared scheme in Xcode on a simulator or on My Mac. Create a family,-add a child, then enter a name or description and select **Save person**. Select-another child or family to change the displayed connections. Quit and reopen to-read saved data. Same-name captures intentionally create distinct People.--This is temporary navigation for exercising the data layer. The app now opens-`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-copied into the App Group automatically.+add a child, then choose **Remember someone**, enter a name or description and+select **Save person**. Select another child or use the family toolbar button to+change family. Mac uses a sidebar; iPhone/iPad uses tabs. Quit and reopen to read+saved data. Same-name captures intentionally create distinct People.++Open a captured Connection to record its first meeting independently of Context+membership. Create nested Contexts and dated birthday/playdate memories through+the family links. A meeting with an unknown date can use a description. Ending+memberships or archiving a Context preserves the Connection and its origin.+Review collects new captures and competing relationship accounts. People supports+name search, review filtering, enrichment and linking one existing+Person to another child. Contexts can associate relevant people with multiple custom+roles and optional dates, without creating peer Connections. Membership rows identify+the child and link to that child's Connection. Relationship controls offer Met once,+Know them, Friend, Good friend and BFF, plus active/lost-contact status and an optional+explanation. Only explicit value changes create closeness periods; history is retained.++Person detail links to structural family facts, entered assertions, address labels+and groups/households. Known kinship paths are derived conservatively, independently+of entered family titles. Use the ellipsis menu to deliberately open Sensitive Details:+deceased status and optional partial date preserve all history and Connection state.+Default child/review/participation suggestions suppress deceased People; explicit+People search and historical inclusion remain available.++Social Events retain invitations and attendance separately, multiple custom roles,+multi-person/group gift givers and multiple recipients. Gifts can refer to that Event's+attachments. These are social memories, without calendar or reminder scheduling.+All family notes, photos and Sensitive Details are visible to invited co-parents;+this is stated before opening system sharing controls.++**Share family** prepares/reuses a FamilySpace share and presents native private+read/write invitations. Accepted invitations open in the Shared store; downloads+arrive asynchronously. Signed device/two-account sharing is not yet verified in+this implementation. Referenced sources can be archived while preserving their links.+V6 merge source passes its local domain/build gate. Explicit previews+retain original identities and accounts; guarded undo restores affected references+only while unchanged. Review surfaces late accounts and competing merges. Recovery+shows separate identities while preserving current references and earlier audits.++The workspace uses the approved native navigation and shared persistence sources.+Account libraries open Private/Shared SQLite stores in an account/environment namespace+inside the App Group, with host-owned CloudKit mirroring. An explicit device-only library+uses a separate local namespace and does not mirror. All windows reuse the selected+host coordinator. Switching libraries does not upload device-only memories; moving them+requires explicit backup/import. Old unscoped stores and `HaloFamily-LocalDevelopment`+remain untouched and unattached until owner provenance is established.  Saving completes locally. CloudKit delivery is asynchronous; local saves do not promise that another device has received the changes. Startup failures offer retry. CloudKit errors and history-refresh failures are visible in the form. The history processor merges store changes before advancing per-store checkpoints; launch, foreground entry and remote-store notifications trigger processing.-History pruning remains deferred until the retention policy is settled.+Persistent history is retained until safe checkpoint-based pruning is verified.  The storage factories support local-only intent/widget roles: intents can write, widgets are read-only, and both require stores prepared by the host. There are-no shipped extension targets yet. Generic Asset payloads are saved on a background-context with external storage enabled; photo/import UI is still pending.+a native WidgetKit extension and typed Shortcuts action, with both platform builds+and metadata/embedding checked. Native execution still requires runtime verification. Asset payloads are saved on a background context with external storage enabled.+Person detail supports Photos/Files imports; primary photos are encoded as JPEG,+up to 2048 pixels and 4 MB. Event JPEG/PNG/PDF imports allow up to 20 MB; image+location metadata is stripped. Each import owns its Asset; replacing/removing a+primary photo preserves the earlier encoded copy pending safe explicit cleanup.++Model V6 preserves V1–V5 for migration and passes both-store migration tests.+Local origin CRUD rejects invalid links,+empty origins and stale edits. Immutable causal proposals retain competing accounts;+the Connection shows **First meeting needs review** until a parent chooses a version.+Resolution retains alternatives, and late arrivals can require another review. Linked+Context/Event and entered description are displayed separately. Overlapping closeness+or contact periods are retained for explicit choice. Resolution closes only the+current periods actually reviewed and creates a fresh selected period; late arrivals+can require review again. Local fixtures do not establish live CloudKit convergence.++For an isolated Debug UI check, launch the built app with+`--synthetic-store /tmp/halo-ui-<unique-id>`. Only a subdirectory of the system+temporary directory or `/tmp` is accepted. This opens plain local SQLite stores+without the App Group or CloudKit. Release builds ignore this Debug launch path.++Historical V5 and V6 gates passed 61/9 and 79/10 cases/suites respectively, strict+lint and sequential iOS Simulator/macOS Debug builds. The later combined gate at+`f7a6afd` passes 146 cases/17 suites and both platform builds. The final application+source `ed6991f` passes 148/17 in 7.923 seconds, strict lint and both Debug builds.+One focused synthetic native case passes in 54.147 seconds with runner exit 0.+Broader native UI and actual two-account CloudKit delivery remain unverified. -Share invitations/acceptance, Contexts, origins and Events remain to implement. See the [acceptance report](docs/halo_family_design_pack/10-initial-implementation-results.md) for current evidence and verification limits. +The integrated Contacts source adds optional Apple Contacts selection/create and device-local+links. Only the names explicitly saved in the contact form are copied to Contacts;+family notes/photos remain in Halo. Local links survive Person merge and unlink does+not delete a Contact. Synthetic/debug stores disable native Contacts access. Contacts+permission and picker/create behavior remain unverified. The six local mapping+cases pass within the current 148-case synthetic gate.+The Contacts increment originally declared 85 tests/11 suites, with the verified+V6 fixture correction at 3286293 already integrated. Current inventory is below.+ ## Install on a device  Both install commands default to the iPhone 17 Pro named **The Dark Side**:@@ -101,3 +173,67 @@ installing either replaces the other on that device.  SwiftLint follows the Prism project's rules. After `make lint-fix`, review the changes before building, particularly changes inside SwiftUI result builders.++## Backup, categories and richer search++Open **Family spaces → Backup and import** to create a versioned ZIP of the selected+family or preview a backup. Export includes all shared notes, Sensitive Details and+app-owned assets. Keep the file somewhere appropriate for that content. Device-local+Apple Contacts identifiers are excluded. A restored family starts in your Private+store and is not shared automatically.++Choose a new copy (fresh identities, retained history with old merge undo disabled)+or restore original identities only when none exist in the local stores. Existing+families are never overwritten. Only Halo's stored ZIP format is accepted; archive,+manifest, record and payload limits are listed in the current evidence document.+The whole-account absence of records on another device is not established locally.++Manage editable labels under **Contexts → Manage categories**, then choose a label+in a Context's detail. New families receive School, Playgroup, Parent group, Childcare+and Activities. Older families can add missing starters explicitly. Archived labels+remain attached to existing Contexts. People search covers names, entered titles,+roles, households, related names and nested Context paths. Person details also show+multiple dated Context roles. Their local cases pass; native UI/runtime acceptance+remains pending.++## Widgets and Shortcuts++Add the **Remember their people** widget and choose a child with an optional default+Context. Tap **Remember someone** to open a compact form, enter a name or description+and save. Context selection records membership; first-meeting memory remains separate.+Choose **None** to capture a name without membership. The **Remember someone** Shortcut+provides the same fields and requires device authentication. Its success means a local+save; open Halo Family to let an account library sync with iCloud.++Selections use scoped stable identities and current permissions/labels. Unavailable+children or Contexts require a current selection, and account/device libraries remain+separate. Widget previews are generic, and actual content is marked privacy-sensitive.+Timeline reload is a request to the system, so cached names after access changes and+locked-device redaction still need native validation.++The final local gate backing `ed6991f` passes **148 synthetic tests in 17 suites** in 7.923 seconds,+with JUnit zero failures/errors/skips, strict lint **0/89 files**, and sequential+**iOS Simulator/macOS Debug builds**. Host/widget metadata extraction and extension+validation pass on both platforms. A focused synthetic native case verifies tab/menu+layout, names, Person archive/restore, disabled Contacts and relaunch (54.147 seconds,+runner exit 0). Warm URL acceptance awaits the OS Open confirmation. Broader native+UI/extension execution, account/share+lifecycle, cache retention, legacy recovery, real CloudKit delivery, production schema+and large-data/runtime evidence remain release gates. Persistent history is retained.+Final review corrections retain ended membership dates, bound file-provider reads+and check duplicate family roots once per state-read batch. The current inventory+is **148 executed cases/17 suites**; their final test/build gate passes.++## Person names and archive/restore++Person details can add optional given/family names while retaining an independent+name or description. Search includes those names. Merge previews choose each name+field explicitly; undo retains the earlier names while affected records are unchanged.++Use **Archive and restore** in Person, child overview or group details. Archiving+changes current family views while retaining records, history and assets. Enable+**Include archived** in the corresponding list to find and restore them. Archiving a+child profile retains its Person; archiving that Person suppresses its current capture+suggestions too. A merged alias requires the guarded merge workflow rather than ordinary+restore. See the [release checklist](docs/halo_family_design_pack/10-initial-implementation-results.md)+for source completion and remaining native/account/schema gates.
docs/halo_family_design_pack/00-design-document.md Modified +5 / -5
diff --git a/docs/halo_family_design_pack/00-design-document.md b/docs/halo_family_design_pack/00-design-document.mdindex 428f3ef..0ee8350 100644--- a/docs/halo_family_design_pack/00-design-document.md+++ b/docs/halo_family_design_pack/00-design-document.md@@ -3,7 +3,7 @@ **Working app name:** Halo Family   **Broader product family:** Halo   **Platform:** iOS  -**Status:** Ready for staged implementation; unresolved decisions gated in the handoff  +**Status:** Approved application scope implemented as source; current local/runtime release gates pending **Distribution:** Personal/family use first   **Storage principle:** On-device and iCloud/CloudKit only   **Backend:** None operated by the app developer@@ -199,7 +199,7 @@ Pacifica can first meet Mia at Sophie's birthday, then later share school class  ### 3.6b ContextPerson -Associates a Person with a Context as teacher, coach, educator or another relevant role. These associations do not require peer Connections or separate Adult/Child entity types. Role vocabulary and lifecycle remain open.+Associates a Person with a Context as teacher, coach, educator or another relevant role. These associations do not require peer Connections or separate Adult/Child entity types. Multiple custom roles with optional dates per association are approved; further lifecycle behavior remains open.  ### 3.7 PersonRelationship @@ -283,7 +283,7 @@ The app's Person remains the canonical record.  Connection state is independent of Context membership and origin. -- Closeness uses five UI positions backed by `1...10`; exact labels/mapping remain open.+- Closeness uses five UI positions: 1 Met once, 3 Know them, 5 Friend, 7 Good friend, 10 BFF. The labels are approved and the numeric mapping is the corresponding implementation choice. - No sentiment model in v1. - Closeness history is recorded only on explicit changes, retained indefinitely and hidden in v1. - Connection status is `active` or `lostContact`, with an optional free-text explanation.@@ -685,7 +685,7 @@ Explicitly not goals:  See `03-open-questions.md` for the authoritative unresolved decision queue and `09-implementation-handoff.md` for phase gates. Do not interpret examples, candidate schema or likely UI directions as final decisions. -Outstanding areas include closeness labels/mapping, origin lifecycle and conflict handling, family primitives, Event states, attachment associations, navigation, privacy and production lifecycle policies. First-meeting provenance is settled as ConnectionOrigin; persistence architecture is selected. Neither needs reopening as a general modelling or architecture question.+Decision 2 in `decision_log.md` settles the remaining application defaults, including temporal history review, family/Event/assets, ordinary archival and privacy. Current source implements those defaults, with release verification tracked in `10-initial-implementation-results.md`. Graph visualisation retains its real-data prerequisite, class rollover remains v2, and optional appearance/future suggestion design remains deferred. Production account/cache retention, native extensions/UI, large-data and schema gates require current evidence. Permanent-delete implementation is conditional on the agreed release scope in Phase 11; actual live deletion always requires specific authority.  --- @@ -711,7 +711,7 @@ The following are stable enough to begin building around: - explicit duplicate merging; - iCloud/CloudKit sharing as a core architectural requirement. -The unresolved items above should remain visible during implementation rather than being silently decided in code.+The remaining validation and deferred-design items above stay explicit; source presence does not establish runtime or CloudKit delivery.   ---
docs/halo_family_design_pack/01-data-model.md Modified +66 / -33
diff --git a/docs/halo_family_design_pack/01-data-model.md b/docs/halo_family_design_pack/01-data-model.mdindex f4017d0..da17f3f 100644--- a/docs/halo_family_design_pack/01-data-model.md+++ b/docs/halo_family_design_pack/01-data-model.md@@ -1,6 +1,6 @@ # Data Model — Halo Family -**Status:** Current domain contract; explicitly marked candidate fields remain unresolved  +**Status:** Current domain contract; remaining application defaults approved in Decision 2 **Purpose:** Capture the current entity structure and the reasons behind each modelling decision.  ---@@ -56,7 +56,7 @@ erDiagram     PERSON ||--o{ EXTERNAL_LINK : has ``` -This is a conceptual domain model, not a final Core Data schema. Candidate attachment cardinalities are not settled. `ConnectionOrigin.context` and `.event` are mutually exclusive; the diagram alone cannot express that rule. Core Data optionality, inverses and defaults must be validated for CloudKit separately from domain validation.+This is a conceptual domain model; the V5 Core Data schema preserves prior models and uses optional inverse relationships. Decision 2 settles attachment ownership and the remaining application defaults. `ConnectionOrigin.context` and `.event` are mutually exclusive; the diagram alone cannot express that rule. Core Data optionality, inverses and defaults must be validated for CloudKit separately from domain validation.  This is intentionally a domain model rather than a generic graph model. @@ -95,8 +95,8 @@ Person - familyName: String? - notes: String? - isDeceased: Bool-- dateOfDeath: PartialDate? // persistence representation unresolved-- primaryPhoto: Asset? // whether photos ship in v1 remains open+- dateOfDeath: PartialDate? // optional year/month/day; each more precise field requires the preceding field+- primaryPhoto: Asset? // approved: one app-owned primary photo - reviewState: ReviewState - createdAt: Date - modifiedAt: Date@@ -125,7 +125,7 @@ Noah's mum Girl from swimming ``` -`reviewState` means “surface this again later”, not “invalid record”. Deceased state is Person-level, with optional partial date of death; expose it through Sensitive Details and suppress inappropriate proactive surfacing. Automatic Connection-state changes remain unresolved.+`reviewState` means “surface this again later”, not “invalid record”. Deceased state is Person-level, with optional partial date of death; expose it through Sensitive Details and suppress inappropriate proactive surfacing. Connection state/history remains unchanged; deceased status controls proactive presentation.  --- @@ -187,9 +187,9 @@ ConnectionClosenessPeriod - endedAt: Date? ``` -Five discrete UI positions map into the numeric domain `1...10`; zero is invalid. Final labels and the five numeric values remain open. Closeness is optional: no period is required for quick capture.+Five discrete UI positions map to 1 Met once, 3 Know them, 5 Friend, 7 Good friend and 10 BFF. Zero is invalid. The user approved the labels; this numeric mapping is the corresponding implementation choice. Closeness is optional: no period is required for quick capture. -Create a new period only on an explicit value change. Preserve every previous period indefinitely; history is hidden in v1 UI. No sentiment entity, field or control is part of v1. Concurrent period edits need reconciliation policy before multi-writer history is considered complete (open questions section 2).+Create a new period only on an explicit value change. Preserve every previous period indefinitely; history is hidden in v1 UI. No sentiment entity, field or control is part of v1. Competing current periods are retained. Explicit resolution closes exactly the reviewed current set and creates a fresh selected period; late arrivals remain reviewable. Two-account verification remains required.  --- @@ -205,7 +205,7 @@ ConnectionStatusPeriod - note: String? // optional free-text explanation ``` -Lost contact preserves the relationship and closeness history. Reconnection reuses the same Person and Connection. No structured loss-reason taxonomy is required. Death belongs to Person, not a Connection loss reason. Exact temporal/concurrent-edit handling remains open.+Lost contact preserves the relationship and closeness history. Reconnection reuses the same Person and Connection. No structured loss-reason taxonomy is required. Death belongs to Person, not a Connection loss reason. Temporal conflict resolution follows the same reviewed-set policy as closeness.  --- @@ -241,7 +241,7 @@ Activities  Generic recursive hierarchy is more flexible than separate entities for school, class, sport, team, playgroup, etc. -The full path is derived from parent relationships rather than duplicated as a string. Seeded categories start with School, Playgroup, Parent group, Childcare and Activities; categories are user-defined. Seed rename/delete/semantic-identifier rules remain open.+The full path is derived from parent relationships rather than duplicated as a string. Seeded categories start with School, Playgroup, Parent group, Childcare and Activities; categories are user-defined. Seeded labels are editable ordinary categories with no automatic School semantics. Referenced categories/sources are archived instead of silently dropping links.  --- @@ -287,7 +287,7 @@ ConnectionOrigin  - A Connection has zero or one origin; each origin belongs to exactly one Connection. - An origin references either one Context or one Event, never both; alternatively it contains only a non-blank free-text description.-- A description may supplement the linked Context or Event. Display precedence/wording remains open; preserve both pieces of information.+- A description may supplement the linked Context or Event. Display the linked source and the parent-entered description separately; preserve both pieces of information. - An empty origin is invalid. An unknown origin is represented by no origin record. - All linked records belong to the same FamilySpace and persistent store as the Connection. - Origin is child-specific: two children may first meet the same Person in different places.@@ -311,7 +311,24 @@ Connection: Rigel -> Mia Origin: description = Met at a playground while on holiday ``` -The optional, singular v1 origin follows the accepted design direction. Concurrent origin creation/replacement, deletion of a referenced Context/Event, and conflicting origins during explicit Person/Connection merge need policies before those operations ship; see open questions section 4.+The optional, singular current origin follows the accepted design direction. Keep competing offline proposals for explicit review and retain alternatives as history (Decision 1). Linked display follows the current source name separately from the preserved narrative. Referenced sources are archived. Overlapping Connections require an explicit merge preview and origin choice while retaining all proposals.++### Implemented proposal representation++Model V4 adds `OriginProposal` with UUID, FamilySpace, Connection, optional Context+or Event, narrative, creation date and a cleared flag. Immutable proposals reference+the predecessor proposals actually observed by their author. Heads are proposals+with no known successor. One head supplies the current origin; multiple heads show+review rather than selecting by timestamps. An explicit resolution acknowledges+every displayed head and records a new proposal, leaving alternatives intact.+Late arrivals can create a new conflict after resolution. Blank editors also retain+their observed head set so an unseen clear cannot be overwritten silently.++The existing ConnectionOrigin is a replaceable current projection, retained for+migration compatibility and stable local origin identity. Once proposals exist,+they are authoritative. The first edit of a V3 origin preserves its old account as+an initial proposal before appending the edit. Source deletion and merge policy+remain separate decisions; archiving does not remove references.  --- @@ -322,19 +339,19 @@ ContextPerson - id: UUID - context: Context - person: Person-- role? // vocabulary/cardinality unresolved+- role: String? // custom; multiple role associations per Person/Context - startedAt: Date? - endedAt: Date? - notes: String? ``` -Core association for teachers, coaches, educators, coordinators and other Context-associated people. Do not create separate Adult/Child entities or a peer Connection solely to represent these roles. Role vocabulary and lifecycle are open in section 6 of the questions document.+Core association for teachers, coaches, educators, coordinators and other Context-associated people. Do not create separate Adult/Child entities or a peer Connection solely to represent these roles. Multiple custom role associations, each with optional start/end dates, are approved. Archiving a Context preserves every role link; dates are entered explicitly. Successor-copy behavior remains a v2 class-rollover decision.  ---  ## 10. PersonRelationship -Proposed structural family relationship.+Approved separate structural family relationship (Decision 2).  ```swift PersonRelationship@@ -348,7 +365,7 @@ PersonRelationship - note: String? ``` -Candidate primitive kinds:+Primitive kinds:  ```text parentOf@@ -357,7 +374,7 @@ partnerOf guardianOf ``` -Possible nature:+Optional nature:  ```text biological@@ -375,7 +392,7 @@ This supports deriving family-side information without storing every possible ki  ### Open -The final primitive relationship vocabulary is not decided.+The primitive vocabulary and optional qualifiers above are approved implementation defaults. Derived kinship never replaces assertions or address labels.  --- @@ -429,7 +446,7 @@ No placeholder parents/grandparents required.  ### Open -This may remain a separate entity, or be unified with PersonRelationship using provenance/relationship type.+Keep a separate free-text assertion, useful without complete ancestry. No missing relatives are invented.  --- @@ -466,7 +483,7 @@ This is especially important for culturally specific family terminology.  ### Open -Whether `usedByGroup` is necessary in v1 and how language/script metadata should work.+Labels may be scoped to one Person, one group, or generally, with optional language/script. Editing a label preserves structural family facts.  --- @@ -557,7 +574,7 @@ The date exists for history and querying, not scheduling.  ### Open -Exact EventType vocabulary.+Use an optional custom Event type. Events remain social memory, not personal-life timeline events or calendar/reminders.  --- @@ -568,7 +585,7 @@ EventPerson - id: UUID - event: Event - person: Person-- role: EventRole?+- roles: Set<String> // multiple custom roles - invitationState: InvitationState? - attendanceState: AttendanceState? - note: String?@@ -588,7 +605,7 @@ Potential invitation states:  ```text considering-planned+intendToInvite invited accepted declined@@ -614,7 +631,7 @@ Allows queries such as:  ### Open -The exact state model needs refinement to avoid overlapping or contradictory values.+Planning/invitations (unknown, considering, intendToInvite, invited, accepted, declined) are independent from attendance (unknown, attended, didNotAttend). An attended uninvited guest is valid; neither state invents the other.  --- @@ -624,12 +641,12 @@ The exact state model needs refinement to avoid overlapping or contradictory val GiftRecord - id: UUID - event: Event-- fromPerson: Person?-- fromGroup: PersonGroup?-- toPerson: Person?+- givers: Set<Person>+- giverGroups: Set<PersonGroup>+- recipients: Set<Person> - description: String - note: String?-- attachment: EventAttachment?+- attachments: Set<EventAttachment> ```  ### Reason@@ -650,7 +667,7 @@ Craft kit  ### Open -Whether gifts need multiple givers/recipients and whether attachments should be many-to-many.+Multiple Person/group givers and Person recipients are supported. Optional gift attachment references must belong to the same Event.  --- @@ -661,7 +678,7 @@ EventAttachment - id: UUID - event: Event - kind: AttachmentKind-- asset: Asset // conceptual payload reference; ownership/cardinality still open+- asset: Asset // one app-owned payload per import - title: String? - note: String? - createdAt: Date@@ -687,7 +704,7 @@ Supports useful artefacts such as:  ### Open -Physical storage is decided: generic `Asset` with Core Data Binary Data and Allows External Storage enabled. Whether EventAttachment remains an association/metadata entity or Events reference Assets directly remains open, along with ownership/cardinality and generic attachment associations beyond Events. Do not implement both alternatives as duplicate sources of truth.+Physical storage is decided: generic `Asset` with Core Data Binary Data and Allows External Storage enabled. EventAttachment is the sole Event/Asset metadata link. Each import creates one app-owned Asset; no payload is shared across families. Person primary photo is a separate optional one-to-one Asset link.  ### Asset @@ -702,12 +719,28 @@ Asset - createdAt, modifiedAt ``` -Metadata is a recommended conceptual shape; see `06-attachment-photo-storage.md` for decided storage and outstanding policy.+V5 adds filename/contentType, byteCount, dimensions, kind and a content revision UUID for local thumbnail invalidation. See `06-attachment-photo-storage.md` for approved limits.  ---  ## 19. ExternalLink +Apple Contacts uses a **device-local mapping**, per the approved policy in+`03-open-questions.md`, rather than a CloudKit entity. `DeviceContactLink` holds a+stable local UUID, FamilySpace UUID, Person UUID, the device's contact identifier,+optional selection label and creation date. The host owns one serialized local file+actor shared by its windows. The mapping file is excluded from backups and is not+part of family ZIP exports. Canonical Person identity is unchanged.++Merged Person aliases retain their separate mappings; no Apple Contacts are merged+or deleted. Unlink removes only the local mapping. Native picker selection and+explicit contact creation copy no family notes, photos or Sensitive Details.+Synthetic persistence/debug workspaces disable native Contacts access. Native OS+permissions, restricted/limited access and picker/create runtime remain unverified.++The original platform-neutral conceptual shape is retained below for context;+it is not the implemented mirrored schema:+ ```swift ExternalLink - id: UUID@@ -767,7 +800,7 @@ Merging Person A into Person B should repoint:  The survivor retains a stable ID. -Automatic merging is explicitly out of scope. Preserve origins while repointing Connections. If merging produces overlapping Connections for one child with different origins, do not silently discard either origin; resolve the merge policy in open questions section 4 first.+Automatic merging is explicitly out of scope. Preserve origins while repointing Connections. If merging produces overlapping Connections for one child with different origins, do not silently discard either origin; require explicit choice in the merge preview while retaining alternatives and guarded undo.  --- @@ -807,4 +840,4 @@ This allows the app to answer historical questions without requiring a general j  ## 23. Model questions still open -`03-open-questions.md` is the authoritative decision queue. Major schema gates include family relationship structure, PartialDate, closeness mapping and concurrent history, origin lifecycle/merge reconciliation, Event participation states, attachment associations and private versus shared metadata. Candidate shapes in this document do not settle those questions.+`03-open-questions.md` is the authoritative decision queue. Decision 2 approves the remaining application defaults. Class rollover stays v2; current source/verification and device/release gates are tracked separately. Historical candidate examples do not override the approved defaults.
docs/halo_family_design_pack/02-technical-architecture.md Modified +1 / -1
diff --git a/docs/halo_family_design_pack/02-technical-architecture.md b/docs/halo_family_design_pack/02-technical-architecture.mdindex 7ec6e36..7436b65 100644--- a/docs/halo_family_design_pack/02-technical-architecture.md+++ b/docs/halo_family_design_pack/02-technical-architecture.md@@ -258,7 +258,7 @@ The persistence layer must expose a reliable way to:  Persist ConnectionOrigin inside its Connection's FamilySpace graph and store. Any referenced Context or Event must belong to that same FamilySpace/store; reject cross-family links at the domain boundary. -Domain rules: zero or one origin per Connection, Context XOR Event when linked, otherwise non-blank description. Description may supplement a reference. These are application invariants, not a claim that CloudKit enforces uniqueness or atomic cross-device validation. Resolve concurrent origin creation/replacement policy before calling multi-writer support complete.+Domain rules: zero or one current origin per Connection, Context XOR Event when linked, otherwise non-blank description. Description may supplement a reference and is displayed separately. These are application invariants, not a claim that CloudKit enforces uniqueness or atomic cross-device validation. Model V4 implements the approved conflict policy with immutable causal OriginProposal records (Decision 1). It validates same-family references, UUID identity and every component of the predecessor graph. Multiple heads require explicit review; resolution records a new proposal referencing the displayed heads and retains all alternatives. No timestamp decides which account is correct. CloudKit two-account verification remains required before multi-writer transport is considered verified.  Include origin changes in relationship fetch/refresh and persistent-history handling. Verify owner-created and participant-created origins, offline edits and references after relaunch. The persistence spike did not test ConnectionOrigin; its coverage must be added, not inferred from the spike report. 
docs/halo_family_design_pack/03-open-questions.md Modified +28 / -498
diff --git a/docs/halo_family_design_pack/03-open-questions.md b/docs/halo_family_design_pack/03-open-questions.mdindex c7a6d40..812d961 100644--- a/docs/halo_family_design_pack/03-open-questions.md+++ b/docs/halo_family_design_pack/03-open-questions.md@@ -1,500 +1,30 @@ # Open Questions — Halo Family -**Updated:** 2026-09-24--Only unresolved decisions belong here.-------## 1. Production hardening--### 1.1 No-iCloud-account lifecycle--The persistence spike deliberately deferred this.--Need to validate:--- app launch with no iCloud account;-- creation/editing of local data;-- persistence across relaunch;-- how sync unavailability is shown;-- what happens after an iCloud account later becomes available;-- whether pre-existing local data synchronises cleanly after sign-in.--### 1.2 Persistent-history retention--Need production policy for:--- checkpoint storage;-- pruning old persistent history;-- interaction with widgets/App Intents;-- recovery if a process checkpoint is stale or missing.--### 1.3 Migration--Need to define:--- Core Data model versioning policy;-- migration tests for Private + Shared stores;-- migration with existing CKShare-backed graphs;-- rollback/recovery expectations.--### 1.4 Account/share lifecycle--Need behaviour for:--- iCloud account change;-- share owner stops sharing;-- participant leaves/removes access;-- re-invitation;-- orphaned local cached data;-- ownership changes if ever supported.--### 1.5 Release CloudKit schema--Need deployment procedure for:--- development → production schema;-- indexes/record types;-- cloud encryption choices;-- release validation.-------## 2. Closeness--### 2.1 Five-step labels and numeric mapping--Decided:--- five discrete UI positions;-- stored numeric domain `1...10`;-- no zero;-- no sentiment model;-- history is created only on explicit changes;-- all prior values retained;-- history hidden in normal v1 UI.--Still open:--- final labels;-- exact numeric values for the five positions.--Illustrative only:--```text-1   Met once-3   Know them-5   Friend-7   Good friend-10  BFF-```--### 2.2 Concurrent temporal edits--Need reconciliation rules when two parents change closeness or Connection status offline, producing overlapping current periods. The spike established ordinary record convergence, not a production policy for temporal histories. Do not assume a deterministic last writer or discard retained history.-------## 3. Deceased Person handling--Decided:--- deceased status is Person-level;-- optional partial date of death;-- sensitive/deceased controls live in an unobtrusive Sensitive Details sheet;-- deceased People should not be proactively surfaced for actions they cannot take part in.--Still open:--### 3.1 Active Connection presentation--When Person becomes deceased:--- automatically convert active Connections to a historical/lost-contact presentation?-- or leave Connection state untouched and let Person deceased-state control presentation?--### 3.2 Feature suppression rules--Need an explicit production checklist for every feature that can proactively surface a Person.--Examples:--- birthday invite suggestions;-- reconnect prompts;-- enrichment prompts;-- widgets;-- graph defaults;-- recent-people surfaces.--### 3.3 PartialDate representation--Need reusable persistence choice for incomplete dates:--- year/month/day fields;-- or Date + precision enum;-- or another representation.-------## 4. ConnectionOrigin follow-up decisions--Decided: ConnectionOrigin is core, optional and singular per Connection in v1. It references one Context or one Event, or free text alone. A description may supplement a reference. Membership and first meeting are separate facts. There is no `metHere` flag on ConnectionContext.--Only these follow-up decisions remain open:--- **Suggestions:** whether/how the earliest Context is offered, confirmation before treating it as origin, and display wording for unconfirmed suggestions. Do not equate earliest recorded Context with first meeting.-- **Linked text:** display precedence when a description supplements a Context/Event; whether linked renames should change historical wording or retain a snapshot.-- **Deletion:** what happens when the referenced Context/Event is deleted; preserve description/snapshot, block deletion, or another explicit choice. Archiving is not deletion and should keep the reference.-- **Conflicts:** how simultaneous creation/replacement of the one origin is reconciled across parents without silently losing information.-- **Merge:** how origins are resolved if explicit Person merge consolidates two Connections for the same child.--These are UI/lifecycle policies, not a choice between a Connection field and ConnectionContext flag.-------## 5. Context categories--Seeded starting categories are decided:--```text-School-Playgroup-Parent group-Childcare-Activities-```--Categories remain user-defined.--Still open:--- can seeded categories be renamed/deleted?-- do seeded categories retain stable semantic identifiers?-- can a user-created category later be marked equivalent to `School`, etc. for feature behaviour?-------## 6. ContextPerson--`ContextPerson` is core.--### 6.1 Role vocabulary--Need to decide:--- seeded suggestions + custom roles?-- fully free-form roles?-- multiple roles for one Person in one Context?-- date ranges per role versus per ContextPerson record?--Likely seeded examples:--```text-Teacher-Coach-Educator-Coordinator-Leader-Staff-Parent helper-```--### 6.2 Lifecycle--Need to decide:--- exact start/end-date behaviour;-- what archiving a Context does to its ContextPerson links;-- whether a Person continuing into a successor Context is copied or newly associated.--### 6.3 Broad PersonKind--No separate Adult/Child entities.--Still open whether Person needs an optional:--```text-child-adult-unknown-```--presentation hint, or whether UI can infer enough from relationships/roles.-------## 7. School/class rollover — v2--Decided:--- manually triggered;-- no calendar-year assumptions;-- selective exclusions;-- previous Context archives as part of transition.--Still open:--- are all peer members selected by default?-- are ContextPerson adults offered separately?-- what metadata does successor Context inherit?-- how are children who stay in an old Context represented?-------## 8. Family model--### 8.1 Structural relationship primitives--Candidate set:--```text-parentOf-siblingOf-partnerOf-guardianOf-```--Need final decision on:--- stored vs derived sibling relationships;-- guardian overlap;-- former/temporal partnerships.--### 8.2 Relationship nature--Candidate qualifiers:--```text-biological-adoptive-step-foster-unknown-```--Need exact applicability.--### 8.3 PersonRelationship vs RelationshipAssertion--Still open whether to keep two entities or unify into one relationship entity with provenance/structure metadata.--### 8.4 Family side--Need rules for explicit versus derived:--- maternal;-- paternal;-- related through marriage;-- incomplete assertions.--### 8.5 Address labels--Need final behaviour for:--- per-person labels;-- group labels such as “the kids call her …”;-- multiple languages;-- native script/romanisation;-- preferred label selection.--### 8.6 Automatic kinship derivation--Need to decide which relationships are safely derivable and how ambiguity is represented.--Current direction remains conservative: derived relationship does not dictate the preferred family title.-------## 9. Event memory--### 9.1 Event type vocabulary--Do we need structured Event types in v1, or is title/date enough initially?--### 9.2 Invitation/attendance state--Need a model that avoids contradictory combinations across:--```text-role-planning/invitation state-attendance state-```--### 9.3 Future birthday planning--Need to support:--- considering;-- intend to invite;-- invited;-- accepted/declined;-- attended/did not attend.--Need final state machine.--### 9.4 Gifts--Need to decide:--- one or multiple givers;-- one or multiple recipients;-- PersonGroup as giver;-- gift-specific attachments.-------## 10. Assets/photos--Storage architecture is decided:--> Core Data Asset + Binary Data + Allows External Storage.--Still open production policy:--- maximum Person-photo dimensions/byte size;-- invitation image resizing threshold;-- supported document types;-- local thumbnail cache behaviour;-- cloud-encryption choices;-- whether Person photos ship in v1;-- attachment ownership/cardinality, including whether EventAttachment is retained as metadata or Events directly reference Assets;-- attachment ownership rules beyond Person primary photo + Event attachments.-------## 11. UI--### 11.1 Navigation--Final top-level navigation remains unresolved. ChildProfile appearance metadata (if any) also remains unspecified; do not make it a required capture field.--### 11.2 Child overview--Need to determine final prioritisation of:--- close/current relationships;-- recently added people;-- Contexts/groups;-- graph access.--No general upcoming-events/calendar section.--### 11.3 Person detail--Need to fit sparse and rich records without over-tabbed UI.--Must support:--- peer relationship information;-- ContextPerson roles;-- family;-- social-event history;-- Contacts;-- Sensitive Details.--### 11.4 Sensitive Details sheet--Need exact discoverability and interaction design.--Goal:--> a user can use the app normally without ever noticing it unless they deliberately look for sensitive details.--### 11.5 Graph--Need visual grammar for:--- Person vs Context;-- peer Connection vs ContextPerson role;-- current vs historical;-- family relationships;-- filtering dense graphs;-- deceased Person default visibility.--### 11.6 Inbox/review--Need exact rules for:--- what enters inbox;-- review completion;-- duplicate suggestions.--### 11.7 Merge People--Need to decide:--- choose survivor;-- field conflict handling;-- undo;-- preview of affected relationships.-------## 12. Search--Need behaviour across:--- partial names;-- custom labels;-- family titles;-- Contexts;-- ContextPerson roles;-- related adults;-- indirect family relations.-------## 13. Widget/App Intent product design--Architecture is validated.--Still need product decisions:--- one widget per child?-- quick-add only or Context shortcuts?-- Lock Screen support?-- identifying information visible while locked?-- App Intent parameters beyond child/name/Context?-------## 14. Privacy--Need decisions on:--- Person photos in v1;-- Lock Screen disclosure;-- app-switcher masking;-- CloudKit cloud encryption for sensitive attributes/assets;-- local file protection;-- shared vs per-parent private notes;-- export/delete.-------## 15. Export/import--Need to decide:--- when export is required;-- JSON, Markdown, or both;-- attachment bundle;-- whether export is re-importable;-- stable UUID behaviour;-- linked Contacts representation.-------## 16. Scope guardrail--For each proposed feature:--> Does this help remember who people are, how they connect, or the socially important history around those connections?--If not, it probably belongs elsewhere.--## 17. Delivery scope--The build plan is an ordered roadmap, not confirmation that every phase ships in v1. Person photos, export/import timing and final release scope remain open. Phase 10 class rollover is v2 and must not gate a v1 release. See the handoff for the smallest first implementation slice.+**Updated:** 2026-10-07 UTC++The user approved the remaining application defaults in Decision 2 of+`decision_log.md`. Those decisions supersede the former unresolved schema/product+queue. Implementation and verification are tracked separately in the build plan.++## Remaining decisions++- Class rollover is v2: selection defaults, successor metadata and separate+  ContextPerson handling still need a concrete design when that phase starts.+- Child appearance metadata remains optional and unspecified.+- Future first-meeting suggestions must remain unconfirmed until explicitly chosen;+  this release does not infer an origin from the earliest Context.+- Contacts identifiers are device-specific. Use a device-local link separate from+  canonical Person identity; do not mirror another device's address-book identifier.++## Remaining validation/release gates++- No-account launch/local editing/restoration, account change, removed share and+  reinvitation must be exercised without changing global settings in this task.+- Verify safe history pruning against every consumer checkpoint before pruning;+  retention is the approved interim behavior.+- Verify migration in both stores and existing CKShare graphs, real two-account+  delivery/offline conflict behavior, extension execution, and production schema.+- Native UI, image limits, quota/storage failures, large data and backup/import+  need current evidence. Historical spike results do not establish these gates.+- Production schema deployment, live invitations/private data and permanent live+  deletion still require specific authority.
docs/halo_family_design_pack/04-build-plan.md Modified +214 / -2
diff --git a/docs/halo_family_design_pack/04-build-plan.md b/docs/halo_family_design_pack/04-build-plan.mdindex 9997464..828b6cc 100644--- a/docs/halo_family_design_pack/04-build-plan.md+++ b/docs/halo_family_design_pack/04-build-plan.md@@ -1,6 +1,218 @@ # Build Plan — Halo Family -**Status:** Architecture spike complete; persistence foundation implemented in part+**Status:** Application source implemented; final local gate and focused native acceptance pass; broader native/release acceptance remains separate, with native/release acceptance separate++### Final publication review corrections — 2026-10-07 UTC++The full unpublished branch review identified a stale membership-end overwrite,+repeated family-root counts during state-list refresh, and an unbounded provider+file read before its size rejection. Scoped fixes preserve the first recorded end+date, check root uniqueness once per family/store within a synchronous batch while+retaining every record's access validation, and read at most the attachment limit+plus one byte. Two new behavioral cases bring declarations to **148/17 suites**.+At `804b98b`, **148/17 pass in 8.624 seconds**, strict lint **0/89** and both Debug+builds pass. A bounded synthetic native check exposed a library-menu/tab overlap;+the separate-header correction at `ed6991f` passes 148/17 in 7.923 seconds, strict+lint and both Debug builds. Its focused native case passes once in 54.147 seconds+with runner exit 0; warm URL acceptance stops at the OS Open confirmation. The earlier 146-case gate+below remains specifically `f7a6afd`. Full native/live acceptance remains pending.++The user published the remote `main` base; read-only fetch verifies `8c5262f`.+No agent remote default change, main push or merge is performed.+See the [smallest isolated acceptance plan](10-initial-implementation-results.md).++### Combined gate at f7a6afd passed — 2026-10-07 UTC++The 146-case/17-suite synthetic gate at `f7a6afd` passes in 7.034 seconds (JUnit zero+failures/errors/skips), with strict lint 0/89 and sequential iOS Simulator/macOS+Debug builds. Host/widget metadata extraction and extension embedding pass on both+platforms. Executed corrections retain every case and correct genuine fixture errors, including narrow+missing-file handling, legacy field rejection, deleted-row permission validation,+genuine fixture errors, macOS picker API and typed intent metadata/isolation.+Four final source reviews are clear; both owned heavy runners have drained.++Phases 1–7 and 9 have implemented source and their current local gate. Native UI,+Contacts/widgets/Shortcuts, actual account/share/offline/cache contents, quota/large+data, existing shares and production schema remain acceptance evidence. Phase 8+still requires representative real data; Phase 10 is v2. See the consolidated+[remaining checklist and exact failed/passing evidence](10-initial-implementation-results.md).++### Earlier source closure and release checklist — 2026-10-07 UTC++Optional structured names now have native editing, explicit merge field choices and+retained undo. Ordinary Person/ChildProfile/PersonGroup archive and restore preserves+identity, links and assets, with current-view suppression and stale/permission guards.+Fourteen further synthetic cases bring current source to **146 declarations/17 suites**;+strict lint passes **0/89 files**. Current compilation/tests and both Debug builds+await the parent-scheduled shared slot. Last executed passing gate is still **3286293:+79 cases/10 suites and both Debug builds**.++Phases 1–7 and 9 are implemented as source. Phase 8 requires enough real data;+Phase 10 remains v2. Phase 11 separates implemented local guards and approved+history retention from runtime, cache-retention, two-account, large-data and schema+release evidence. Permanent-delete implementation remains conditional on the agreed+release scope, as stated in Phase 11; ordinary removal archives. See the consolidated+[remaining checklist and evidence](10-initial-implementation-results.md).++### Widget and AppIntent implementation — 2026-10-07 UTC++Phase 9 source includes the native extension target, scoped typed child/Context+entities, a small host capture form and authenticated Shortcuts action. Widgets+use fresh read-only local coordinators; intents write locally without mirroring.+Optional Context saves membership atomically and does not infer an origin.+Stale account, permission, child and Context references fail closed. Twelve new+synthetic cases bring source to **132 declared cases/16 suites**; strict lint is+**0/86 files**, with valid project/plist syntax. New compilation/runtime gates+await the shared Mac slot. The last executed passing gate remains **3286293:+79 cases/10 suites and both Debug builds**. Widget privacy/cache refresh,+configuration, deep-link delivery and authenticated extension execution still+need native evidence. Phase 8's real-data prerequisite and v2 Phase 10 are unchanged.++### Account/access implementation — 2026-10-07 UTC++Account/environment-scoped stores, an explicit device-only library, opening/session+invalidation, store-qualified permission manifests, save/publication guards and+scoped share verification/reinvitation are implemented as source. Fourteen new+synthetic cases bring this checkout to **120 declared cases/15 suites**; strict+lint passes **0/79 files**. All new runtime/build gates remain pending the shared+slot. The last executed passing gate remains **3286293: 79 cases/10 suites and+both Debug builds**. Actual framework cache retention, account switching, share+revocation/reinvite/offline and legacy unscoped recovery remain release evidence+requirements. No production schema or actual account data operation ran.++### Backup, categories and search source checkpoint — 2026-10-07 UTC++The source on verified V6 now adds versioned JSON plus payload ZIP export, an+optional Markdown summary, native preview/import and an atomic Private-store+restore. Existing identities in either local store reject original-identity+restore; an explicit copy receives a fresh identity namespace, including historical+merge references. Competing accounts remain retained. Historical merge undo is+disabled in copied families; absent-family restore retains its existing guards.+Apple Contacts mappings are excluded. Native selection/export requires only the+user-selected document; no real family export or Contacts operation ran here.++Context categories are ordinary editable labels: five starters in newly created+families, explicit starter addition for older families, stale-edit checks and archive+without dropping Context links. People search now includes structured names,+entered family/address titles, roles, groups, related names and nested Context paths.+Person details display every Context role and optional date, including history.+Search does not infer gender or culturally specific titles.++This source batch declares **106 tests/14 suites**: six Contacts, eleven backup,+six category and four search cases above the verified 79. Strict lint passes+**0/74 files**; compilation/tests/native runtime are pending the shared-Mac slot.+Fixture-only role references use the actual `.appIntent` enum case; the earlier+Contacts draft's `.intent` spelling was not compiled. Four independent source+reviews identified ownership-derived photo limits, indexed inverse validation,+streamed history validation, copied UUID ordering and cancellation/staging cleanup;+those corrections are implemented. All four final source reviews are clear.++Backup limits are explicit: stored ZIP32 only, 1 GB/10,000 members, 32 MB manifest,+100,000 current records, 16 MB per merge snapshot, and aggregate preview/restore+payloads of 128 MB on iOS / 512 MB on macOS. Photo/Event payload limits follow+actual ownership (4 MB/20 MB), independently of mutable kind metadata. Absence+checks cover these local stores, not unseen records on another CloudKit device.+No native UI, live CloudKit, no-account/account-change/share-removal or production+schema evidence is claimed. Extensions and lifecycle work remain active; graph+visualisation still has its real-data prerequisite, and class rollover remains v2.++### Contacts source checkpoint — 2026-10-07 UTC++Phase 7 source integrated onto verified V6 implements optional native Contact+selection/creation, visible local linked state and unlink. Device identifiers/labels+live in a bounded host-only local file actor, separate from the CloudKit model and+exports. Merge aliases retain multiple links, and undo restores the original mapping+scope. Explicit creation copies only entered names; link failure retries never+create another Contact. Synthetic/debug stacks disable native Contacts calls.++Six new local mapping cases are drafted: **85 declared tests/11 suites** in this+checkout, all new Contacts/runtime verification pending. Lint passes 0/60 files.+The V6 gate passes 79 cases/10 suites and both Debug builds at **3286293**.+Contacts is now integrated onto that verified checkpoint, including the seven+fixture-argument corrections; its own 85-case gate remains pending.+There is no heavy Halo runner. Backup/import and later application work remain active.++### Duplicate/merge implementation — 2026-10-07 UTC++V6 source implements Phase 6 name suggestions, explicit merge previews and field/+overlapping-Connection choices, retained identities/accounts, metadata audit history+and guarded undo. Stale archived Person/Connection/ChildProfile editors reject;+self-Connections are archived rather than shown as current. Late imported accounts+have an explicit Review transfer that copies only unreviewed alternatives, retaining+original UUIDs. Opposing merge accounts and unsupported/circular aliases expose the+affected people. Recovery clears aliases while retaining current references and+all audit history; later explicit merges acknowledge observed recovery UUIDs.++The final sequential **make test → make check** gate passes: **79 tests/10 suites**+(18 new merge cases), **0 lint violations/55 files**, and both iOS Simulator/macOS+Debug builds. Runtime was 5.020 seconds, with no assertion failure or runner stall.+The first attempt failed test compilation because seven fixture status calls omitted+an existing required note argument; those calls were corrected without changing+assertions or inventory. Native UI and actual CloudKit transport remain unrun.+Contacts, backup/import, categories/search/role visibility, extensions and lifecycle+hardening remain active application work. Runtime/two-account/schema gates are separate.++### Family/photo/social-memory increment — 2026-10-07 UTC++Decision 2 records the remaining defaults approved by the user. V5 source adds+Person photos and partial deceased dates, structural facts and entered assertions,+scoped editable address labels, flexible groups, date-aware conservative kinship,+full social Event participation/gifts/attachment links and native forms. Image work+and payload saves run in the background; metadata is stripped and limits enforced.+Closeness/status conflicts now support explicit reviewed-set resolution.++The final make test → make check gate passes: 61 tests in 9 suites, including+18 new cases and both-store V4 migration; strict lint 0/44 files; sequential+iOS Simulator and macOS Debug builds. Runtime UI and two-account delivery have+not run. Initial compiler errors and final-review fixes are recorded in the+evidence document, separately from the passing assertion results.+Merge/duplicates, Contacts, backup/import, final extension UX and account/share+hardening remain active implementation work. Seeded editable Context categories,+richer search and Person-level Context role visibility also remain. Class rollover is v2.++### Approved defaults implementation — 2026-10-07 UTC++V4 adds immutable causal OriginProposal history, explicit conflict choice, retained+alternatives and late-arrival review. Blank/stale editors and stale resolution are+guarded by their observed proposal heads. Existing V3 origins are retained on first+edit. Five closeness controls write explicit numeric 1...10 periods; lost contact and+reconnection retain Person/Connection identity and earlier history. ContextPerson+supports multiple custom roles and optional dates. Context membership lists identify+the child and open the corresponding Connection.++The runnable workspace uses Mac sidebar/iOS tabs for Children, People, Contexts,+Events and Review. Capture stays name-only; child lists show explicit closeness+and can include lost-contact history. Review includes new Person captures and+competing origin/temporal accounts. Batched period/proposal queries keep list+refresh from fetching each Connection's state separately.++The final gates pass: 43 synthetic tests in seven suites, strict lint 0/34 files,+and make check with sequential iOS Simulator/macOS Debug builds. Native UI runtime+and real two-account CloudKit verification have not run. The previous checkpoint's+passing counts below remain historical.+Concurrent temporal histories are retained and flagged, with their explicit resolution+policy still open. Remaining durable family/Event/assets/privacy decisions are being+resolved while independent source work continues.++### Relationship implementation progress — 2026-10-06 UTC++Native share preparation/reuse and invitation acceptance are implemented in the+host, with private read/write system controls and cold/warm launch delivery.+V3 adds nested Contexts, independent memberships, optional first-meeting CRUD,+minimal dated Events and ContextPerson associations. People supports enrichment,+name search, review filtering and reuse across children. Direct queries and local+snapshot guards protect refresh and stale editor behavior.++Twenty-six local tests pass, including both-store V1/V2 → V3 migration. Strict+lint and both Debug platform builds pass individually; the initial combined+gate found a macOS SDK type rename, corrected and rebuilt. Device/two-account+sharing and native UI automation have not run. See the current evidence document.++The user approved origin conflict preservation/review, separate linked-source and+narrative display, five closeness labels/mapping and multiple dated custom roles.+These product defaults are recorded in `decision_log.md`; implementation follows+this checkpoint. Source deletion, merge, temporal history concurrency and later+roadmap/release choices remain gated.  ### Implementation progress — 2026-10-07 @@ -109,7 +321,7 @@ Build: - search by name; - inbox/review. -Phase gate: settle closeness labels/mapping before the final control, and origin concurrent-edit/deletion policies before those operations ship. Minimal Event origin support must not depend on unresolved invitation/attendance enums. An unknown meeting date can remain a free-text origin rather than requiring an invented Event date. Validate scenarios 21–28.+Phase gate: implement and verify the approved closeness labels/mapping and retained competing origin proposals/review. Concurrent temporal histories, source deletion and overlapping Connection merge remain gated. Minimal Event origin support must not depend on unresolved invitation/attendance enums. An unknown meeting date can remain a free-text origin rather than requiring an invented Event date. Validate scenarios 21–28.  Do not build graph visualisation yet. 
docs/halo_family_design_pack/06-attachment-photo-storage.md Modified +16 / -20
diff --git a/docs/halo_family_design_pack/06-attachment-photo-storage.md b/docs/halo_family_design_pack/06-attachment-photo-storage.mdindex 8e2fa06..359ce4c 100644--- a/docs/halo_family_design_pack/06-attachment-photo-storage.md+++ b/docs/halo_family_design_pack/06-attachment-photo-storage.md@@ -58,11 +58,11 @@ Asset - modifiedAt ``` -Conceptual uses (Person-photo v1 scope and Event attachment association/cardinality remain unresolved):+Approved uses (Decision 2):  ```text-Person.primaryPhoto -> Asset?-Event attachments -> Asset payloads // directly or through EventAttachment; decision pending+Person.primaryPhoto -> Asset? // one app-owned imported copy+Event -> EventAttachment -> Asset // one payload per imported attachment ```  ---@@ -80,7 +80,7 @@ Production policy should: - generate thumbnails locally; - keep decode/resize work off the main thread. -Exact maximum dimensions/byte target remain open.+Maximum Person photo dimensions are 2048 pixels, with a 4 MB encoded limit. Imports remove image location metadata.  --- @@ -95,7 +95,7 @@ Policy should: - preserve PDF as PDF where imported as PDF; - keep filename/content type metadata. -Exact resizing threshold remains open.+Event attachments accept JPEG/PNG/PDF up to 20 MB. Image imports produce fresh metadata-free images; the implementation downsamples to a 4096-pixel bound. PDF remains PDF.  --- @@ -121,23 +121,19 @@ Production requirements:  ## 8. Privacy -Still to decide before production schema finalisation:+Approved defaults; verification remains required: -- cloud-encryption options for asset/sensitive attributes;-- local file protection policy;-- Lock Screen/widget disclosure;-- export/delete semantics.+- use Apple platform/CloudKit protections without claiming custom end-to-end encryption;+- iOS protection after first unlock supports extensions;+- home-screen capture only; no Lock Screen disclosure;+- explicit versioned ZIP backup/import preview, ordinary archives and separately confirmed permanent deletion.  --- -## 9. Remaining production questions+## 9. Implementation and verification -The architecture is decided. Remaining policy questions are:--- Person-photo maximum dimensions/bytes;-- invitation image resize threshold;-- supported document content types;-- local thumbnail cache strategy;-- cloud encryption;-- whether Person photos ship in v1;-- ownership/reference rules if an Asset is ever shared by multiple domain records.+V5 source includes bounded background photo/attachment processing, app-owned imports,+size/type guards, metadata-free image encoding, local versioned thumbnail cache,+retained replaced photos and cancellable temporary document previews. Every related+record follows its FamilySpace store. Tests/builds and native/two-account delivery+are tracked in the implementation evidence; source presence is not transport proof.
docs/halo_family_design_pack/09-implementation-handoff.md Modified +25 / -20
diff --git a/docs/halo_family_design_pack/09-implementation-handoff.md b/docs/halo_family_design_pack/09-implementation-handoff.mdindex 0773407..2e2d179 100644--- a/docs/halo_family_design_pack/09-implementation-handoff.md+++ b/docs/halo_family_design_pack/09-implementation-handoff.md@@ -1,9 +1,11 @@ # Halo Family — Implementation Handoff -**Updated:** 2026-09-24  +**Updated:** 2026-10-07 **Working app name:** Halo Family   **Product family:** Halo  -**Readiness:** Ready to begin staged production implementation; not a fully closed specification.+**Readiness:** Application implementation in progress. Decisions 1 and 2 supersede+the original decision gates below; the current build plan and evidence document+distinguish implemented source from verified behavior.  ## Start here @@ -27,10 +29,10 @@ Implement settled requirements and ordinary reversible engineering details. For 2. FamilySpace is the collaboration boundary. Person is canonical identity; ChildProfile marks our children; Connection is child-specific. Sparse records and same-name distinct People are valid. 3. ConnectionContext records shared-context membership. ContextPerson records relevant teachers/coaches/etc. ConnectionOrigin independently records first meeting. 4. ConnectionOrigin is optional and singular per Connection. It links a Context or Event, never both, or uses free text alone; linked descriptions are allowed. No origin is required for quick capture and no earliest-context inference becomes a fact automatically.-5. Closeness: five UI positions, numeric domain 1...10, no sentiment, explicit-change history retained but hidden in v1. Labels/mapping remain open. Connection status: active/lostContact with free-text explanation.-6. Person-level deceased state with optional partial date and discreet Sensitive Details; preserve history and suppress inappropriate proactive surfacing. Representation and state-transition details remain gated.+5. Closeness: five UI positions (1 Met once, 3 Know them, 5 Friend, 7 Good friend, 10 BFF), numeric domain 1...10, no sentiment, explicit-change history retained. Competing temporal histories require explicit review. Connection status: active/lostContact with free-text explanation.+6. Person-level deceased state with optional partial date and discreet Sensitive Details; preserve history, keep explicit search available and suppress routine suggestions. It does not automatically rewrite Connection history. 7. Core Data + NSPersistentCloudKitContainer in host; Private/Shared App Group stores; same-FamilySpace store assignment. Local-only widget/intent coordinators, persistent history, asynchronous notification handling. Intent success means local save.-8. Core Data-managed Asset binary data with external storage. No separate asset sync stack. Photo scope and size/privacy policy remain open.+8. Core Data-managed Asset binary data with external storage. One primary Person photo plus Event images/PDFs; strip photo location metadata, limit photos to 4 MB and attachments to 20 MB. No separate asset sync stack. 9. Events are social memory, not calendar/reminder features. Explicit merge only; no automatic Person deduplication.  ## First implementation slice@@ -46,24 +48,27 @@ Start with Phase 1 and the settled subset of Phase 2:  A minimal Event needs identity, FamilySpace, a known date and a useful title; optional notes follow the model. Reuse it in Phase 5. Do not introduce invitation-state enums just to support an origin. Use free-text origin when a formal dated Event is not warranted. -ContextPerson associations can proceed independently of final role vocabulary. Keep unresolved role-dependent UI and final closeness control out of the completed-slice claim until decisions are made. Provide a runnable minimal UI without presenting it as approved final navigation.+ContextPerson supports multiple custom roles per Person/Context with optional dates per association. Role vocabulary and five-step closeness labels/mapping are approved; further role lifecycle and concurrent temporal histories remain gated. Provide a runnable minimal UI without presenting it as approved final navigation. -## Decision gates+## Current decision and delivery boundaries -| Before implementing/shipping | Resolve in open questions |+| Area | Current boundary | |---|---|-| Signed app/device validation | §17 production setup values |-| Final closeness control and concurrent history | §2 labels/mapping and temporal reconciliation |-| Origin suggestion/display rules, source deletion, concurrent origin edits or overlapping Connection merge | §4 applicable lifecycle policies |-| Complete ContextPerson role/lifecycle features | §6 vocabulary/cardinality and lifecycle |-| Deceased-date persistence and automatic status changes | §3 PartialDate and Connection presentation |-| Durable family schema | §8 primitives, assertions and address labels |-| Full Event planning/gifts/attachment associations | §9–10 state and ownership models |-| Person photos | §10 and §14 scope, limits and privacy |-| Final navigation, widgets and merge UX | §11–14 relevant decisions |-| Production schema promotion / reliance on release | §1, §14–15 lifecycle, encryption, migration, export/delete policy |--These gates apply to dependent work; they do not block unrelated phases. Class rollover is v2. Phase 11 hardening gates the chosen release without waiting for v2 work. Final v1 scope remains explicit and unresolved where noted.+| Signing and identifiers | Confirmed from repository; device installation still requires specific authority |+| Concurrent histories | Preserve competing accounts and require explicit review; stale review cannot silently replace a later account |+| Origins and ContextPerson | Independent origin/narrative, custom dated roles and retained history are approved |+| Family facts and deceased details | Sparse facts, assertions, custom labels and partial dates are approved; never invent relatives |+| Events and Assets | Separate invitation/attendance, multiple gift parties, images/PDFs and approved size/privacy limits |+| Merge and source deletion | Explicit preview, archived referenced records, undo only while affected records are unchanged |+| Sharing | All family notes/details visible to invited co-parents; warn before sharing; no private-per-parent notes |+| Backup/import | ZIP of JSON and attachments, preview import, never silently overwrite an existing family |+| Navigation and extensions | Routine reversible UX may be implemented; no Lock Screen family capture |+| Release | Actual account/share lifecycle, device/two-account checks, schema deployment and required gates remain separate |++The user approved continuing the full application implementation through the+remaining pack phases. Class rollover remains v2. Approval of the product defaults+does not authorize live family data access, sending invitations, destructive live+operations, signing changes, installation or deployment.  ## Verification and delivery 
docs/halo_family_design_pack/10-initial-implementation-results.md Modified +648 / -0
diff --git a/docs/halo_family_design_pack/10-initial-implementation-results.md b/docs/halo_family_design_pack/10-initial-implementation-results.mdindex 4337aa2..cd7e2f4 100644--- a/docs/halo_family_design_pack/10-initial-implementation-results.md+++ b/docs/halo_family_design_pack/10-initial-implementation-results.md@@ -1,5 +1,653 @@ # Implementation evidence +## Final local and focused native gates passed — 2026-10-07 UTC++Application source **`ed6991f`** passes **148 cases/17 suites in 7.923 seconds**,+JUnit zero failures/errors/skips, strict lint **0/89**, and sequential iOS+Simulator/macOS Debug builds with clean host/widget metadata extraction and+embedding. Tests/builds ran on the recorded dirty `3919848` tree; every tracked+hash matches the committed `ed6991f` tree. Full-run package coverage is archived.+Logs, JUnit, pre-run dirty-file copies and commit-tree proof are under+`/tmp/halo-final-layout-gate-inputs` and `/tmp/halo-final-layout-gate-*.log`.+No source hash changed during either gate, and no payload diagnostic appears in+this run. The earlier unconfirmed synthetic clone diagnostic remains recorded below.++The focused native XCTest case **passes once, zero failures, 54.147 seconds**.+Its runner exits **0 in 65.591 seconds**, without startup/teardown timeout. The fresh+owned iOS 27 simulator was verified signed out, used only its unique Debug synthetic+store and had no configured Halo widgets. Assertions verify People navigation,+library geometry clear of tabs and expanded/collapsed navigation titles, structured+name form/save, visible archive confirmation and restore, disabled Contacts controls,+and synthetic child/peer presence after explicit flagged relaunch. A saved/viewed+screenshot confirms the separate header and disabled Contacts screen. Before/after+read-only inspection retains one family, one child, two Persons, one Connection and+the observed child/family UUIDs. This establishes only these synthetic records and+forms; it is not production/account/cache or binary-payload preservation evidence.++Native evidence, the temporary driver and retained failed attempts are under+`/tmp/halo-native-smoke-804b98b`; the directory name is historical, and its final+receipt/summary identify `ed6991f`. Warm URL dispatch from the verified running+synthetic host succeeds but reaches the OS **“Open in Halo Family?”** confirmation.+It was not automated; warm capture acceptance remains pending that confirmation.+Cold URL and extension execution remain separately isolated future checks.++The owned simulator is shut down with fixture data preserved, all owned runners+are drained, and the exclusive heavy slot is released. No real Contacts/family+reads/writes, live fixtures, account/privacy/global-setting changes, physical install,+schema promotion or agent main push/merge occurred. Four full source review lenses+and scoped layout follow-ups are clear. The user-published base remains `8c5262f`;+authorized feature/draft publication follows the reviewed evidence.++## Corrected application gate and native diagnosis — 2026-10-07 UTC++At **`804b98b`**, **148 cases/17 suites pass in 8.624 seconds**, with JUnit+zero failures/errors/skips and command exit 0. `make -j1 check` passes strict lint+**0/89** and sequential iOS Simulator/macOS Debug builds, with clean host/widget+metadata extraction and embedding. Tracked source hashes are unchanged by both+runs. Evidence is under `/tmp/halo-corrected-gate-inputs` and the corresponding+`/tmp/halo-corrected-gate-*.log` files.++The full test log contains one Core Data external-payload clone diagnostic for an+absent file in a temporary synthetic store. All assertions pass. A focused asset+repeat passes **3 cases/1 suite in 0.769 seconds** without reproducing it; the cause+is unconfirmed. This diagnostic does not establish live cache/payload preservation.+The focused repeat overwrote package coverage before the full-run coverage was+archived. JUnit retains the exact full-run count; current coverage represents only+the focused three cases and is not reported as full-run coverage.++A fresh owned iOS 27 simulator was verified signed out in Settings, then launched+the source-bound host with a unique Debug synthetic-store directory. Native form+execution created one synthetic family, child and peer. The temporary XCTest driver+first failed compilation before any cases; after its selector compile fix, **one+case failed in 45.454 seconds** because the structured-name screen was not reached.+The screenshot shows the library menu overlapping the tab bar and intercepting+People navigation. After reporting the case, Xcode stalled during teardown; the+owned wrapper terminated it at **180.045 seconds**, with no runner left alive.+The assertion failure and later environmental stall are separate evidence.++The top-inset correction at `3919848` passes **148/17 in 7.241 seconds**, strict+lint **0/89** and both Debug builds, with full-run package coverage archived. Native+retry proved People navigation and structured-name editing, then failed one case+in **39.302 seconds** because the driver selected the archive control behind its+confirmation popover. A preceding retry failed one case in **14.547 seconds** after+reinstallation rotated the owned app-container path; the host correctly refused the+stale path, and the synthetic stores were found in the current container. Its+post-case stall was bounded at **180.031 seconds**. Neither fixture issue required+permission/security changes or weaker assertions.++The new screenshot also shows the top inset overlapping a collapsed navigation+title. The final scoped correction therefore places the library/invitation header+and workspace as separate children of an explicit root VStack; its final local and+focused native gates pass as recorded above. The driver selects the unique hittable archive+confirmation rather than an index among duplicate labels.+No real Contacts/family data, account changes, widget/Shortcut execution or cold+URL launch occurred. The user published `main` themselves; read-only fetch verifies+base `8c5262f`. Feature-branch/draft publication can follow the final local gate;+no agent main push, merge or schema promotion is authorized.++## Final publication review corrections — 2026-10-07 UTC++The complete unpublished history was reviewed at `f7a6afd`, including the initial+commits because the configured private GitHub repository has no branches. Final+review found and corrected three issues: an already ended membership could have+its date overwritten; state-list reads repeated the same family-root count for+each Connection; and native file-provider reads materialized an entire file before+enforcing the limit. The fixes retain the first end date, check root uniqueness+once per family/store within a synchronous batch while retaining each record's+permissions, and bound the read to the 20 MB attachment limit plus one byte with+cancellation/handle/security-scope cleanup. Historical Context memberships remain+closable after Context archival.++Two new behavioral regressions cover stale membership closure and batched reads+with denied/ambiguous/foreign references, preserving private/shared qualification+even for equal UUIDs. The current source declares **148 tests in 17 suites**.+The gate at `804b98b` now passes **148/17**, strict lint **0/89** and both Debug+builds, as recorded above. The earlier `f7a6afd` gate remains exactly **146/17**.+The subsequent native layout correction’s passing gates are recorded above.++Read-only scanning covered 336 reachable historical blobs and the supplied ZIP's+12 Markdown documents. No credential patterns or private stores/exports were found;+source/test review found synthetic fixtures. Configuration bundle/team/container+identifiers are retained. This is a scoped scan, not a guarantee about arbitrary+prose. All historical commits and the supplied design archive are preserved.++The user has since published the remote `main` base themselves. No agent main+push, remote default-setting change, merge or schema promotion occurred. Draft+publication now has the subsequent native layout correction’s passing gates.++### Smallest later synthetic/native acceptance plan++Run after the parent grants one native slot, on a **fresh simulator with no account,+family data or configured Halo widgets**. Use Debug `--synthetic-store` with a unique+directory inside that simulator's temporary directory. Keep one host window; avoid+library switching, sharing/invitations and Photos/Contacts selection. Do not reset an+existing simulator or change account/privacy settings.++1. Create one synthetic family, two children and one shared Person. Capture a name,+   edit display/given/family names, and verify both child relationships keep identity.+2. Set first-meeting memory and a separate Context membership. End membership,+   archive its Context, and verify the origin and retained history remain independent.+3. Add a synthetic Event and generated PNG/PDF from a fixture directory. Verify+   thumbnail/preview and size rejection; use Files only, with no personal photo picker.+4. Preview an explicit merge, undo it, archive/restore Person/ChildProfile/group,+   and confirm stale/duplicate actions reject without losing earlier history.+5. Export only this synthetic family, preview it, import a fresh-identity copy and+   relaunch the same synthetic directory. Compare IDs/history/assets within that+   directory; label any file listing as metadata evidence separately.+6. With the synthetic host already running, open a deep link built from those+   synthetic scoped UUIDs, exercise capture with and without Context, and confirm+   Apple Contacts controls remain disabled. Relaunch explicitly with the same+   synthetic flag; a system cold launch through a URL does not inherit it.++The host Debug flag does **not** isolate WidgetKit/Shortcuts: their catalog opens+production App Group/account stores. Host saves also request timeline reloads, so+the shared Mac's potentially configured widgets must not be used for this check.+A plain synthetic coordinator also does not establish production history delivery,+cross-window changes or account lifecycle behavior.+Cold URL launch needs a separately isolated native fixture because it does not+inherit the host's temporary-store argument.++| Remaining check | Can be verified safely later | User action actually required |+| --- | --- | --- |+| Host forms, backup/copy, generated assets, relaunch and synthetic deep links | The fresh-simulator walkthrough above after scheduling; no real data | Only an OS authorization prompt if one appears; no permission automation |+| Large generated stores, quota/failure paths and SQLite/payload protection | Synthetic fixtures in a scheduled local batch | A physical install or locked-device check needs device-specific authority |+| Widget/Shortcut execution and cached/redacted timelines | Separately isolated native fixtures on a fresh simulator; host flag alone is insufficient | Physical authentication/lock-screen verification needs the authorized test device and user authentication |+| Native Contacts picker/create/unlink | Domain link files are already synthetic; native calls remain disabled in host fixtures | An explicitly authorized test address book/device and permission prompt; no real Contacts reading/writes |+| Account loss/change, actual sharing/read-only/reinvite/offline delivery, existing-share migration and cache contents | Further domain failure simulations are safe but do not establish framework/live behavior | Separate authorized test accounts/devices/shares and user-driven account transitions; no global account changes by the agent |+| Production CloudKit schema, invitations, physical deployment, permanent live deletion and main merge | Preparation and read-only review | Specific authority for each actual action; current draft policy does not authorize them |+| Graph and class rollover | Graph still needs representative data; rollover remains v2 | Data access/scope approval or a later feature request respectively |++## Combined application gate at f7a6afd passed — 2026-10-07 UTC++**146 tests in 17 suites passed in 7.034 seconds**, test command exit 0. JUnit+contains 146 cases with zero failures/errors/skips. `make -j1 check` then passes+strict lint (**0 violations/89 files**) and both iOS Simulator/macOS Debug builds,+exit 0. Host and widget AppIntents extraction completes on both platforms without+extractor diagnostics; four nonempty parsed metadata files contain the corrected+entity types, and both app products validate their embedded extension.++The source is `04eea67` plus the reviewed gate corrections below and the preserved+Xcode project normalization. Exact tracked hashes and dirty-file copies are recorded+under `/tmp/halo-final-gate-inputs`. The final unit package/test/model sources match+the final built tree byte-for-byte; builds changed no tracked source. Xcode's earlier+normalization of extension destination/runpaths is retained unchanged and now has+both-platform build evidence. No owned heavy runner remains active; the shared slot+is released for the parent's next batch.++Corrections discovered by execution, with every case retained:++- One account permission identifier redeclaration and three missing throwing fixture+  evaluations stopped three initial attempts at compilation; no tests ran in those+  attempts. Backup resolves its frozen model inside the background operation instead+  of capturing a non-Sendable model value.+- The first runtime attempt recorded **29 passes and six failed-case lines** before+  an application `NSUnknownKeyException` on missing legacy Person `notes` aborted the+  runner with signal 6. This was a source/model failure, not an environmental stall.+  Legacy reads now provide an empty value and writes reject unsupported enrichment+  before mutation; the incorrect legacy fixture input now tests atomic rejection.+- FileHandle reports Cocoa missing-file code 4 on first use, not only code 260.+  Device Contacts mappings and share-denial reads accept these two absence codes;+  other errors/corruption still fail. Four observed Contacts failures are corrected.+- Two guarded merge undo failures came from permission checks after Core Data had+  nullified deleted generated rows' family link. The check recovers the committed+  family only for deleted nonroots and still validates scope/duplicates/access.+  The focused 19-case merge suite passes separately from the final full run.+- A completed full run had **145 passes/one failure in 7.319 seconds**. The fixture+  incorrectly excluded a valid related-name result; it now requires exactly both+  related people and still excludes another family. Production search is unchanged.+  A model-bound fetch request reused across backup coordinators was also corrected,+  retaining UUID and undo assertions.+- The first platform check failed macOS Contacts compilation. Its iOS build reported+  success while AppIntents extraction emitted invalid-identifier errors, so it was+  not accepted as a clean gate. The picker uses the SDK's imported method; intent+  type identifiers use legal stable names, and static metadata remains nonisolated+  without applying that annotation to mutable parameter wrappers. Record IDs,+  authentication, permissions and local capture behavior are unchanged.++Four final source lenses are clear. Coverage JSON was collected for the package;+it does not measure native UI or extension execution. Expected invalid-PDF fixture+logging and existing optional-checkpoint/unused-fixture-result compiler warnings+are not assertions or runner stalls. Earlier failed/aborted logs and JUnit are retained.++Evidence: `/tmp/halo-final-gate-tests.log`, `/tmp/halo-final-gate-build.log`,+`/tmp/halo-final-gate-tests-compile-{1,2,3}.log`,+`/tmp/halo-final-gate-tests-runtime-{1,2}.log`,+`/tmp/halo-final-gate-build-failure-1.log`, and structured results in+`/tmp/halo-final-gate-inputs` (JUnit, coverage, source hashes and metadata checks).+Native UI/Contacts/widget/Shortcuts behavior, locked-device/cache privacy and actual+account/share/offline/cache-retention, quota/large-data/CKShare/schema gates remain+unrun. No real family data, live fixtures, physical installation, account/signing+configuration changes, push or main merge occurred.++## Person enrichment and archival source closure — 2026-10-07 UTC++Person details now edit optional given/family names independently from the required+name or description. One guarded save includes all fields; omitted structured names+preserve lightweight callers' existing values. Merge previews choose display, given+and family names separately, and guarded undo restores them with the original metadata.+Legacy V1/V2 edits remain supported without writing unavailable attributes.++Ordinary Person, ChildProfile and PersonGroup removal now archives, retaining UUIDs,+relationships, memberships, origins, gift parties, address labels and encoded assets.+Include archived exposes explicit restore. Archived people/children stop current+capture suggestions; stale writes and background photo imports reject archived owners.+Merge aliases cannot be restored through ordinary archive controls. Archive confirmation+freezes the reviewed record revision and states the effect on shared family views.+The iOS store explicitly requests the platform's existing after-first-unlock protection;+actual SQLite sidecars/external payload protection remains a runtime check. Dynamic+persistence errors use private OSLog interpolation. Explicit device-only stacks do not+construct a CloudKit container.++Fourteen further synthetic cases bring the current inventory to **146 declared tests+in 17 suites**. Strict lint passes **0 violations/89 files** and whitespace checks pass.+These declarations have not been compiled or executed. The last executed passing gate+remains **3286293: 79 cases/10 suites and both Debug builds**. Four independent final+source reviews identified two association archive-boundary gaps. Role saves now+revalidate the linked Person and membership-ending actions revalidate the linked+group inside their transaction; focused regressions preserve archived Context role+history editing. All four final source rechecks are clear; no current build or runtime pass is claimed.++### Approved plan reconciliation and remaining release checklist++| Plan section | Source status | Remaining evidence or dependency |+| --- | --- | --- |+| Phase 0 | Historical spike complete within its recorded scope | Does not establish the current application's release gates. |+| Phases 1–2 | Production stores/sharing, relationship workspace, capture, membership, origin/temporal history and Review implemented; local gate and focused capture/People forms pass | Broader Context/origin/history forms and actual sharing/transport validation. |+| Phases 3–5 | Approved photos, family knowledge, Sensitive Details, groups, social Events/gifts/attachments and archive/restore implemented | Native UI, image/document memory behavior and real shared delivery. |+| Phase 6 | Explicit field/overlap merge, retained identities, guarded undo and competing-account recovery implemented; local regressions pass | Actual two-account/offline histories and existing CKShare migration. |+| Phase 7 | Optional native Contacts and isolated device-local links implemented | Permission/picker/create/unlink behavior on an explicitly authorized test address book. |+| Phase 8 | Deferred by the approved real-data prerequisite | Enough representative data and authority to use it; no live family inspection performed. |+| Phase 9 | Native widget, scoped typed capture and compact host form implemented; metadata/embedding pass both builds | Configuration, authentication, cold/warm URLs, locked-device redaction and cached timeline behavior. |+| Phase 10 | v2 | Separate class-rollover design and implementation when requested. |+| Phase 11 | Account/access guards, bounded backup/import, private logs and explicit store protection implemented | Runtime/account/schema/storage gates below. History retention is approved until safe pruning is verified. |++- **Local gate complete:** 146 cases/17 suites, strict lint and both Debug builds pass+  with current metadata/embedding checks. The historical source checkpoint below+  preserves its earlier pending status; native runtime acceptance remains separate.+- **Synthetic runtime hardening:** native forms and backup preview/restore/copy,+  quota/storage failures, image memory limits, large generated datasets, and actual+  SQLite/WAL/external-payload file protection. Domain tests cover local invariants;+  they do not substitute for these runtime observations.+- **Authorized account/device validation:** no-account and later restoration,+  account change, exact-share removal/read-only/reinvitation/offline behavior,+  two-account delivery and migrations of existing shares. Framework-managed cache+  content preservation needs evidence beyond retaining filenames. Legacy unscoped+  caches remain unattached until owner provenance is established.+- **Explicit release actions:** production CloudKit schema promotion, live invitations+  or private-data operations, physical-device installation, signing/account changes,+  permanent live deletion and merge/main publication need specific authority.+  Feature-branch/draft PR publication follows the user's review policy after the+  required local gate; it never implies an automatic merge.+- **Conditional source scope:** the approved permanent-delete behavior is a separate+  explicit action showing sharing impact. Phase 11 makes its implementation conditional+  on the agreed release scope; it is not an unresolved security/product decision or+  an unconditional source blocker. Ordinary removal is implemented as archive/restore.++## Widget and typed capture source increment — 2026-10-07 UTC++A native WidgetKit extension now shares the versioned persistence sources and+typed AppEntity/intent definitions with the host. It opens read-only, host-prepared+local stores, selects a child and an optional default Context, and opens a small+host capture form through a scoped UUID-only URL. The host handles cold loading+and explicit device/account library selection before resolving the current child.+Shortcuts provides the same name/description plus optional Context capture using+a local writable `.appIntent` coordinator and device authentication. Neither+extension role configures CloudKit mirroring; success describes a local save.++References contain account/environment namespace, Private/Shared qualification,+family UUID and record UUID. Queries and execution re-resolve current permissions+and labels, reject stale/ambiguous, archived, deceased or merged child selections,+and reject unavailable or cross-family Contexts without partial writes. Optional+Context creates membership in the same transaction, never a first-meeting origin.+The native form preserves a failed default selection instead of silently omitting+it. Home-screen/desktop small and medium widgets show only the selected child,+family label and optional Context; they load no photos, notes or relationship lists.+Private content is marked privacy-sensitive, with generic previews/placeholders.+iOS StandBy/CarPlay locations are disfavored; this is a platform hint, not a ban.++Twelve new synthetic cases bring source to **132 declared tests/16 suites**.+Strict lint passes **0/86 files**, plist/project syntax validates, and no heavy+Halo runner has started. New test compilation, AppIntents metadata extraction,+extension embedding and both Debug builds await the shared slot. The last+executed passing gate remains **3286293: 79 cases/10 suites and both Debug builds**.+Native widget configuration, cold/warm URLs, authentication, locked-device+redaction and system timeline refresh/cache behavior remain unrun release gates.+Host saves, history refresh and session lock request timeline reload; WidgetKit+scheduling does not promise immediate removal of a cached name after access changes.++Phase 9 is implemented as source with runtime gates pending. Phase 8 retains its+real-data prerequisite and Phase 10 remains v2. Persistent history remains retained+under the approved interim policy. Actual account/cache retention, share lifecycle,+legacy cache recovery, quota/large-data behavior, native UI and production schema+gates remain separate; none are established by the historical spike or source lint.++## Account/access source increment — 2026-10-07 UTC++Source now selects two stores under a SHA-256 account/environment namespace only+following account identity verification, with a separate explicitly selectable+on-device library that never mirrors CloudKit. Existing unscoped SQLite files are+left in place and are not attached to an unproven owner. Device-only memories+remain selectable after signing in; moving them to iCloud requires explicit+backup/import. The opening account-change signal is armed before identity lookup+and store attachment. A retained CKContainer receives account notifications.++Account changes invalidate reads and serialize final local saves against the+in-process signal. The UI hides locked sessions and teardown detaches stores+without deleting SQLite. Teardown is idempotent; background history/assets/import+results check access again before publication. Each grant contains both family+UUID and Private/Shared store identity, so an original-ID restored root cannot+lend permission to its later Shared counterpart. Multiple roots with the same+UUID within one store are also rejected at query/reference boundaries, including+before the next history refresh.++Extensions recheck a bounded host manifest under the permission lock. Shared+errors temporarily require server permission verification; permanent denials are+recorded only for the exact queried share. Read-only downgrades remain readable.+Explicit successful reinvitation clears only that share's denial; old cached+removed metadata does not recreate a permanent denial. Unrelated valid shares+can regain access following verification. Unknown/offline verification failures+leave shared access locked and Private data available.++Fourteen new synthetic cases are drafted: **120 declared tests/15 suites**,+strict lint **0/79 files**, with new test compilation and both builds pending the+shared Mac slot. The last executed passing gate is still **79 tests/10 suites**+and both Debug builds at **3286293**. Initial source reviewers identified startup,+save, manifest ordering, cross-store identity, stale teardown/publication and+reinvitation/revocation issues; fixes and regression source passed all four final read-only reviews.+Corrections also include duplicate roots within one store, library preference+changes in every window, overlapping share-verification retry, and avoiding a+root-count query per exported row. Permission updates and account invalidation+share a save gate; ordinary permission reads use a separate short lock.++No account status lookup, real store opening, CloudKit share fetch/update, native+Contacts call or real family backup was performed by this implementation task.+Actual no-account/restoration, account-change, revocation/reinvitation and offline+runtime gates remain unrun. Core Data may itself purge or alter cached content+before observer-driven detachment; retaining paths alone is not proof of retained+cache contents. Legacy unscoped recovery needs owner-provenance evidence before+those stores can be attached. CloudKit schema promotion and device/two-account+release validation remain separate blockers. Widget/intent product UX remains active.+++## Backup, categories and search source checkpoint — 2026-10-07 UTC++The source on verified V6 now adds versioned JSON plus payload ZIP export, an+optional Markdown summary, native preview/import and an atomic Private-store+restore. Existing identities in either local store reject original-identity+restore; an explicit copy receives a fresh identity namespace, including historical+merge references. Competing accounts remain retained. Historical merge undo is+disabled in copied families; absent-family restore retains its existing guards.+Apple Contacts mappings are excluded. Native selection/export requires only the+user-selected document; no real family export or Contacts operation ran here.++Context categories are ordinary editable labels: five starters in newly created+families, explicit starter addition for older families, stale-edit checks and archive+without dropping Context links. People search now includes structured names,+entered family/address titles, roles, groups, related names and nested Context paths.+Person details display every Context role and optional date, including history.+Search does not infer gender or culturally specific titles.++This source batch declares **106 tests/14 suites**: six Contacts, eleven backup,+six category and four search cases above the verified 79. Strict lint passes+**0/74 files**; compilation/tests/native runtime are pending the shared-Mac slot.+Fixture-only role references use the actual `.appIntent` enum case; the earlier+Contacts draft's `.intent` spelling was not compiled. Four independent source+reviews identified ownership-derived photo limits, indexed inverse validation,+streamed history validation, copied UUID ordering and cancellation/staging cleanup;+those corrections are implemented. All four final source reviews are clear.++Backup limits are explicit: stored ZIP32 only, 1 GB/10,000 members, 32 MB manifest,+100,000 current records, 16 MB per merge snapshot, and aggregate preview/restore+payloads of 128 MB on iOS / 512 MB on macOS. Photo/Event payload limits follow+actual ownership (4 MB/20 MB), independently of mutable kind metadata. Absence+checks cover these local stores, not unseen records on another CloudKit device.+No native UI, live CloudKit, no-account/account-change/share-removal or production+schema evidence is claimed. Extensions and lifecycle work remain active; graph+visualisation still has its real-data prerequisite, and class rollover remains v2.++## Contacts source checkpoint — 2026-10-07 UTC++Optional native Contacts selection/create routes and linked-state/unlink UI are+integrated onto verified V6 commit `3286293` from source commit `e9ae0b7`.+Family/person UUID-scoped identifiers/selection labels remain in a device-local+bounded file actor; they are excluded from CloudKit, family export and device backup.+One actor per host stack serializes windows; change notifications refresh local UI.+Merged aliases retain both mappings; unlink never deletes an Apple Contact.++Creation presents editable given/family/nickname fields and explicitly saves only+those chosen values. Family notes/photos/Sensitive Details are not copied. A pending+local link survives write failure; retry only saves the mapping, and link actions+serialize so an older completion cannot clear another pending link. Bounded reads+reject corrupt/oversized local files without overwriting them. Synthetic/debug stacks+disable native Contacts access rather than relying on a synthetic Core Data directory+to isolate the user's address book.++**Source checks only:** strict lint 0/60 files and diff check pass. Six new cases are+drafted for local scope, reopening/idempotence/unlink, corruption/oversize,+concurrent windows, merge/undo and extension exclusion: **85 declared tests/11 suites**+in this checkout. No new test, compiler, permission prompt, picker or CNContactStore+operation has run. Four source reviews ran; the bounded-read and overlapping-link+findings were corrected and their focused rechecks are clear. A direct duplicate-save+guard also prevents queued creation actions from spawning two Contacts requests. Contact usage text and the+macOS app's address-book entitlement are source configuration for this optional feature;+signing identity/account/global settings are unchanged.++The separate V6 gate passes at main checkout commit `3286293`: 79 cases/10 suites+and both Debug builds. The Contacts source is now integrated on that checkpoint, retaining its seven+fixture-argument corrections before the pending 85-case gate. Backup/import, category/+search improvements, extensions and lifecycle hardening remain application work.++## Duplicate/merge implementation — 2026-10-07 UTC++Phase 6 source passes its required local domain/build gate. Model V6 retains+V1–V5 and adds retained Connection/ChildProfile aliases, merge audits, append-only+late-account review and explicit recovery records. Native previews require identity+confirmation and choices for competing first meetings/current periods. All reference+kinds are consolidated, original UUIDs and encoded asset payloads remain, self-facts+and self-Connections archive, and Event participation accounts stay separate.++Undo checks only affected metadata against the saved post-merge snapshot and restores+earlier references without overwriting unrelated edits. It removes only untouched+merge-generated proposals/periods; the audit retains their selection. Stale archived+record editors/captures reject. Earlier Connection details are read-only.++Late offline accounts are compared with ordered per-Connection audit/review snapshots.+Explicit transfer copies only unseen/changed accounts into the kept Connection as+alternatives, retaining the originals. Repeated/stale review actions reject. Circular,+opposing and unsupported merge aliases expose the People in Review. Recovery shows+separate identities while retaining current references/notes/photos and prior audits;+new explicit merges acknowledge observed recovery UUIDs. These are local causal+guards, not a CloudKit transaction or delivery claim.++**Final verified gate:** 79 tests in 10 suites passed in 5.020 seconds, exit 0;+strict lint **0/55 files** and sequential iOS Simulator/macOS Debug builds passed,+exit 0. JUnit contains 79 cases with zero failures/errors/skips. The initial test+attempt stopped at compilation: seven fixture status calls omitted an existing+required note argument. Correcting the calls retained every assertion and test case.+No startup/teardown stall or assertion failure occurred. Native UI and real CloudKit+transport remain unrun; synthetic opposing/offline account imports do not prove live+CloudKit delivery. All owned heavy jobs drained after this gate.++Four final read-only source reviews are clear. Corrections cover stale writes,+self-Connections, late account visibility, opposing/delayed recovery, repeated review+copies, synthetic first-meeting absence and repeated snapshot scans. Evidence:+`/tmp/halo-merge-tests.log`, `/tmp/halo-merge-tests-compile.log`,+`/tmp/halo-merge-build.log` and `/tmp/halo-merge-review-inputs/junit-swift-testing.xml`.+Verification source is `00abc82` plus the recorded fixture argument corrections;+this gate excludes the independent Contacts worktree.++Full application scope remains active after this increment: Contacts, backup/import,+categories/search/role visibility, extension UX and lifecycle hardening. No live+family data, live CloudKit fixtures, account/security changes, physical installation,+push or main merge occurred.++## Family/photo/social-memory implementation — 2026-10-07 UTC++The user approved the remaining defaults in Decision 2. V5 source and native views+now implement family facts/assertions, groups, editable address labels, partial+deceased dates, social invitations/attendance, multiple roles/gift parties, photos+and attachments, and explicit temporal conflict choice. The final gate passes:+**61 tests in 9 suites**, exit 0, 2.700 seconds test runtime; **strict lint 0/44+files**; **make check**, exit 0, with sequential iOS Simulator/macOS Debug builds.+Four source reviews identified and prompted fixes for event draft+baselines, visibility, bounded Photos transfer, temporary preview cleanup, cache+revisions, date-aware/linear kinship validation and guarded address-label edits.+Final review additionally caught invented dates during legacy undated Event edits+and stale relationship endings. Both were corrected with meaningful assertions+inside existing cases, then the suite and both builds passed again. No cases were+removed or weakened. Final read-only review has no outstanding material finding.++Two initial attempts stopped at compilation before running tests: Swift needed+an explicit family-fact result type, then the test macro's throwing inference+and a fixture helper's MainActor annotation needed correction. The successful+61-case runs had no assertion failures, startup stalls or teardown crashes.++| Check | Result | Evidence / limit |+|---|---|---|+| Sparse family facts, entered titles and date-aware kinship | passed | Synthetic direct assertions, absent ancestors, dates and conservative paths |+| Deceased details and suppression | passed | Partial precision, invalid dates, stale edits, preserved Connection identity/history and explicit search |+| Groups and scoped address labels | passed | Independent memberships, guarded corrections and retained endings |+| Invitation, attendance and multi-party gifts | passed | Separate states, stable edited gift identity, stale drafts and same-Event attachment guards |+| Bounded image/PDF imports and revisions | passed | Metadata removal, dimensions/limits, unsupported/invalid files, shared-store placement, replacement and relaunch |+| Reviewed temporal resolution | passed | Exact displayed sets, retained notes/periods, stale resolution and late arrival |+| Event enrichment/archive | passed | Stable origin references, legacy unknown-date preservation and stale guards |+| Both-store V4 → V5 migration | passed | Person UUIDs, role/origin/temporal preservation and new defaults; earlier migration suites retained |+| Strict lint and both Debug builds | passed | Final make check, exit 0 |+| Native UI, Photos/Files/QuickLook and real CloudKit delivery | not run | Local domain tests and compilation do not establish OS runtime behavior |++Evidence: `/tmp/halo-memory-tests.log`, `/tmp/halo-memory-tests-compile.log`,+`/tmp/halo-memory-tests-test-compile.log`, `/tmp/halo-memory-build.log`,+the two `*-before-review-fixes.log` files and+`/tmp/halo-memory-review-inputs/junit-swift-testing.xml` (temporary local files).++Remaining implementation includes merge/undo, Contacts, backup/import, extension+UX and lifecycle hardening, seeded editable Context categories, richer search and+Person-level Context role visibility. Native runtime, two-account delivery and production+schema authority remain separate; no real family data was read or imported.+++## Approved relationship defaults and native workspace — 2026-10-07 UTC++Model V4 retains V1–V3 and implements immutable causal first-meeting proposals.+Simultaneous first creation, replacement, clear/edit competition and late arrivals+retain separate accounts. Review requires an explicit choice; resolution acknowledges+only the heads actually displayed and retains every alternative. Stale drafts,+including a blank editor opened before an unseen clear, cannot silently overwrite+newer accounts. Malformed predecessor graphs are rejected without deleting records.++Five closeness controls map to 1/3/5/7/10; the full numeric 1...10 domain is preserved.+Only explicit changes create closeness history. Lost contact/reconnection retain the+same Person/Connection and earlier closeness/status periods. Overlapping current+periods remain stored and appear in Review, pending their approved resolution policy.+ContextPerson supports multiple custom dated roles and guarded role/date editing.+Context membership rows distinguish children and navigate to their Connection.++The app now uses Mac sidebar/iOS tabs for Children, People, Contexts, Events and+Review. Family selection is per window; changing family resets routes. Capture is+still child + name/description. Child lists prioritize explicit closeness and offer+lost-contact inclusion. Review collects sparse captures and conflicting relationship+accounts; failed refresh retains an error/retry surface rather than claiming completion.++Final local gates: **43 tests in seven suites passed**, exit 0; strict SwiftLint+**0 violations in 34 files**; **make check passed**, exit 0, including sequential+iOS Simulator and macOS Debug builds on Xcode 27.0 (27A266a).++An initial test attempt failed compilation in a Swift Testing key-path macro; the+equivalent predicate closure corrected it without weakening assertions. The first+platform attempt found conditional-layout grouping in a SwiftUI editor; wrapping+the shared modifier target corrected it. Both builds then passed, and a final+focused date-default fix was rebuilt on both platforms. The successful 43-case run+had no assertion failure, startup stall or teardown crash. No domain code changed+after that run; subsequent corrections were UI-only.++| Check | Result | Evidence / limit |+|---|---|---|+| Retained origin branches and explicit resolution | passed | Synthetic simultaneous first writes, edit/clear branches and retained alternative UUIDs |+| Late arrivals and stale resolution/blank editors | passed | New accounts remain reviewable; stale reviewed-head sets reject |+| Malformed history and numeric bounds | passed | Cycles beside valid heads, zero/out-of-range values preserve data and surface errors |+| Closeness, lost contact/reconnection and retained history | passed | Explicit changes, same-value no-op and stable Person/Connection identity |+| Multiple roles, role/date edits and child-qualified memberships | passed | Role identity, invalid ranges and stale-edit guards |+| Scoped Review and batched relationship state | passed | Separate families, duplicate input IDs and resolved review items |+| Both-store V1/V2/V3 → V4 migration | passed | Prior migration suites plus V3 legacy origin/account and roleless-link preservation |+| Cross-coordinator proposal/status/closeness refresh | passed | Local intent-role writes merged through persistent history |+| Strict lint and both Debug platform builds | passed | Final make check, exit 0 |+| Native runtime UI/OS sharing and two-account transport | not run | Compilation/local SQLite evidence does not establish these |+| Remaining family, Event, photo, merge and privacy features | blocked | Concrete durable defaults are awaiting user approval; overall application scope is preserved |+| Release account/share lifecycle and schema promotion | blocked | Policy/device evidence and specific production authority remain required |++Four read-only source reviews ran. Fixes include complete graph cycle validation,+one validated head set per write, accurate numeric-domain display, native section+route resets, invitation cancellation/presentation ownership, honest failed Review+states and compatible unknown-start date defaults. No live family data, CloudKit+fixture writes, account/signing changes, physical-device install or main merge occurred.++Evidence: `/tmp/halo-defaults-tests.log`, `/tmp/halo-defaults-tests-compile.log`,+`/tmp/halo-defaults-build.log`, `/tmp/halo-defaults-build-compile.log`,+`/tmp/halo-defaults-build-before-date-fix.log` and+`/tmp/halo-defaults-review-inputs/junit-swift-testing.xml` (temporary local files).+This completes the settled Phase 2 source increment; later ordered application+features and release evidence remain to be completed.++## Relationship graph and sharing plumbing — 2026-10-06 UTC++Feature branch `feature/relationship-graph` continues the existing two commits.+Native iOS/macOS sharing controls use host-only Core Data share APIs. FamilySpace+shares are reused, invitations are private/read-write, metadata is container-checked,+and cold/warm invitation delivery targets the Shared store. Failed acceptance retains+the invitation for retry. No live account or CloudKit fixtures were used.++Model V3 retains V1/V2 and adds Context hierarchy, ConnectionContext, ConnectionOrigin,+minimal Event and ContextPerson. Repository writes validate family/store boundaries,+cycles, date ranges, origin XOR/nonempty rules and stale editor snapshots. Membership+and origin remain independent. The temporary SwiftUI navigation now exposes People,+name search/review, enrichment, existing-person reuse, Contexts/membership/archive,+dated Event labels/notes and all three local origin forms. Final navigation is still open.++Environment: Xcode 27.0 (27A266a), macOS, actual temporary SQLite stores.+`make test` with coverage/JUnit flags passed **26 tests in five suites**, exit 0.+Strict lint reports **0 violations in 22 files**. iOS Simulator Debug build passed.+The macOS build initially found a renamed sharing-options SDK type; the corrected+`make build-macos` passed, exit 0. The combined `make check` attempt therefore failed;+the affected build and lint subsequently passed, without rerunning the unaffected iOS build.++An earlier runtime attempt recorded **13 passes**, then a signal-6 fault when a queued+automatic merge outlived a synchronous fixture's removed SQLite files. The new fixture+now relies on the repository's explicit local merge before return, preventing queued+automatic merges after teardown. No assertion failure preceded that crash. The final+26-case run passed. Source and throwing-expression fixture compile errors were also+corrected before the successful runtime run.++| Check | Result | Evidence / limit |+|---|---|---|+| Origin description, Context and Event round-trip/edit/clear | passed | Local SQLite; identity and linked description preserved |+| Empty/XOR/cross-family origin and stale origin edit/clear | passed | Invalid operations rejected without partial writes |+| Independent origins for two children sharing one Person | passed | One canonical Person; separate Connections |+| Later/ended memberships and archived origin source | passed | Source, origin and Connection preserved; no automatic origin inference |+| Hierarchy cycles, date ranges, cross-family memberships | passed | Repository validation and unchanged graph assertions |+| ContextPerson reuse and Person enrichment/search/review | passed | Relevant person needs no peer Connection; stale review cannot discard enrichment |+| All new entities placed in owner/participant family store | passed | Synthetic Private/Shared placement, not CloudKit delivery |+| Both-store V1/V2 → V3 migration, graph and Asset UUID/data | passed | Existing V1 migration plus new V2 migration with payload checks |+| Second-coordinator origin/membership/archive refresh | passed | Insert/update/clear through local intent-role coordinator and history merges |+| Host-only sharing boundary | passed | Local and extension coordinators reject CloudKit share preparation |+| Strict lint, iOS Simulator/macOS Debug builds | passed | Individual final gates as described above |+| Native UI launch/automation | not run | Debug-only synthetic-store launch path is available |+| Actual invitations, owner/participant delivery, offline recovery | not run | Plumbing compiles; real device/two-account validation remains required |+| Simultaneous origin conflict preservation/review | not run | Product default approved; next implementation increment |+| Closeness controls and multiple dated ContextPerson roles | not run | Product defaults approved; next implementation increment |+| Source deletion, merge, account/share removal and release hardening | blocked | Policies or device/release evidence still required |++Four read-only source reviews ran. Findings about stale drafts, Event disambiguation,+Person relationship visibility, repeated global refresh and duplicated Person creation+were corrected. Logs/results: `/tmp/halo-graph-tests.log`,+`/tmp/halo-graph-tests-fixture-crash.log`, `/tmp/halo-graph-build.log`,+`/tmp/halo-graph-macos-build.log`, `/tmp/halo-graph-lint.log`, and+`/tmp/halo-graph-review-inputs/junit-swift-testing.xml` (temporary local files).++This is a tested implementation checkpoint. Whole-product completion and live sharing+are not claimed. Continue the approved defaults and remaining ordered roadmap work.++---+ ## Persistence foundation — 2026-10-07  The setup values are confirmed in Xcode and the app uses the production App
docs/halo_family_design_pack/CHANGELOG.md Modified +67 / -0
diff --git a/docs/halo_family_design_pack/CHANGELOG.md b/docs/halo_family_design_pack/CHANGELOG.mdindex aee02d0..d72a958 100644--- a/docs/halo_family_design_pack/CHANGELOG.md+++ b/docs/halo_family_design_pack/CHANGELOG.md@@ -1,5 +1,69 @@ # Halo Family — Pack Changes +## 7 October 2026 UTC++- Record final application source `ed6991f`: 148 cases/17 suites pass in 7.923+  seconds, full package coverage archived, strict lint 0/89 and both Debug builds+  pass. Focused native layout/names/archive/disabled-Contacts/relaunch case passes+  in 54.147 seconds with runner exit 0. Keep warm URL OS confirmation and broader+  native/live gates explicit; release the owned simulator/test slot.+++- Place the library menu and invitation notice in a separate vertical header after+  synthetic native checks showed tab-bar and collapsed-title overlap. Preserve the executed `804b98b` gate:+  148 cases/17 suites, strict lint 0/89 and both Debug builds. Record the native+  failed case, bounded teardown stall and unconfirmed synthetic payload diagnostic.+++- Correct final-review membership stale writes, state-read root-check repetition and+  unbounded file-provider reads. Current inventory is 148 declarations/17 suites;+  strict lint 0/89, new test/build gate pending. Keep `f7a6afd` 146-pass evidence exact.+- Add the smallest safe synthetic native acceptance plan, explicit host-only isolation+  limits and remaining user-action requirements. Remote publication needs a base branch.++- Record the passing current 146-case/17-suite gate (7.034 seconds), JUnit zero+  failures/errors/skips, strict lint 0/89 and sequential platform builds. Validate+  host/widget metadata and embedded extensions; retain exact earlier failures and+  runtime/account/schema acceptance limits. Preserve all source cases and commits.++- Close native structured-name and ordinary Person/ChildProfile/PersonGroup archive/+  restore source gaps; include explicit name merge choices and retained undo/assets.+  Current inventory is 146 declarations/17 suites, strict lint 0/89; combined gates+  remain pending. Reconcile each plan section and conditional permanent-delete scope.++- Add native per-child widget, scoped typed entities, authenticated local capture+  intent and host capture form with optional Context membership. Twelve new source+  cases bring inventory to 132/16 suites; strict lint 0/86 and valid project/plists.+  Keep compilation, extension metadata/runtime and combined gates pending.++- Add account/access lifecycle source and fourteen synthetic regression cases;+  120 declared cases/15 suites, strict lint 0/79 files. Keep test/build and actual+  account/share/cache-retention gates pending; preserve the prior verified evidence.++- Add V6 duplicate/merge source, explicit previews, retained original records,+  guarded undo, late-account Review and conservative recovery of competing aliases.+  The V6 build/test gate passes: 79 cases/10 suites, strict lint 0/55 and both Debug builds.+- Record the verified V5 family/photo/social-memory gate: 61 tests/9 suites,+  strict lint 0/44 and both Debug builds. Keep runtime/transport evidence separate.++- Document V4 causal origin proposals, clear/resolution guards and legacy migration.+- Implement approved closeness labels/numeric domain, contact periods and dated roles.+- Add synthetic simultaneous-origin, late-arrival, malformed-history, stale editor,+  migration and cross-coordinator fixtures. Final gates pass 43 tests/seven suites,+  strict lint 0/34 files and both Debug builds. Implement reversible native workspace+  navigation and honest Review error states. Preserve remaining temporal, family,+  Event, asset and privacy choices; native/runtime and CloudKit transport are not verified.++## 6 October 2026 UTC++- User approved separate first-meeting source/narrative display, retention/review+  of competing offline origin proposals, five closeness labels and multiple custom+  roles with optional dates. Record the corresponding numeric mapping and causal+  proposal representation as implementation choices in `decision_log.md`.+- Remove resolved label/role/origin-conflict questions. Preserve unrelated rename,+  deletion, merge, temporal history, privacy and release gates.+- Add V3 relationship/sharing implementation progress and precise local verification.+ ## 24 September 2026  Source: the user-supplied `kids_relationship_app_design_current.zip` dated 22 September 2026. Original archive preserved.@@ -14,3 +78,6 @@ Source: the user-supplied `kids_relationship_app_design_current.zip` dated 22 Se - Preserved unresolved product/schema choices; clarified attachment association ambiguity and temporal concurrency as decision gates.  Documentation consistency and ZIP integrity were checked. No application build, automated application test or device validation was run for this documentation revision. Historical spike results retain their original scope; no-iCloud-account validation remains deferred.++- 2026-10-07: Record backup/import, editable categories, richer search and Person role+  source with exact pending verification inventory. Preserve V6 verified evidence.
docs/halo_family_design_pack/README.md Modified +12 / -2
diff --git a/docs/halo_family_design_pack/README.md b/docs/halo_family_design_pack/README.mdindex 0596c0f..949bf8b 100644--- a/docs/halo_family_design_pack/README.md+++ b/docs/halo_family_design_pack/README.md@@ -3,7 +3,7 @@ **Working app name:** Halo Family   **Broader product family:** Halo   **Platform:** Native iOS  -**Status:** Ready for staged implementation; unresolved decisions remain explicit  +**Status:** Approved application source implemented; broader native/release acceptance pending **Storage:** On-device + iCloud/CloudKit only   **Collaboration:** Shared `FamilySpace` between parents/co-parents @@ -40,7 +40,17 @@ The persistence spike concluded successfully enough to make a production decisio - persistent history + remote-store notifications for cross-process change delivery - binary assets with external storage enabled -The only deliberately deferred architecture validation is behaviour when **no iCloud account is available**, including later account restoration.+Account/access lifecycle is now implemented as source, including a separate device-only library. Actual no-account/restoration, account-change, share-removal/reinvite and framework cache-retention validation remain release gates; see [current implementation evidence](10-initial-implementation-results.md).++Person structured names, ordinary Person/ChildProfile/PersonGroup archive/restore,+per-child WidgetKit and typed AppIntent capture UX are now implemented as source,+with optional Context membership and a compact host form. At `ed6991f`, 148+cases/17 suites pass in 7.923 seconds, strict lint 0/89 and both Debug builds pass,+including host/widget metadata and embedding. The separate library header and+focused native forms/archive/disabled-Contacts/relaunch case pass in 54.147 seconds+with runner exit 0. Warm URL acceptance awaits the OS Open confirmation.+Native execution/privacy and actual account/share/cache/schema acceptance remain+separate; see the current evidence and smallest synthetic acceptance plan.  ## Document policy 
docs/halo_family_design_pack/decision_log.md Added +104 / -0
diff --git a/docs/halo_family_design_pack/decision_log.md b/docs/halo_family_design_pack/decision_log.mdnew file mode 100644index 0000000..99707e0--- /dev/null+++ b/docs/halo_family_design_pack/decision_log.md@@ -0,0 +1,104 @@+# Decision Log: Halo Family++## Quick Decisions++| ID | Date | Decision | Rationale |+|---|---|---|---|+| Q1 | 2026-10-06 UTC | Five closeness choices: 1 Met once, 3 Know them, 5 Friend, 7 Good friend, 10 BFF | User approved the proposed labels; numeric mapping is the corresponding adjustable implementation choice. |+| Q2 | 2026-10-06 UTC | Display the linked first-meeting Context/Event separately from the parent-entered description | User approved preserving both pieces without choosing one display field over the other. |+| Q3 | 2026-10-06 UTC | Allow multiple custom roles for one Person in a Context, with optional dates per role association | User approved custom role multiplicity and optional dates; no Adult/Child entity split. |+| Q4 | 2026-10-07 UTC | Use Children, People, Contexts, Events and Review navigation, with a Mac sidebar and iOS tabs | Reversible implementation choice within the pack's UI direction. Keep per-window family selection and reset routes when changing family. Prioritize explicit closeness in child lists; lost contact can be included deliberately. |+| Q5 | 2026-10-07 UTC | Retain source Connection accounts on archived records; transfer only late unseen/changed accounts as alternatives through Review | Implements the approved retention/review default. Keep original UUIDs, source histories and separate Event accounts; local snapshot checks do not claim a CloudKit compare-and-swap. |+| Q6 | 2026-10-07 UTC | Recover competing merges by exposing separate identities while preserving current references and all earlier audits | Reversible conservative recovery avoids replaying old references over later edits. Current unsupported aliases remain visible; subsequent explicit merges acknowledge observed recovery UUIDs. Recovery is described separately from guarded undo. |+| Q7 | 2026-10-07 UTC | Separate verified account/environment stores from an explicitly selectable device-only library; retain unscoped stores without attaching them | Reversible privacy-preserving implementation of approved account lifecycle defaults. Never automatically upload device-only data or guess the owner of an old cache. Legacy recovery and framework retention still require evidence. |+| Q9 | 2026-10-07 UTC | Per-child small/medium widget opens a compact name capture form; authenticated typed Shortcut captures locally with optional Context membership | Reversible Phase 9 implementation using existing native forms and persistence roles. Scoped UUIDs re-resolve current access; optional membership never infers origin. Generic previews, privacy-sensitive rendering and timeline reload requests require native cache/redaction evidence before reliance. |+| Q8 | 2026-10-07 UTC | Qualify permissions by family UUID plus owning store; temporarily lock ambiguous share errors and verify each exact share | Prevents an original-ID Private backup from granting access to a Shared counterpart, and avoids declaring unrelated invitations revoked. Confirmed denials require explicit reinvitation. |++## 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.

Things to double-check

Exact current gate

Recorded dirty 3919848 tree committed byte-for-byte as ed6991f: 148 cases/17 suites in 7.923 seconds, command exit 0, JUnit zero failures/errors/skips; strict lint 0/89; both Debug builds pass with clean host/widget extraction and embedding. Full-run coverage archived. commit-tree-proof.json records all tracked hashes.

Preserve diagnostic history

804 b 98 b passed 148 cases in 8.624 seconds but emitted one missing temporary synthetic external-payload clone diagnostic. Focused 3-case asset run passed 0.769 seconds without reproducing it; current 3919848 full run has no such diagnostic. Cause remains unconfirmed; no live payload/cache claims.

Focused native and retained failures

Final ed6991f case passes once with zero failures in 54.147 seconds; runner exit 0 in 65.591 seconds, no timeout. Assertions cover tab/title geometry, People navigation, structured-name form/save, visible archive confirmation/restore, disabled Contacts and synthetic relaunch. Read-only counts and child/family UUIDs are retained. Historical native failures 45.454/14.547/39.302 seconds and their 180-second post-case bounds remain separately recorded. Warm dispatch stops at the OS Open confirmation; capture through that URL remains unverified. Owned simulator shut down and runners drained.

Remaining release evidence

Full native assets/events/backup/merge/Context walkthrough, Contacts permission/picker/create/unlink, WidgetKit/Shortcuts execution, authentication/cache redaction, actual account/share/offline/framework retention, existing shares, quota/image-memory/large-data and production schema remain separate gates. No live family/Contacts data, physical install, account/global-setting change, schema promotion or merge occurred.

Documentation-only publication head

9445a27 only updates exact gate/native evidence and release checklists. Every application/test/build file remains identical to tested ed6991f; tests are not repeated for documentation-only changes. Feature commits: 15, merge base: 8c5262f. No main push/merge.

Preserved Markdown whitespace

The final correction/documentation diffs pass whitespace checks. The full feature diff against main retains one approved historical Markdown hard-break line in decision_log.md:19. Initial empty-tree review retained 20 such original lines. No source whitespace errors or preserved-pack rewrites were introduced.