Native per-child widget and authenticated local typed capture. Source checkpoint; scheduled runtime gate pending.
One per-child small/medium widget opens a compact host form; typed Shortcuts requires device authentication and writes through a local intent coordinator.
Optional Context is membership only, committed atomically without inventing an origin. Current scoped identities reject stale or cross-family selection.
Generic previews and privacy-sensitive content load no photos, notes or relationship lists. OS redaction, cached timelines and account lifecycle remain runtime gates.
Source reviewed; runtime pending
Four independent source reviewers clear the final source after fixes. Strict lint, whitespace and project/plist syntax pass. Transit owns the shared heavy slot: current test compilation, all 132 declared cases, extension metadata extraction/embedding and both Debug builds remain unrun. Last executed passing gate is 3286293:79 cases/10 suites and both Debug builds. No remote publication or actual account/private-data operation.
working-tree Reviewed widget and typed local capture source Choose a child in the widget, tap Remember someone and enter a name or description. You can choose a Context such as a class, or leave it empty. The new person enters Review. This does not invent how they first met.
A Shortcut offers the same capture fields with device authentication. Saved means saved on this device; iCloud delivery still depends on the host app.
The host and widget compile the same persistence/model and typed intent source. Read-only widgets and local writable intents keep mirroring host-owned. Scoped UUID references identify account/environment, store, family and record, rather than trusting serialized labels or managed-object URLs.
Catalog queries resolve bounded requested identities directly; child suggestions batch family-root ambiguity checks. A native form resolves current child/Context and latches after successful save.
CaptureRepository resolves exact namespace/store/family/UUID identities and rejects ambiguous rows. FamilyRepository revalidates child retirement and same-family Context within its save context, creates Person, Connection and optional membership in one write, and uses the existing access save gate. This process gate is not cross-process or CloudKit compare-and-swap.
Deep links contain no names and reject duplicate/unknown query keys, malformed Contexts and cross-scope pairing. Host load generations keep old opening completions from publishing. Stable AppIntents persistent identifiers are explicit across the two compiled modules. Widget providers open fresh local snapshots with no CloudKit options.
Completeness: Phase9 source is present. AppIntents extraction, extension embedding, actual configuration/execution, cold/warm links, authentication, cached timeline privacy and both platform builds require current gates. History retention remains approved interim behavior; Phase8 requires sufficient real data and Phase10 is v2.
Halo Family/Halo Family/Persistence/CaptureReference.swift
Why it matters. A saved picker or URL cannot silently redirect into another account/store/family.
What to look at. CaptureReference.init(identifier:), CaptureRoute.init(url:)
Halo Family/Halo Family/Persistence/FamilyRepository.swift
Why it matters. Failure cannot leave a partial person, and Context membership remains independent from first meeting.
What to look at. quickCapture, validateCaptureChild
Halo Family/SharedIntents/CaptureCatalog.swift
Why it matters. Saved selections fetch requested rows instead of enumerating unrelated children and Contexts.
What to look at. children(identifiers:), contexts(identifiers:), requestedStores
Halo Family/HaloWidgets/ChildCaptureWidget.swift
Why it matters. A selected child/default Context gives a short capture path without exposing larger family records.
What to look at. CaptureWidgetProvider, ChildCaptureWidget
Halo Family/Halo Family/WidgetCaptureSheet.swift
Why it matters. Unavailable default membership is not silently dropped, and one presentation saves once.
What to look at. reload, save
Halo Family/Halo Family.xcodeproj/project.pbxproj
Why it matters. Both native platforms share existing sources/model without adding an unrelated framework.
What to look at. HaloFamilyWidgets, SharedIntents and Extension Persistence synchronized groups
Q9 follows the approved domain distinction: capture adds ConnectionContext and creates no ConnectionOrigin.
The approved architecture keeps CloudKit mirroring in the host. Typed intent success states local persistence separately from sync.
The reversible product choice omits photos/notes and accessory Lock Screen families. Privacy-sensitive rendering and iOS location hints do not prove cached-name removal or locked-device behavior.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | macOS WidgetKit API | disfavoredLocations and StandBy/CarPlay symbols are unavailable on macOS. | Guarded modifier with #if os(iOS), confirmed against installed SDK interface. |
| major | Capture form repeated submit | Queued save activations could create two graphs before sheet dismissal. | Added save latch, disabled button through success, reset only after failure. |
| minor | Saved selection lookup | Child lookup enumerated both libraries/all children, and selected Context enumerated the family. | Bounded targeted child/context resolution; only requested library kinds open. |
| minor | Child suggestions | Duplicate family-root count queries occurred for every child. | Batch ambiguity checks, qualified permission-only row checks and identity reuse. |
Source: local run at 2026-10-07T04:28:18.809519+00:00 · snapshot b17aba8e26438c72590cde4e9622673470ec3312 (dirty working tree)
Baseline: none
Execution: not run · JUnit: none · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
scheduled build/test slot pending
Derived by declaration name, from the diff (no baseline run).
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 b17aba8.
22 files: 15 code · 7 docs. Click to expand.
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
diff --git a/Halo Family/Halo Family.xcodeproj/project.pbxproj b/Halo Family/Halo Family.xcodeproj/project.pbxprojindex c2a59f8..9c236f2 100644--- a/Halo Family/Halo Family.xcodeproj/project.pbxproj +++ b/Halo Family/Halo Family.xcodeproj/project.pbxproj @@ -6,9 +6,21 @@ objectVersion = 90; objects = { +/* Begin PBXBuildFile section */+ A90000000000000000000001 /* HaloFamilyWidgets.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = A90000000000000000000002; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };+/* End PBXBuildFile section */++/* Begin PBXContainerItemProxy section */+ A90000000000000000000003 = {isa = PBXContainerItemProxy; containerPortal = 000000000000000000000000; proxyType = 1; remoteGlobalIDString = A90000000000000000000010; remoteInfo = HaloFamilyWidgets; };+/* End PBXContainerItemProxy section */++/* Begin PBXCopyFilesBuildPhase section */+ A90000000000000000000004 /* Embed App Extensions */ = {isa = PBXCopyFilesBuildPhase; dstPath = ""; dstSubfolderSpec = 13; files = (A90000000000000000000001, ); 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; }; D4E68C5730752C710095AE3C /* Halo-Family-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = "Halo-Family-Info.plist"; sourceTree = "<group>"; };+ A90000000000000000000002 /* HaloFamilyWidgets.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = HaloFamilyWidgets.appex; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFileSystemSynchronizedRootGroup section */@@ -17,6 +29,9 @@ 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 +40,7 @@ files = ( ); };+ A90000000000000000000011 /* Frameworks */ = {isa = PBXFrameworksBuildPhase; files = (); }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */@@ -33,6 +49,9 @@ children = ( D4E68C5730752C710095AE3C /* Halo-Family-Info.plist */, 000000000000000000000010 /* Halo Family */,+ A90000000000000000000005 /* SharedIntents */,+ A90000000000000000000006 /* HaloWidgets */,+ A90000000000000000000007 /* Extension Persistence */, 000000000000000000000020 /* Products */, ); sourceTree = "<group>";@@ -41,6 +60,7 @@ isa = PBXGroup; children = ( 000000000000000000000120 /* Halo Family.app */,+ A90000000000000000000002 /* HaloFamilyWidgets.appex */, ); name = Products; sourceTree = "<group>";@@ -55,17 +75,32 @@ 000000000000000120000000 /* Sources */, 000000000000000130000000 /* Frameworks */, 000000000000000140000000 /* Resources */,+ A90000000000000000000004 /* Embed App Extensions */, ); buildRules = ( );+ dependencies = (A90000000000000000000008, ); 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;+ buildPhases = (A90000000000000000000012, A90000000000000000000011, A90000000000000000000013, );+ buildRules = ();+ dependencies = ();+ fileSystemSynchronizedGroups = (A90000000000000000000005, A90000000000000000000006, A90000000000000000000007, );+ name = HaloFamilyWidgets;+ productName = HaloFamilyWidgets;+ productReference = A90000000000000000000002;+ productType = "com.apple.product-type.app-extension";+ }; /* End PBXNativeTarget section */ /* Begin PBXProject section */@@ -96,6 +131,7 @@ projectRoot = ""; targets = ( 000000000000000100000000 /* Halo Family */,+ A90000000000000000000010 /* HaloFamilyWidgets */, ); }; /* End PBXProject section */@@ -106,6 +142,7 @@ files = ( ); };+ A90000000000000000000013 /* Resources */ = {isa = PBXResourcesBuildPhase; files = (); }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */@@ -114,8 +151,12 @@ files = ( ); };+ A90000000000000000000012 /* Sources */ = {isa = PBXSourcesBuildPhase; files = (); }; /* End PBXSourcesBuildPhase section */ +/* Begin PBXTargetDependency section */+ A90000000000000000000008 = {isa = PBXTargetDependency; target = A90000000000000000000010; targetProxy = A90000000000000000000003; };+/* End PBXTargetDependency section */ /* Begin XCBuildConfiguration section */ 000000000000000011000000 /* Debug configuration for PBXProject "Halo Family" */ = { isa = XCBuildConfiguration;@@ -333,6 +374,70 @@ }; name = Release; };+ A90000000000000000000015 = {+ 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 = {+ 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 +457,7 @@ ); defaultConfigurationName = Release; };+ A90000000000000000000014 = {isa = XCConfigurationList; buildConfigurations = (A90000000000000000000015, A90000000000000000000016, ); defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 000000000000000000000000 /* Project object */;
diff --git a/Halo Family/Halo Family/ContentView.swift b/Halo Family/Halo Family/ContentView.swiftindex 541035f..9ee40a5 100644--- a/Halo Family/Halo Family/ContentView.swift +++ b/Halo Family/Halo Family/ContentView.swift @@ -1,11 +1,14 @@ import CloudKit import Combine 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 @@ -34,7 +37,14 @@ struct ContentView: View { } } .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() } }@@ -60,6 +70,9 @@ struct ContentView: View { .background(.regularMaterial) } }+ .sheet(item: $activeCapture) { route in+ if let repository { WidgetCaptureSheet(repository: repository, route: route) }+ } } private func load() async {@@ -81,6 +94,7 @@ struct ContentView: View { guard loadGeneration == generation else { return } repository = FamilyRepository(stack: stack) failure = nil+ presentCapture() } catch { guard loadGeneration == generation else { return } failure = error.localizedDescription@@ -91,9 +105,25 @@ struct ContentView: View { loadGeneration = UUID() repository = nil failure = nil+ activeCapture = nil Task { await load() } } + 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 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 } }
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 }+}
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")+ }+}
diff --git a/Halo Family/Halo Family/Persistence/FamilyRepository.swift b/Halo Family/Halo Family/Persistence/FamilyRepository.swiftindex 5b04488..a0f9e7a 100644--- a/Halo Family/Halo Family/Persistence/FamilyRepository.swift +++ b/Halo Family/Halo Family/Persistence/FamilyRepository.swift @@ -111,17 +111,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)
diff --git a/Halo Family/Halo Family/Persistence/PersistenceStack.swift b/Halo Family/Halo Family/Persistence/PersistenceStack.swiftindex 521a27e..a0d6b02 100644--- a/Halo Family/Halo Family/Persistence/PersistenceStack.swift +++ b/Halo Family/Halo Family/Persistence/PersistenceStack.swift @@ -301,6 +301,7 @@ final class PersistenceStack { 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 {
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 }+ }+}
diff --git a/Halo Family/Halo-Family-Info.plist b/Halo Family/Halo-Family-Info.plistindex d7690fe..8e7d002 100644--- a/Halo Family/Halo-Family-Info.plist +++ b/Halo Family/Halo-Family-Info.plist @@ -2,6 +2,15 @@ <!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>
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>
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>
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+ }+}
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+ }+}
diff --git a/Halo Family/SharedIntents/CaptureIntents.swift b/Halo Family/SharedIntents/CaptureIntents.swiftnew file mode 100644index 0000000..bb4f9f1--- /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 = "halo-family.capture-child"+ 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 = "halo-family.capture-context"+ 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 = "halo-family.capture-child-query"+ @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 = "halo-family.capture-context-query"+ @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)+ }+}++nonisolated struct RememberPersonIntent: AppIntent {+ static let persistentIdentifier = "halo-family.remember-person"+ static let title: LocalizedStringResource = "Remember someone"+ static let description = IntentDescription("Save a name or description for a child, with an optional context membership.")+ static let authenticationPolicy: IntentAuthenticationPolicy = .requiresLocalDeviceAuthentication+ static let openAppWhenRun = false+ 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?++ 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.")+ }+}++nonisolated struct ChildCaptureConfiguration: WidgetConfigurationIntent {+ static let persistentIdentifier = "halo-family.child-capture-widget"+ static let title: LocalizedStringResource = "Child capture"+ 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")+ }+}
diff --git a/Tests/HaloPersistenceTests/CaptureTests.swift b/Tests/HaloPersistenceTests/CaptureTests.swiftnew file mode 100644index 0000000..c0dbc19--- /dev/null+++ b/Tests/HaloPersistenceTests/CaptureTests.swift@@ -0,0 +1,218 @@+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)+ 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)+ 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)+ #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)+ }+ }+}
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex af99a50..436e4fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,14 @@ ### Added +- 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,
diff --git a/README.md b/README.mdindex d68ee51..fed323d 100644--- a/README.md+++ b/README.md@@ -139,9 +139,9 @@ The integrated Contacts source adds optional Apple Contacts selection/create and 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, picker/create behavior and the six new synthetic cases are unverified;-this source checkpoint declares 85 tests/11 suites, with the verified V6 fixture-correction at 3286293 already integrated.+permission, picker/create behavior and the six new synthetic cases are unverified.+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 @@ -189,5 +189,26 @@ in a Context's detail. New families receive School, Playgroup, Parent group, Chi and Activities. Older families can add missing starters explicitly. Archived labels remain attached to existing Contexts. People search covers names, entered titles, roles, households, related names and nested Context paths. Person details also show-multiple dated Context roles. The current 106-case source batch awaits its runtime-gate; the last verified checkpoint remains 79 cases and both Debug builds.+multiple dated Context roles. These features await their runtime gate.++## 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.++Current source declares **132 synthetic tests/16 suites**, with strict lint **0/86+files** and valid project/plists. New compilation, both Debug builds and native+extension/UI runtime await the shared Mac slot. The last executed passing gate is+still **3286293: 79 tests/10 suites and both Debug builds**. Account/share lifecycle,+cache retention, legacy cache recovery, real CloudKit delivery, production schema and+large-data/runtime evidence remain release gates. Persistent history is retained.
diff --git a/docs/halo_family_design_pack/04-build-plan.md b/docs/halo_family_design_pack/04-build-plan.mdindex 771938c..91558db 100644--- a/docs/halo_family_design_pack/04-build-plan.md+++ b/docs/halo_family_design_pack/04-build-plan.md@@ -2,6 +2,20 @@ **Status:** Full application implementation in progress; release gates remain separate +### 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
diff --git a/docs/halo_family_design_pack/10-initial-implementation-results.md b/docs/halo_family_design_pack/10-initial-implementation-results.mdindex 1e7fa0c..454406a 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,43 @@ # Implementation evidence +## 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
diff --git a/docs/halo_family_design_pack/CHANGELOG.md b/docs/halo_family_design_pack/CHANGELOG.mdindex beb58c3..20cacf7 100644--- a/docs/halo_family_design_pack/CHANGELOG.md+++ b/docs/halo_family_design_pack/CHANGELOG.md@@ -2,6 +2,11 @@ ## 7 October 2026 UTC +- 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.
diff --git a/docs/halo_family_design_pack/README.md b/docs/halo_family_design_pack/README.mdindex d703a6c..3825e21 100644--- a/docs/halo_family_design_pack/README.md+++ b/docs/halo_family_design_pack/README.md@@ -42,6 +42,12 @@ The persistence spike concluded successfully enough to make a production decisio 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). +Per-child WidgetKit and typed AppIntent capture UX are now implemented as source,+with optional Context membership and a compact host form. This checkout declares+132 synthetic cases in 16 suites; new compilation, extension/native runtime and+the combined gate are pending. The last executed passing gate remains 79 cases+and both Debug builds at `3286293`; source lint does not replace those checks.+ ## Document policy Open questions should stay explicit. When a question is resolved, update the relevant design document and remove it from [03-open-questions.md](03-open-questions.md) rather than leaving stale alternatives behind.
diff --git a/docs/halo_family_design_pack/decision_log.md b/docs/halo_family_design_pack/decision_log.mdindex 5cd68a7..99707e0 100644--- a/docs/halo_family_design_pack/decision_log.md+++ b/docs/halo_family_design_pack/decision_log.md@@ -11,6 +11,7 @@ | 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
Run make test with coverage/JUnit, then make check sequentially after the shared slot grant. No current executed cases or build success are claimed.
Verify configuration, authentication, cold/warm URLs, metadata extraction, embedding and OS timeline/redaction behavior using authorized synthetic stores/accounts. Cached widgets may persist until the system refreshes.
Actual two-account share lifecycle/cache retention, legacy recovery provenance, quota/large-data and production schema remain separate. No live-data reads, deletion, account/signing changes, physical installs, push or merge performed.