halo-family

T-2448: inline missing-context creation

Reviewed friend/context capture with explicit parent placement and bounded cancellation ownership.

At a glance

  • Literal Jason at swimming and Met Rachel at school work without model availability. No ChildProfile or schema is added.

  • Inline Name/Inside review offers existing context, Top level or parent; one save creates context, friend/Connection and membership.

  • Full physical/canonical ancestry, family/store/child/permission, eligibility and duplicate checks run before mutation. Receipt owns only new records and rejects later use or ABA history.

Verdict

Ready for feature push and draft PR

Four independent reviews are clear. Final synthetic domain 302/302, strict lint 0/157 and sequential iOS Simulator/macOS builds pass. Seven affected native journeys have passing assertions across a qualified mixed invocation and normal 1/1 corrected retry. Original failures and reporting stalls are retained; broader native/cloud/phone acceptance remains separate.

Review findings

4 raised · 4 fixed · 0 skipped

Jump to findings →

Tests

Pass rate: 100% (302 of 302)

New tests: 14

Diff coverage: 99% (411 of 414 added lines)

Jump to tests →

Commits

Three-level explanation

A short memory separates the friend from the group. Missing groups are reviewed inline before saving. Cancel review keeps the draft; the saved result can cancel only its unchanged new records while visible.

Deterministic literal parsing precedes optional grounded model extraction. Immutable context choices enter the existing one-save repository transaction. A frozen existing child defines the Connection; namesakes require deliberate reuse and existing Connections route to their editors.

CaptureTarget validates expected family/store and exact child inside the transaction. Context choices capture ancestor rows and UUIDs; duplicate canonical identities and newly appearing siblings reject. Link snapshots plus bounded history reject edits, adoption and use/revert before deletion. Local checks do not establish offline distributed uniqueness or unimported remote changes.

Important changes — detailed

Literal friend/group parsing

Halo Family/Halo Family/Persistence/CaptureProposal.swift

Why it matters. Prevents missing-context phrases and unsafe short prose becoming a whole Person name.

What to look at. literalMemory, literalName, nameOnly and grounded

Takeaway. Use a bounded deterministic grammar for common inputs, then retain unsupported drafts.
Rationale. The requested short onboarding prompts must work without model availability.

Immutable context placement and atomic creation

Halo Family/Halo Family/Persistence/CaptureContextSelection.swift

Why it matters. Revalidates exactly the reviewed parent and its full ancestor identities before one graph save.

What to look at. captureContextChoices, validateCaptureSelection, insertCaptureContext

Takeaway. Display strings do not establish record/ancestor identity.
Rationale. Same-name parents and stale context placements must remain explicit and safe.

Joint cancellation ownership

Halo Family/Halo Family/Persistence/CaptureReceipt.swift

Why it matters. New Context ownership remains scoped to the temporary result; subsequent use and ABA changes refuse deletion.

What to look at. confirmedCapture, captureReceipt, discardCapture, requireUnchangedCaptureAudit

Takeaway. Current equality alone cannot detect use-and-revert; pair snapshots with mutation history.
Rationale. Cancel may remove only the unchanged just-created graph, preserving reused/adopted records.

Reusable inline capture review

Halo Family/Halo Family/CaptureContextReview.swift

Why it matters. Name, Inside, Top level and existing-context selection stay in the same flow and can be embedded by onboarding.

What to look at. CaptureContextReview callbacks and CaptureReceipt result metadata

Takeaway. Separate transient cancellation ownership from durable onboarding checkpoints.
Rationale. T-2448 owns capture/Edit/Cancel; T-2445 owns resume/history reconciliation.

Key decisions

Current transaction and receipt

Extend the existing one-save path and conservative whole-Cancel rejection; no new cleanup policy or schema.

Membership versus first meeting

Met Rachel at school records the stated group membership without inventing an explicit first-meeting origin.

Onboarding seam

Successful receipt supplies committed local IDs, creation flags, saved outcome and visibility. The onboarding task owns durable witness/checkpoint/resume handling.

Review findings

SeverityAreaFindingResolution
majorUnsafe prose fallbackShort negated or subject/verb prose could be saved as a Person name.Shared unsafe tokens, conservative multiword name grammar and regressions retain unsafe drafts; model context grounding rejects negation.
majorConcurrent ConnectionA chosen existing Person gaining a Connection during context review did not expose the editor.Atomic duplicate rejection now refreshes Person/Connection choices and routes to the existing editor.
moderateNative Create targetThe outside frame exposed a 34.33-point AX button height.Minimum size now belongs to the label; normal and largest-text native cases pass.
moderateNested UI driverThe driver tapped the parent record instead of its disclosure before checking Class Blue.The corrected disclosure coordinate retains classroom and removed-context assertions; affected retry 1/1 passes normally.

Tests

Source: local run at 2026-10-13T14:26:20.907793+00:00 · snapshot ce3b33a460d669d049befde1111b6e1554c4ba52

Baseline: none

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

Coverage scope: every test in the repository

Totals: 302 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
CHANGELOG.md7—no coverage data
Halo Family/Halo Family/AskHaloView.swift38—no coverage data
Halo Family/Halo Family/CaptureContextReview.swift71—no coverage data
Halo Family/Halo Family/CaptureProposalParser.swift1—no coverage data
Halo Family/Halo Family/Persistence/CaptureContextSelection.swift1127799%
Halo Family/Halo Family/Persistence/CaptureProposal.swift4230100%
Halo Family/Halo Family/Persistence/CaptureReceipt.swift6350100%
Halo Family/Halo Family/Persistence/HaloQuestions.swift100%
Halo Family/Halo Family/Persistence/ProposedCaptureResolution.swift191794%
README.md7—no coverage data
Tests/HaloPersistenceTests/ContextCaptureCreationTests.swift231210100%
Tests/HaloPersistenceTests/LiteralContextCaptureTests.swift3527100%
Tests/HaloUITests/CaptureFeedbackUITests.swift116—no coverage data
docs/halo_family_design_pack/10-initial-implementation-results.md74—no coverage data
docs/halo_family_design_pack/README.md1—no coverage data
specs/ask-context-creation/decision_log.md29—no coverage data
specs/ask-context-creation/design.md42—no coverage data
specs/ask-context-creation/implementation.md17—no coverage data
specs/ask-context-creation/requirements.md35—no coverage data
specs/ask-context-creation/review.md13—no coverage data
specs/ask-context-creation/tasks.md41—no coverage data

Aggregate diff coverage: 99% (411 of 414 measurable added lines).

Overall coverage

Head 94.0% (11968 of 12726 lines)

7 of 21 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 fa25918.

addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

21 files: 11 code · 10 docs. Click to expand.

Code (11)

Halo Family/Halo Family/AskHaloView.swift Modified
diff --git a/Halo Family/Halo Family/AskHaloView.swift b/Halo Family/Halo Family/AskHaloView.swiftindex 4b7253c..bab7658 100644--- a/Halo Family/Halo Family/AskHaloView.swift	+++ b/Halo Family/Halo Family/AskHaloView.swift	@@ -54,7 +54,8 @@ struct AskHaloView: View {     @State private var photoPerson: PersonCard?     @State private var captureDiscarded = false     @State private var captureIssue: CaptureResolutionError?-    @State private var captureContexts: [ContextRow] = []+    @State private var captureContexts: [CaptureContextSelection] = []+    @State private var contextReviewChildID: NSManagedObjectID?     @State private var capturePersonChoice: CapturePersonChoice?     @State private var captureConnections: [PeerCard] = []     @State private var working = false@@ -411,12 +412,14 @@ struct AskHaloView: View {             case .capture(let name):                 if let captureIssue {                     Text(captureIssue.localizedDescription).foregroundStyle(.secondary)-                    ForEach(captureContexts) { context in-                        Button(context.path) {-                            saveCapture(proposal ?? ProposedCapture.nameOnly(in: name), contextID: context.id)-                        }-                            .frame(minHeight: 45)-                            .accessibilityIdentifier("ask.captureContext." + context.id.uriRepresentation().absoluteString)+                    if case .contextChoice(let contextName) = captureIssue, let value = proposal {+                        CaptureContextReview(friendName: value.personName, contextName: contextName,+                                             childLabel: children.first { $0.id == contextReviewChildID }?.person.name ?? "this child",+                                             choices: captureContexts,+                                             onExisting: { saveCapture(value, contextChoice: .existing($0)) },+                                             onCreate: { saveCapture(value, contextChoice: .create($0)) },+                                             onCancel: cancelContextReview)+                            .id(submitted + (contextReviewChildID?.uriRepresentation().absoluteString ?? ""))                     }                 }             case .missing(let message): Text(message).foregroundStyle(.secondary)@@ -424,6 +427,11 @@ struct AskHaloView: View {         } else { Text("Try “Who is Sam again?” or “Was Avery at Sam’s last party?”").foregroundStyle(.secondary) }     } +    private func cancelContextReview() {+        let draft = submitted+        endResults(); result = nil; proposal = nil; submitted = ""; text = draft; focused = true+    }+     private func rememberDifferentPerson() {         cancelParsing(); focused = false         capturePersonChoice = .newPerson@@ -441,15 +449,17 @@ struct AskHaloView: View {         inlineScroll.reveal(identifier + ".results")     } -    private func saveCapture(_ value: ProposedCapture?, contextID: NSManagedObjectID? = nil) {+    private func saveCapture(_ value: ProposedCapture?, contextChoice: CaptureContextChoice? = nil) {+        guard receipt == nil, captured == nil, workspaceIsVisible, pageIsVisible, scenePhase == .active else { return }         guard let value else {             captureIssue = .unparsed             return         }         do {             let saved = try repository.saveProposedCapture(value, source: submitted, familyID: familyID,-                                                          scopedChildID: childID, explicitContextID: contextID,-                                                          personChoice: capturePersonChoice, explicitChildID: explicitCaptureChildID)+                                                          scopedChildID: childID, personChoice: capturePersonChoice,+                                                          explicitChildID: contextReviewChildID ?? explicitCaptureChildID,+                                                          contextChoice: contextChoice)             receipt = saved             let connection = try repository.readable(saved.connectionID, entity: "Connection")             guard let child = connection.value(forKey: "child") as? NSManagedObject else { throw GraphError.invalidReference }@@ -462,10 +472,21 @@ struct AskHaloView: View {             result = nil; answer = nil; captureIssue = nil; captureContexts = []             inlineScroll.reveal(identifier + ".results")         } catch CaptureResolutionError.contextChoice(let name) {+            proposal = value             captureIssue = .contextChoice(name)-            captureContexts = (try? repository.contexts(in: familyID).filter { !$0.isArchived && !$0.hasEnded }) ?? []+            do {+                if contextReviewChildID == nil {+                    contextReviewChildID = try repository.resolvedCaptureChild(proposedName: value.childName, familyID: familyID,+                        scopedChildID: childID, source: submitted, personName: value.personName, explicitChildID: explicitCaptureChildID)+                }+                captureContexts = try repository.captureContextChoices(in: familyID)+            } catch { failure = error.localizedDescription }         } catch CaptureResolutionError.childChoice {             captureIssue = .childChoice+        } catch GraphError.duplicateConnection {+            proposal = value+            captureIssue = .personChoice+            do { try showCapturePersonChoices(value) } catch { failure = error.localizedDescription }         } catch CaptureResolutionError.personChoice {             proposal = value             captureIssue = .personChoice@@ -475,6 +496,7 @@ struct AskHaloView: View {                 receipt?.endVisibility(); receipt = nil; text = ""                 result = .missing("Saved. Its record is temporarily unavailable; check this child's people before trying again.")             }+            if contextChoice != nil { captureContexts = (try? repository.captureContextChoices(in: familyID)) ?? [] }             failure = error.localizedDescription         }     }@@ -483,6 +505,7 @@ struct AskHaloView: View {         guard canSubmit else { return }         endResults(); selectedQuestion = nil; answer = nil; proposal = nil; submitted = text; focused = false         do {+            children = try repository.childCards(in: familyID)             let resolved: HaloQueryResult             if let personID, ["who is this again?", "who is this person?", "who is this?"].contains(HaloPhrase.normalized(text)) {                 resolved = .questions([HaloQuestionOption(id: personID.uriRepresentation().absoluteString,@@ -526,7 +549,7 @@ struct AskHaloView: View {         cancelParsing()         receipt?.endVisibility(); receipt = nil; captured = nil; captureDiscarded = false         visibleCaptureID.wrappedValue = nil-        captureIssue = nil; captureContexts = []+        captureIssue = nil; captureContexts = []; contextReviewChildID = nil         capturePersonChoice = nil; captureConnections = []     }     private func cancelParsing() {@@ -541,7 +564,7 @@ struct AskHaloView: View {         captureConnections = try repository.existingCaptureConnections(proposedName: value.childName,                                                                        familyID: familyID, scopedChildID: childID,                                                                        source: submitted, personName: value.personName,-                                                                       explicitChildID: explicitCaptureChildID)+                                                                       explicitChildID: contextReviewChildID ?? explicitCaptureChildID)         result = .people(people, descriptions: descriptions)     }     private func discard() {@@ -549,7 +572,7 @@ struct AskHaloView: View {         do {             try repository.discardCapture(receipt); endResults(); result = nil; captureDiscarded = true             inlineScroll.reveal(identifier + ".results")-        } catch { self.receipt = nil; failure = error.localizedDescription }+        } catch { receipt.endVisibility(); self.receipt = nil; failure = error.localizedDescription }     }     private func revalidate() {         do {@@ -560,7 +583,7 @@ struct AskHaloView: View {                 if let proposal, case .people? = result {                     try showCapturePersonChoices(proposal)                 } else if case .contextChoice? = captureIssue {-                    captureContexts = try repository.contexts(in: familyID).filter { !$0.isArchived && !$0.hasEnded }+                    captureContexts = try repository.captureContextChoices(in: familyID)                 } else if captureIssue == nil {                     result = try repository.resolveQuestion(submitted, in: familyID)                     captureConnections = try repository.existingCaptureConnections(proposedName: nil, familyID: familyID,
Halo Family/Halo Family/CaptureContextReview.swift Added
diff --git a/Halo Family/Halo Family/CaptureContextReview.swift b/Halo Family/Halo Family/CaptureContextReview.swiftnew file mode 100644index 0000000..480e4aa--- /dev/null+++ b/Halo Family/Halo Family/CaptureContextReview.swift	@@ -0,0 +1,71 @@+import CoreData+import SwiftUI++/// Shared by Ask and guided capture: reviewed placement is immutable until deliberately reselected.+struct CaptureContextReview: View {+    let friendName: String+    let contextName: String+    let childLabel: String+    let choices: [CaptureContextSelection]+    let onExisting: (CaptureContextSelection) -> Void+    let onCreate: (CaptureContextCreation) -> Void+    let onCancel: () -> Void+    @State private var name = ""+    @State private var parent: CaptureContextSelection?+    @State private var parentChanged = false+    @State private var existingID: NSManagedObjectID?++    private var parentBinding: Binding<NSManagedObjectID?> {+        Binding(get: { parent?.id }, set: { id in+            parent = choices.first { $0.id == id }+            parentChanged = false+        })+    }++    var body: some View {+        HaloCard {+            Text("Choose a group for \(friendName)").font(.headline)+            Text("For \(childLabel)").font(.subheadline).foregroundStyle(.secondary)+            if !choices.isEmpty {+                MemoryMenuPicker(title: "Recorded group", selection: $existingID,+                                 selectionLabel: choices.first { $0.id == existingID }?.label ?? "Choose an existing group") {+                    Text("Choose an existing group").tag(nil as NSManagedObjectID?)+                    ForEach(choices) { Text($0.label).tag(Optional($0.id)) }+                }.accessibilityIdentifier("ask.existingContext")+            }+            Text("Or create a group").font(.headline)+            TextField("Group name", text: $name).padding(.vertical, 12).frame(minHeight: 45)+                .accessibilityIdentifier("ask.newContext.name")+            MemoryMenuPicker(title: "Inside", selection: parentBinding,+                             selectionLabel: parent?.label ?? "Top level") {+                Text("Top level").tag(nil as NSManagedObjectID?)+                ForEach(choices) { Text($0.label).tag(Optional($0.id)) }+            }.accessibilityIdentifier("ask.newContext.parent")+            if parentChanged {+                Text("That parent group changed. Choose its current placement before saving.")+                    .font(.caption).foregroundStyle(.secondary)+            }+            Text("Nothing is saved until you choose a recorded group or create this group.")+                .font(.caption).foregroundStyle(.secondary)+            HStack {+                Button(action: onCancel) {+                    Text("Cancel review").frame(minWidth: 45, minHeight: 45).contentShape(Rectangle())+                }.accessibilityIdentifier("ask.newContext.cancel")+                Spacer()+                Button { onCreate(CaptureContextCreation(name: name, parent: parent)) } label: {+                    Text("Create and remember").frame(minWidth: 45, minHeight: 45).contentShape(Rectangle())+                }.buttonStyle(.borderedProminent)+                    .disabled(parentChanged || name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+                    .accessibilityIdentifier("ask.newContext.save")+            }+        }+        .onAppear { name = contextName }+        .onChange(of: existingID) {+            if let selection = choices.first(where: { $0.id == existingID }) { onExisting(selection) }+        }+        .onChange(of: choices) {+            if let parent, !choices.contains(parent) { parentChanged = true }+            existingID = nil+        }+    }+}
Halo Family/Halo Family/CaptureProposalParser.swift Modified
diff --git a/Halo Family/Halo Family/CaptureProposalParser.swift b/Halo Family/Halo Family/CaptureProposalParser.swiftindex b045420..d25fe62 100644--- a/Halo Family/Halo Family/CaptureProposalParser.swift	+++ b/Halo Family/Halo Family/CaptureProposalParser.swift	@@ -17,6 +17,7 @@ nonisolated private struct CaptureProposal {  actor CaptureProposalParser {     func parse(_ text: String) async -> ProposedCapture? {+        if let literal = ProposedCapture.literalMemory(in: text) { return literal }         guard text.count <= 500, text.split(whereSeparator: \.isWhitespace).count >= 4,               SystemLanguageModel.default.isAvailable else { return nil }         do {
Halo Family/Halo Family/Persistence/CaptureContextSelection.swift Added
diff --git a/Halo Family/Halo Family/Persistence/CaptureContextSelection.swift b/Halo Family/Halo Family/Persistence/CaptureContextSelection.swiftnew file mode 100644index 0000000..33e1dfc--- /dev/null+++ b/Halo Family/Halo Family/Persistence/CaptureContextSelection.swift	@@ -0,0 +1,112 @@+import CoreData+import Foundation++struct CaptureContextSelection: Identifiable, Equatable {+    let row: ContextRow+    let ancestry: [ContextRow]+    let stableIDs: [UUID]+    var id: NSManagedObjectID { row.id }+    var label: String { row.path + " · Record " + (stableIDs.first.map { String($0.uuidString.prefix(8)) } ?? "Unavailable") }+}++struct CaptureContextCreation {+    var name: String+    var parent: CaptureContextSelection?++    init(name: String, parent: CaptureContextSelection? = nil) {+        self.name = name+        self.parent = parent+    }+}++enum CaptureContextChoice {+    case existing(CaptureContextSelection)+    case create(CaptureContextCreation)+}++struct CaptureTarget {+    let familyID: NSManagedObjectID+    var context: CaptureContextChoice?+}++@MainActor+extension FamilyRepository {+    /// Freeze the displayed placement, including identities of same-label ancestors.+    func captureContextChoices(in familyID: NSManagedObjectID) throws -> [CaptureContextSelection] {+        let rows = try contexts(in: familyID)+        let byID = Dictionary(uniqueKeysWithValues: rows.map { ($0.id, $0) })+        let identities = try Dictionary(uniqueKeysWithValues: readable(rows.map(\.id), entity: "Context").map {+            ($0.objectID, try stable($0))+        })+        guard Set(identities.values).count == identities.count else { throw GraphError.invalidReference }+        return try rows.filter { !$0.isArchived && !$0.hasEnded }.map { row in+            var ancestry: [ContextRow] = []+            var current: ContextRow? = row+            var seen = Set<NSManagedObjectID>()+            while let node = current {+                guard seen.insert(node.id).inserted else { throw GraphError.contextCycle }+                ancestry.append(node)+                if let parentID = node.parentID {+                    guard let parent = byID[parentID] else { throw GraphError.invalidReference }+                    current = parent+                } else { current = nil }+            }+            let stableIDs = try ancestry.map { node in+                guard let id = identities[node.id] else { throw GraphError.invalidReference }+                return id+            }+            return CaptureContextSelection(row: row, ancestry: ancestry, stableIDs: stableIDs)+        }+    }++    func validateCaptureSelection(_ selection: CaptureContextSelection, family: NSManagedObject,+                                  in context: NSManagedObjectContext) throws -> NSManagedObject {+        let source = try record(selection.id, entity: "Context", in: context)+        try validateCaptureContext(source, family: family)+        var current: NSManagedObject? = source+        var rows: [ContextRow] = []+        var stableIDs: [UUID] = []+        var seen = Set<NSManagedObjectID>()+        while let node = current {+            guard seen.insert(node.objectID).inserted else { throw GraphError.contextCycle }+            _ = try record(node.objectID, entity: "Context", in: context)+            try requireSameFamily(node, family: family)+            let stableID = try stable(node)+            let request = NSFetchRequest<NSManagedObject>(entityName: "Context")+            request.predicate = NSPredicate(format: "id == %@ AND familySpace == %@", stableID as NSUUID, family)+            request.affectedStores = [try owningStore(of: family)]+            guard try context.count(for: request) == 1 else { throw GraphError.invalidReference }+            stableIDs.append(stableID)+            rows.append(ContextRow(id: node.objectID, name: node.value(forKey: "name") as? String ?? "Unnamed",+                                   path: contextPath(node), isArchived: node.value(forKey: "archivedAt") != nil,+                                   parentID: (node.value(forKey: "parent") as? NSManagedObject)?.objectID,+                                   categoryID: (node.value(forKey: "category") as? NSManagedObject)?.objectID,+                                   endDate: node.value(forKey: "endDate") as? Date))+            current = node.value(forKey: "parent") as? NSManagedObject+        }+        guard rows.first == selection.row, rows == selection.ancestry, stableIDs == selection.stableIDs else { throw MemoryError.changed }+        return source+    }++    /// The caller owns the final save; no context can survive a failed capture.+    func insertCaptureContext(_ creation: CaptureContextCreation, family: NSManagedObject,+                              in context: NSManagedObjectContext) throws -> NSManagedObject {+        let name = try validated(creation.name)+        let parent = try creation.parent.map { try validateCaptureSelection($0, family: family, in: context) }+        let request = NSFetchRequest<NSManagedObject>(entityName: "Context")+        request.predicate = NSPredicate(format: "familySpace == %@", family)+        request.affectedStores = [try owningStore(of: family)]+        let siblings = try context.fetch(request).filter { source in+            (source.value(forKey: "parent") as? NSManagedObject)?.objectID == parent?.objectID &&+                source.value(forKey: "archivedAt") == nil &&+                !ContextEndDate.hasEnded(source.value(forKey: "endDate") as? Date) &&+                HaloPhrase.normalized(source.value(forKey: "name") as? String ?? "") == HaloPhrase.normalized(name)+        }+        guard siblings.isEmpty else { throw CaptureResolutionError.contextChoice(name) }+        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+    }+}
Halo Family/Halo Family/Persistence/CaptureProposal.swift Modified
diff --git a/Halo Family/Halo Family/Persistence/CaptureProposal.swift b/Halo Family/Halo Family/Persistence/CaptureProposal.swiftindex 159bae4..71b3e94 100644--- a/Halo Family/Halo Family/Persistence/CaptureProposal.swift	+++ b/Halo Family/Halo Family/Persistence/CaptureProposal.swift	@@ -12,13 +12,44 @@ nonisolated struct ProposedCapture: Equatable, Sendable {     static func nameOnly(in source: String) -> Self? {         let name = source.trimmingCharacters(in: .whitespacesAndNewlines)         let words = HaloPhrase.normalized(name).split(whereSeparator: \.isWhitespace)-        let sentenceWords: Set<String> = ["made", "met", "knows", "says", "was", "is", "first", "friendship"]         guard !name.isEmpty, name.count <= 160, words.count <= 3,-              !words.contains(where: { sentenceWords.contains(String($0)) }),+              !words.contains(where: { unsafeMemoryWords.contains(String($0)) || ["first", "friendship"].contains(String($0)) }),               !name.contains(where: { ",;!?\n".contains($0) }) else { return nil }         return Self(childName: "", personName: name)     } +    /// Small literal memories work independently of model availability and recorded groups.+    static func literalMemory(in source: String) -> Self? {+        guard source.count <= 500, !source.contains(where: { ",;!?\n\r".contains($0) }),+              let parts = HaloPhrase.groups("(?:met\\s+)?(.+?)\\s+at\\s+(.+)", in: source), parts.count == 2,+              literalName(parts[0]), literalSpan(parts[1], limit: 8) else { return nil }+        return Self(childName: "", personName: parts[0], contextName: parts[1]).grounded(in: source)+    }++    private static func literalName(_ text: String) -> Bool {+        guard literalSpan(text, limit: 3) else { return false }+        let particles: Set<String> = ["van", "von", "de", "der", "da", "del", "di", "la", "le", "du", "dos"]+        // Multiword lowercase prose is left to review/model extraction, never treated as a literal full name.+        return text.split(whereSeparator: \.isWhitespace).dropFirst().allSatisfy {+            $0.first?.isUppercase == true || particles.contains(HaloPhrase.normalized(String($0)))+        }+    }++    private static func literalSpan(_ text: String, limit: Int) -> Bool {+        let words = HaloPhrase.normalized(text).split(whereSeparator: \.isWhitespace)+        return !words.isEmpty && words.count <= limit && text.count <= 160 &&+            text.range(of: "^[\\p{L}\\p{N} ’'›-]+$", options: .regularExpression) != nil &&+            !words.contains { unsafeMemoryWords.contains(String($0)) }+    }++    private static let unsafeMemoryWords: Set<String> = [+        "at", "from", "met", "made", "knows", "says", "was", "is", "were", "are", "not", "no", "never",+        "and", "or", "but", "didn't", "doesn't", "isn't", "wasn't", "don't", "cannot", "can't",+        "plays", "play", "attends", "attend", "goes", "go", "went", "lives", "live", "works", "work", "swims", "swim",+        "studies", "study", "has", "had", "have", "meet", "meets", "wants", "want",+        "i", "we", "you", "he", "she", "they", "my", "our", "your", "his", "her", "their", "saw", "see", "seen",+    ]+     var closeness: ClosenessChoice? {         switch HaloPhrase.normalized(closenessText) {         case "met once": .metOnce@@ -33,6 +64,11 @@ nonisolated struct ProposedCapture: Equatable, Sendable {     /// A model supplies candidate substrings; only unique, verbatim source spans survive.     func grounded(in source: String) -> Self? {         guard childName.isEmpty || unique(childName, in: source), unique(personName, in: source) else { return nil }+        if !contextName.isEmpty {+            let normalized = HaloPhrase.normalized(source)+            let separators = normalized.split(whereSeparator: \.isWhitespace).filter { $0 == "at" }+            if negatedSpan(contextName, in: normalized) || source.contains("?") || separators.count > 1 { return nil }+        }         var result = self         if !contextName.isEmpty && !unique(contextName, in: source) { result.contextName = "" }         let token = NSRegularExpression.escapedPattern(for: closenessText)@@ -116,7 +152,10 @@ enum CaptureChildSelection {                 fullNames.contains { $0.id == child.id } ||                     remaining.range(of: namePattern(givenNames[child.id] ?? ""), options: .regularExpression) != nil             }-            if mentioned.count == 1 { return mentioned.first?.id }+            if mentioned.count == 1 {+                if let explicitChildID, mentioned.first?.id != explicitChildID { return nil }+                return mentioned.first?.id+            }             if !mentioned.isEmpty { return mentioned.first { $0.id == explicitChildID }?.id }         }         if let explicitChildID { return explicitChildID }
Halo Family/Halo Family/Persistence/CaptureReceipt.swift Modified
diff --git a/Halo Family/Halo Family/Persistence/CaptureReceipt.swift b/Halo Family/Halo Family/Persistence/CaptureReceipt.swiftindex 9f97174..027d9bb 100644--- a/Halo Family/Halo Family/Persistence/CaptureReceipt.swift	+++ b/Halo Family/Halo Family/Persistence/CaptureReceipt.swift	@@ -1,6 +1,8 @@ import CoreData import Foundation +enum CaptureSaveOutcome { case saved }+ private struct CaptureSnapshot: Equatable {     let metadata: MergeRecord     let links: [String: Set<NSManagedObjectID>]@@ -9,18 +11,33 @@ private struct CaptureSnapshot: Equatable { /// Kept only by the currently displayed query result, never persisted as a deletion capability. @MainActor final class CaptureReceipt {-    fileprivate let familyID: NSManagedObjectID+    let familyID: NSManagedObjectID     fileprivate let snapshots: [NSManagedObjectID: CaptureSnapshot]     fileprivate let historyToken: NSPersistentHistoryToken?     fileprivate var consumed = false     let connectionID: NSManagedObjectID+    let childID: NSManagedObjectID+    let personID: NSManagedObjectID+    let contextID: NSManagedObjectID?+    let createdPerson: Bool+    let createdContext: Bool+    var isVisible: Bool { !consumed }+    // Construction is private and publication happens only after the graph save succeeds.+    var saveOutcome: CaptureSaveOutcome { .saved }      fileprivate init(familyID: NSManagedObjectID, connectionID: NSManagedObjectID,-                     snapshots: [NSManagedObjectID: CaptureSnapshot], historyToken: NSPersistentHistoryToken?) {+                     snapshots: [NSManagedObjectID: CaptureSnapshot], historyToken: NSPersistentHistoryToken?,+                     childID: NSManagedObjectID, personID: NSManagedObjectID, contextID: NSManagedObjectID?,+                     createdPerson: Bool, createdContext: Bool) {         self.familyID = familyID         self.connectionID = connectionID         self.snapshots = snapshots         self.historyToken = historyToken+        self.childID = childID+        self.personID = personID+        self.contextID = contextID+        self.createdPerson = createdPerson+        self.createdContext = createdContext     }     func endVisibility() { consumed = true } }@@ -28,23 +45,46 @@ final class CaptureReceipt { @MainActor extension FamilyRepository {     func confirmedCapture(name: String, childID: NSManagedObjectID, contextID: NSManagedObjectID? = nil,-                          details: CaptureDetails = CaptureDetails(), existingPersonID: NSManagedObjectID? = nil) throws -> CaptureReceipt {+                          details: CaptureDetails = CaptureDetails(), existingPersonID: NSManagedObjectID? = nil,+                          target: CaptureTarget? = nil) throws -> CaptureReceipt {         var receipt: CaptureReceipt?         _ = try write { context in-            let connection = try insertCapture(name: name, childID: childID, contextID: contextID, details: details,+            let child = try record(childID, entity: "ChildProfile", in: context)+            try validateCaptureChild(child)+            let family = try self.family(of: child)+            if let target {+                let expectedFamily = try record(target.familyID, entity: "FamilySpace", in: context)+                try requireSameFamily(child, family: expectedFamily)+            }+            var selectedContextID = contextID+            var createdContext: NSManagedObject?+            if let choice = target?.context {+                guard contextID == nil else { throw GraphError.invalidReference }+                switch choice {+                case .existing(let selection):+                    selectedContextID = try validateCaptureSelection(selection, family: family, in: context).objectID+                case .create(let creation):+                    createdContext = try insertCaptureContext(creation, family: family, in: context)+                    try context.obtainPermanentIDs(for: Array(context.insertedObjects))+                    selectedContextID = createdContext?.objectID+                }+            }+            let connection = try insertCapture(name: name, childID: childID, contextID: selectedContextID, details: details,                                                existingPersonID: existingPersonID, in: context)             try context.obtainPermanentIDs(for: Array(context.insertedObjects))-            receipt = try captureReceipt(for: connection, createdPerson: existingPersonID == nil, in: context)+            receipt = try captureReceipt(for: connection, createdPerson: existingPersonID == nil,+                                         createdContext: createdContext, in: context)             return connection         }         guard let receipt else { throw GraphError.invalidReference }         return receipt     } -    private func captureReceipt(for connection: NSManagedObject, createdPerson: Bool,+    private func captureReceipt(for connection: NSManagedObject, createdPerson: Bool, createdContext: NSManagedObject?,                                 in context: NSManagedObjectContext) throws -> CaptureReceipt {         let family = try family(of: connection)         var owned = [connection]+        if let createdContext { owned.append(createdContext) }         for key in ["memberships", "originProposals", "closenessPeriods", "statusPeriods"] {             owned += Array(connection.value(forKey: key) as? Set<NSManagedObject> ?? [])         }@@ -56,7 +96,13 @@ extension FamilyRepository {         })         let stores = family.objectID.persistentStore.map { [$0] }         let token = context.persistentStoreCoordinator?.currentPersistentHistoryToken(fromStores: stores)-        return CaptureReceipt(familyID: family.objectID, connectionID: connection.objectID, snapshots: snapshots, historyToken: token)+        guard let child = connection.value(forKey: "child") as? NSManagedObject,+              let person = connection.value(forKey: "person") as? NSManagedObject else { throw GraphError.invalidReference }+        let memberships = connection.value(forKey: "memberships") as? Set<NSManagedObject> ?? []+        let contextID = memberships.first.flatMap { ($0.value(forKey: "context") as? NSManagedObject)?.objectID }+        return CaptureReceipt(familyID: family.objectID, connectionID: connection.objectID, snapshots: snapshots, historyToken: token,+                              childID: child.objectID, personID: person.objectID, contextID: contextID,+                              createdPerson: createdPerson, createdContext: createdContext != nil)     }      func discardCapture(_ receipt: CaptureReceipt) throws {@@ -100,10 +146,16 @@ extension FamilyRepository {             throw MemoryError.changed         }         let entities = ["PersonMerge", "MergeConnectionReview", "PersonMergeRecovery"]-        for change in transactions.flatMap({ $0.changes ?? [] }) where entities.contains(change.changedObjectID.entity.name ?? "") {-            guard change.changeType != .delete,-                  let object = try? context.existingObject(with: change.changedObjectID), !object.isDeleted,-                  (object.value(forKey: "familySpace") as? NSManagedObject)?.objectID != family.objectID else { throw MemoryError.changed }+        for change in transactions.flatMap({ $0.changes ?? [] }) {+            // A later edit/use cannot revive Cancel by restoring the same values or removing the new link.+            if receipt.snapshots[change.changedObjectID] != nil && change.changeType != .insert { throw MemoryError.changed }+            if entities.contains(change.changedObjectID.entity.name ?? "") {+                guard change.changeType != .delete,+                      let object = try? context.existingObject(with: change.changedObjectID), !object.isDeleted,+                      (object.value(forKey: "familySpace") as? NSManagedObject)?.objectID != family.objectID else {+                    throw MemoryError.changed+                }+            }         }     } }
Halo Family/Halo Family/Persistence/HaloQuestions.swift Modified
diff --git a/Halo Family/Halo Family/Persistence/HaloQuestions.swift b/Halo Family/Halo Family/Persistence/HaloQuestions.swiftindex 1ba7c30..a01e250 100644--- a/Halo Family/Halo Family/Persistence/HaloQuestions.swift	+++ b/Halo Family/Halo Family/Persistence/HaloQuestions.swift	@@ -62,6 +62,7 @@ extension FamilyRepository {             }             return options.isEmpty ? .missing("No matching past party or Event is recorded.") : .questions(options)         }+        if ProposedCapture.literalMemory(in: text) != nil { return .capture(text) }         let people = try personCards(people(in: familyID, search: text))         return people.isEmpty ? .capture(text) : .people(people, descriptions: try personDistinctions(people.map(\.id), in: familyID))     }
Halo Family/Halo Family/Persistence/ProposedCaptureResolution.swift Modified
diff --git a/Halo Family/Halo Family/Persistence/ProposedCaptureResolution.swift b/Halo Family/Halo Family/Persistence/ProposedCaptureResolution.swiftindex 655640c..621e82e 100644--- a/Halo Family/Halo Family/Persistence/ProposedCaptureResolution.swift	+++ b/Halo Family/Halo Family/Persistence/ProposedCaptureResolution.swift	@@ -11,7 +11,7 @@ nonisolated enum CaptureResolutionError: LocalizedError, Equatable {     var errorDescription: String? {         switch self {         case .childChoice: "Choose the child who knows this person, then press Go. Nothing has been saved yet."-        case .contextChoice(let name): "Choose the recorded group for “\(name)”. Nothing has been saved yet."+        case .contextChoice(let name): "Choose a recorded group or create a group for “\(name)”. Nothing has been saved yet."         case .personChoice: "Choose the recorded person or remember a different namesake. Nothing has been saved yet."         case .ungrounded: "The extracted name could not be verified against your text. Nothing has been saved."         case .unparsed: "Halo couldn't read that memory. Enter just a name or short description and press Go. Nothing has been saved."@@ -29,7 +29,8 @@ extension FamilyRepository {     /// Resolve current, authorized references immediately before the existing atomic capture transaction.     func saveProposedCapture(_ proposal: ProposedCapture, source: String, familyID: NSManagedObjectID,                              scopedChildID: NSManagedObjectID?, explicitContextID: NSManagedObjectID? = nil,-                             personChoice: CapturePersonChoice? = nil, explicitChildID: NSManagedObjectID? = nil) throws -> CaptureReceipt {+                             personChoice: CapturePersonChoice? = nil, explicitChildID: NSManagedObjectID? = nil,+                             contextChoice: CaptureContextChoice? = nil) throws -> CaptureReceipt {         guard let grounded = proposal.grounded(in: source) else { throw CaptureResolutionError.ungrounded }         _ = try readable(familyID, entity: "FamilySpace")         guard let child = try resolvedCaptureChild(proposedName: grounded.childName, familyID: familyID,@@ -48,25 +49,29 @@ extension FamilyRepository {             guard matches.isEmpty else { throw CaptureResolutionError.personChoice }             existingPersonID = nil         }-        let contextID: NSManagedObjectID?+        var selectedContext = contextChoice         if let explicitContextID {-            contextID = explicitContextID-        } else if grounded.contextName.isEmpty {-            contextID = nil-        } else {+            guard contextChoice == nil else { throw GraphError.invalidReference }+            guard let selection = try captureContextChoices(in: familyID).first(where: { $0.id == explicitContextID }) else {+                throw GraphError.invalidReference+            }+            selectedContext = .existing(selection)+        } else if selectedContext == nil && !grounded.contextName.isEmpty {             let name = HaloPhrase.normalized(grounded.contextName)-            let matches = try contexts(in: familyID).filter {-                !$0.isArchived && !$0.hasEnded &&-                    (HaloPhrase.normalized($0.name) == name || HaloPhrase.normalized($0.path) == name)+            let matches = try captureContextChoices(in: familyID).filter {+                HaloPhrase.normalized($0.row.name) == name || HaloPhrase.normalized($0.row.path) == name+            }+            guard matches.count == 1, let selection = matches.first else {+                throw CaptureResolutionError.contextChoice(grounded.contextName)             }-            guard matches.count == 1 else { throw CaptureResolutionError.contextChoice(grounded.contextName) }-            contextID = matches.first?.id+            selectedContext = .existing(selection)         }         let narrative = grounded.originDescription.trimmingCharacters(in: .whitespacesAndNewlines)         let details = CaptureDetails(origin: narrative.isEmpty ? nil : OriginInput(narrative: narrative),                                      closeness: grounded.closeness)-        return try confirmedCapture(name: grounded.personName, childID: child, contextID: contextID,-                                    details: details, existingPersonID: existingPersonID)+        return try confirmedCapture(name: grounded.personName, childID: child,+                                    details: details, existingPersonID: existingPersonID,+                                    target: CaptureTarget(familyID: familyID, context: selectedContext))     }      func resolvedCaptureChild(proposedName: String?, familyID: NSManagedObjectID,
Tests/HaloPersistenceTests/ContextCaptureCreationTests.swift Added
diff --git a/Tests/HaloPersistenceTests/ContextCaptureCreationTests.swift b/Tests/HaloPersistenceTests/ContextCaptureCreationTests.swiftnew file mode 100644index 0000000..0e39d9a--- /dev/null+++ b/Tests/HaloPersistenceTests/ContextCaptureCreationTests.swift@@ -0,0 +1,231 @@+import CoreData+import Foundation+import Testing+@testable import HaloPersistence++@MainActor+struct ContextCaptureCreationTests {+    private func withGraph(_ test: (GraphFixture) throws -> Void) throws {+        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+        defer { try? FileManager.default.removeItem(at: directory) }+        try test(GraphFixture(directory: directory))+    }++    private func capture(_ fixture: GraphFixture, choice: CaptureContextChoice?,+                         person: CapturePersonChoice? = nil) throws -> CaptureReceipt {+        try fixture.graph.saveProposedCapture(ProposedCapture(childName: "", personName: "Jason", contextName: "swimming"),+            source: "Jason at swimming", familyID: fixture.family, scopedChildID: fixture.child,+            personChoice: person, contextChoice: choice)+    }++    @Test func jointCreationAndCancelRetainExistingParentAndOwnChild() throws {+        try withGraph { fixture in+            let graph = fixture.graph+            let parent = try graph.createContext(name: "Activities", familyID: fixture.family)+            let selection = try #require(try graph.captureContextChoices(in: fixture.family).first { $0.id == parent })+            #expect(throws: CaptureResolutionError.self) { try capture(fixture, choice: nil) }+            #expect(try graph.people(in: fixture.family).count == 2)+            let receipt = try capture(fixture, choice: .create(CaptureContextCreation(name: "Swimming", parent: selection)))+            let contexts = try graph.contexts(in: fixture.family)+            let swimming = try #require(contexts.first { $0.name == "Swimming" })+            #expect(receipt.familyID == fixture.family && receipt.childID == fixture.child)+            #expect(receipt.createdContext && receipt.createdPerson && receipt.isVisible)+            #expect(receipt.contextID == swimming.id && receipt.saveOutcome == .saved)+            #expect(swimming.parentID == parent && swimming.path == "Activities › Swimming")+            #expect(try graph.memberships(for: receipt.connectionID).map(\.contextID) == [swimming.id])+            #expect(try graph.person(graph.personID(for: receipt.connectionID)).name == "Jason")+            #expect(try graph.children(in: fixture.family).map(\.id) == [fixture.child])+            try graph.discardCapture(receipt)+            #expect(!receipt.isVisible)+            #expect(try graph.contexts(in: fixture.family).map(\.id) == [parent])+            #expect(try graph.people(in: fixture.family).count == 2)+        }+    }++    @Test func topLevelCreationAndReusedPersonCancelPreserveThePerson() throws {+        try withGraph { fixture in+            let person = try fixture.graph.addPerson(name: "Jason", familyID: fixture.family)+            let receipt = try capture(fixture, choice: .create(CaptureContextCreation(name: "swimming")), person: .existing(person))+            #expect(try fixture.graph.personID(for: receipt.connectionID) == person)+            try fixture.graph.discardCapture(receipt)+            #expect(try fixture.graph.contexts(in: fixture.family).isEmpty)+            #expect(try fixture.graph.person(person).name == "Jason")+        }+    }++    @Test func appearingSiblingRequiresExplicitReuseWithoutPartialRecords() throws {+        try withGraph { fixture in+            let choice = CaptureContextCreation(name: "swimming")+            let existing = try fixture.graph.createContext(name: "SWIMMING", familyID: fixture.family)+            #expect(throws: CaptureResolutionError.self) { try capture(fixture, choice: .create(choice)) }+            #expect(try fixture.graph.people(in: fixture.family).count == 2)+            let selection = try #require(try fixture.graph.captureContextChoices(in: fixture.family).first { $0.id == existing })+            let receipt = try capture(fixture, choice: .existing(selection))+            try fixture.graph.discardCapture(receipt)+            #expect(try fixture.graph.contexts(in: fixture.family).map(\.id) == [existing])+        }+    }++    @Test func changedParentAncestryRejectsEvenWhenItsDisplayPathIsIdentical() throws {+        try withGraph { fixture in+            let graph = fixture.graph+            let first = try graph.createContext(name: "Activities", familyID: fixture.family)+            let second = try graph.createContext(name: "Activities", familyID: fixture.family)+            let middle = try graph.createContext(name: "Sports", familyID: fixture.family, parentID: first)+            let parent = try graph.createContext(name: "Pool", familyID: fixture.family, parentID: middle)+            let selection = try #require(try graph.captureContextChoices(in: fixture.family).first { $0.id == parent })+            try graph.moveContext(middle, parentID: second)+            #expect(try graph.contexts(in: fixture.family).first { $0.id == parent }?.path == selection.row.path)+            #expect(throws: MemoryError.changed) {+                try capture(fixture, choice: .create(CaptureContextCreation(name: "swimming", parent: selection)))+            }+            #expect(try graph.people(in: fixture.family).count == 2)+            #expect(try graph.contexts(in: fixture.family).count == 4)+        }+    }++    @Test func staleEndedArchivedAndForeignParentsRejectWithoutPartialCapture() throws {+        for kind in ["rename", "ended", "archived", "foreign", "cycle"] {+            try withGraph { fixture in+                let graph = fixture.graph+                let family = kind == "foreign" ? try graph.createFamily(name: "Other synthetic") : fixture.family+                let parent = try graph.createContext(name: "Activities", familyID: family)+                let selection = try #require(try graph.captureContextChoices(in: family).first { $0.id == parent })+                switch kind {+                case "ended": try graph.setContextEndDate(parent, endDate: Date(timeIntervalSince1970: 0), expected: nil)+                case "archived": try graph.archiveContext(parent, archived: true)+                case "rename", "cycle":+                    _ = try graph.write { context in+                        let row = try graph.record(parent, entity: "Context", in: context)+                        if kind == "rename" { row.setValue("Changed", forKey: "name") } else { row.setValue(row, forKey: "parent") }+                        return row+                    }+                default: break+                }+                #expect(throws: Error.self) {+                    try capture(fixture, choice: .create(CaptureContextCreation(name: "swimming", parent: selection)))+                }+                #expect(try graph.people(in: fixture.family).count == 2)+                #expect(try graph.connections(for: fixture.child).count == 1)+            }+        }+    }++    @Test func adoptionEditAndExpiredVisibilityRejectWholeCancel() throws {+        for kind in ["membership", "nested", "edit", "expired"] {+            try withGraph { fixture in+                let graph = fixture.graph+                let receipt = try capture(fixture, choice: .create(CaptureContextCreation(name: "swimming")))+                let source = try #require(try graph.contexts(in: fixture.family).first)+                switch kind {+                case "membership": _ = try graph.addMembership(connectionID: fixture.connection, contextID: source.id)+                case "nested": _ = try graph.createContext(name: "Other lesson", familyID: fixture.family, parentID: source.id)+                case "edit":+                    _ = try graph.write { context in+                        let row = try graph.record(source.id, entity: "Context", in: context)+                        row.setValue("Renamed", forKey: "name"); return row+                    }+                default: receipt.endVisibility()+                }+                #expect(throws: MemoryError.changed) { try graph.discardCapture(receipt) }+                #expect(try graph.connections(for: fixture.child).count == 2)+                #expect(try graph.people(in: fixture.family).count == 3)+                #expect(try graph.contexts(in: fixture.family).contains { $0.id == source.id })+            }+        }+    }++    @Test func aContextUsedThenUnlinkedOrRenamedBackDoesNotReviveCancel() throws {+        for kind in ["membership", "rename"] {+            try withGraph { fixture in+                let graph = fixture.graph+                let receipt = try capture(fixture, choice: .create(CaptureContextCreation(name: "swimming")))+                let source = try #require(receipt.contextID)+                if kind == "membership" {+                    let membership = try graph.addMembership(connectionID: fixture.connection, contextID: source)+                    _ = try graph.write { context in+                        let row = try graph.record(membership, entity: "ConnectionContext", in: context)+                        context.delete(row); return try graph.record(source, entity: "Context", in: context)+                    }+                } else {+                    for name in ["Changed", "swimming"] {+                        _ = try graph.write { context in+                            let row = try graph.record(source, entity: "Context", in: context)+                            row.setValue(name, forKey: "name"); return row+                        }+                    }+                }+                #expect(throws: MemoryError.changed) { try graph.discardCapture(receipt) }+                #expect(try graph.connections(for: fixture.child).count == 2)+                #expect(try graph.contexts(in: fixture.family).count == 1)+            }+        }+    }++    @Test func existingContextSnapshotAndFrozenChildAreRevalidated() throws {+        try withGraph { fixture in+            let graph = fixture.graph+            let group = try graph.createContext(name: "swimming", familyID: fixture.family)+            let selection = try #require(try graph.captureContextChoices(in: fixture.family).first)+            let parent = try graph.createContext(name: "Activities", familyID: fixture.family)+            try graph.moveContext(group, parentID: parent)+            #expect(throws: MemoryError.changed) { try capture(fixture, choice: .existing(selection)) }+            let other = try graph.addChild(name: "Other child", familyID: fixture.family)+            #expect(try graph.resolvedCaptureChild(proposedName: "", familyID: fixture.family,+                scopedChildID: fixture.child, source: "Other child knows Jason", personName: "Jason",+                explicitChildID: fixture.child) == nil)+            #expect(try graph.connections(for: other).isEmpty)+            #expect(try graph.people(in: fixture.family).count == 3)+        }+    }++    @Test func concurrentlyConnectedPersonLeavesNoPartialNewContext() throws {+        try withGraph { fixture in+            let graph = fixture.graph+            let person = try graph.addPerson(name: "Jason", familyID: fixture.family)+            let connection = try graph.connect(personID: person, childID: fixture.child)+            #expect(throws: GraphError.duplicateConnection) {+                try capture(fixture, choice: .create(CaptureContextCreation(name: "swimming")), person: .existing(person))+            }+            #expect(try graph.contexts(in: fixture.family).isEmpty)+            let choices = try graph.existingCaptureConnections(proposedName: "", familyID: fixture.family,+                scopedChildID: fixture.child, source: "Jason at swimming", personName: "Jason", explicitChildID: fixture.child)+            #expect(choices.contains { $0.id == connection && $0.person.id == person })+        }+    }++    @Test func duplicateCanonicalContextIdentityInvalidatesReviewedSelection() throws {+        try withGraph { fixture in+            let graph = fixture.graph+            let selected = try graph.createContext(name: "Activities", familyID: fixture.family)+            let choice = try #require(try graph.captureContextChoices(in: fixture.family).first)+            let duplicate = try graph.createContext(name: "Other group", familyID: fixture.family)+            _ = try graph.write { context in+                let row = try graph.record(duplicate, entity: "Context", in: context)+                row.setValue(try graph.stable(graph.record(selected, entity: "Context", in: context)), forKey: "id")+                return row+            }+            #expect(throws: GraphError.self) {+                try capture(fixture, choice: .create(CaptureContextCreation(name: "swimming", parent: choice)))+            }+            #expect(try graph.people(in: fixture.family).count == 2)+            #expect(try graph.contexts(in: fixture.family).count == 2)+        }+    }++    @Test func expectedFamilyAndDeniedAccessCannotCreatePartialContext() throws {+        try withGraph { fixture in+            let graph = fixture.graph+            let other = try graph.createFamily(name: "Other synthetic")+            #expect(throws: GraphError.self) {+                try graph.confirmedCapture(name: "Jason", childID: fixture.child,+                    target: CaptureTarget(familyID: other, context: .create(CaptureContextCreation(name: "swimming"))))+            }+            let identity = try StoreAccess.identity(graph.readable(fixture.family, entity: "FamilySpace"))+            fixture.stack.access.update(readable: [identity], writable: [])+            #expect(throws: AccessError.self) { try capture(fixture, choice: .create(CaptureContextCreation(name: "swimming"))) }+            #expect(try graph.contexts(in: fixture.family).isEmpty)+            #expect(try graph.people(in: fixture.family).count == 2)+        }+    }+}
Tests/HaloPersistenceTests/LiteralContextCaptureTests.swift Added
diff --git a/Tests/HaloPersistenceTests/LiteralContextCaptureTests.swift b/Tests/HaloPersistenceTests/LiteralContextCaptureTests.swiftnew file mode 100644index 0000000..9468f69--- /dev/null+++ b/Tests/HaloPersistenceTests/LiteralContextCaptureTests.swift@@ -0,0 +1,35 @@+import Foundation+import Testing+@testable import HaloPersistence++struct LiteralContextCaptureTests {+    @Test func shortFriendAndContextSpansRemainLiteral() throws {+        for (source, person, group) in [("Jason at swimming", "Jason", "swimming"),+                                        ("Met Rachel at school", "Rachel", "school"),+                                        ("met José O’Neill at School › Year 3", "José O’Neill", "School › Year 3")] {+            let proposal = try #require(ProposedCapture.literalMemory(in: source))+            #expect(proposal.personName == person && proposal.contextName == group)+            #expect(proposal.childName.isEmpty && proposal.originDescription.isEmpty)+            #expect(proposal.grounded(in: source) == proposal)+            #expect(ProposedCapture.nameOnly(in: source) == nil)+        }+    }++    @Test func unsafeOrAmbiguousShortMemoriesCannotBecomeLiteralNames() {+        for source in ["Jason at swimming at school", "Jason is not at swimming", "Jason at swimming?",+                       "Jason at", "at swimming", "Met Rachel", "Who is Jason?", "Jason\nat swimming",+                       "Jason and Rachel at swimming", "Jason at not swimming", "Jason from swimming",+                       "Jason isn't swimming", "Jason or Rachel", "Jason can’t swim", "Jason plays at school", "Jason attends school",+                       "I saw Jason at swimming",+                       "Jason swims at school", "Jason dances at school"] {+            #expect(ProposedCapture.literalMemory(in: source) == nil)+            #expect(ProposedCapture.nameOnly(in: source) == nil)+        }+    }++    @Test func modelProposalCannotBypassNegatedContextAssertion() {+        for source in ["Jason is not at swimming", "Jason never met at swimming", "Jason at swimming?", "Jason at not swimming"] {+            #expect(ProposedCapture(childName: "", personName: "Jason", contextName: "swimming").grounded(in: source) == nil)+        }+    }+}
Tests/HaloUITests/CaptureFeedbackUITests.swift Modified
diff --git a/Tests/HaloUITests/CaptureFeedbackUITests.swift b/Tests/HaloUITests/CaptureFeedbackUITests.swiftindex 3bf3d9b..10f2f8c 100644--- a/Tests/HaloUITests/CaptureFeedbackUITests.swift+++ b/Tests/HaloUITests/CaptureFeedbackUITests.swift@@ -388,3 +388,119 @@ extension WorkspaceUITests {         app.terminate()     } }++extension WorkspaceUITests {+    @MainActor func testMissingContextReviewCreatesNestedGroupAndCancelRemovesOnlyNewResult() {+        let app = launch(initialInput: "Jason at tennis")+        tap(childScope("Avery", in: app)); tap(app.buttons["ask.submit"])+        let name = app.textFields["ask.newContext.name"]+        XCTAssertTrue(name.waitForExistence(timeout: 10))+        XCTAssertEqual(name.value as? String, "tennis")+        XCTAssertTrue(app.staticTexts["For Avery"].exists)+        XCTAssertFalse(app.buttons["ask.cancelCapture"].exists)+        let parent = app.buttons["ask.newContext.parent"]+        scrollTo(parent, in: app); tap(parent)+        tap(app.buttons.matching(NSPredicate(format: "label BEGINSWITH %@", "Oak School · Record")).firstMatch)+        let create = app.buttons["ask.newContext.save"]+        scrollTo(create, in: app); assertTouchTarget(create); screenshot(app, name: "Missing context inline review and parent choice")+        tap(create)+        let saved = app.staticTexts["capture.name"]+        XCTAssertTrue(saved.waitForExistence(timeout: 10)); XCTAssertEqual(saved.label, "Jason")+        let cancel = app.buttons["ask.cancelCapture"]+        scrollTo(cancel, in: app); tap(cancel)+        XCTAssertTrue(app.staticTexts["Capture discarded."].waitForExistence(timeout: 10))+        tap(app.buttons["Home options"]); tap(app.buttons["All groups"])+        XCTAssertTrue(app.staticTexts["Oak School"].exists || app.buttons["context.open.Oak School"].exists)+        let classroom = app.buttons["context.open.Class Blue"]+        if !classroom.exists {+            let row = app.cells.containing(.button, identifier: "context.open.Oak School").firstMatch+            XCTAssertTrue(row.exists)+            screenshot(app, name: "Recorded context tree before disclosure expansion")+            row.coordinate(withNormalizedOffset: CGVector(dx: 0.95, dy: 0.5)).tap()+        }+        XCTAssertTrue(classroom.waitForExistence(timeout: 5))+        XCTAssertFalse(app.buttons["context.open.tennis"].exists)+        screenshot(app, name: "Cancel retains recorded contexts and removes jointly created group")+        app.terminate()+    }++    @MainActor func testMetFriendCreatesTopLevelContextAndEditEndsCancelLifetime() {+        let app = launch(initialInput: "Met Rachel at choir")+        tap(childScope("Avery", in: app)); tap(app.buttons["ask.submit"])+        let create = app.buttons["ask.newContext.save"]+        XCTAssertTrue(create.waitForExistence(timeout: 10)); scrollTo(create, in: app); tap(create)+        XCTAssertTrue(app.staticTexts["capture.name"].waitForExistence(timeout: 10))+        XCTAssertEqual(app.staticTexts["capture.name"].label, "Rachel")+        let edit = app.buttons["ask.editCapture"]+        scrollTo(edit, in: app); tap(edit)+        XCTAssertTrue(app.navigationBars.firstMatch.waitForExistence(timeout: 10))+        screenshot(app, name: "New friend relationship editor retains ordinary context")+        app.navigationBars.buttons.firstMatch.tap()+        XCTAssertFalse(app.buttons["ask.cancelCapture"].exists)+        tap(app.buttons["Home options"]); tap(app.buttons["All groups"])+        let group = app.buttons["context.open.choir"]+        scrollTo(group, in: app); XCTAssertTrue(group.exists)+        app.terminate()+    }++    @MainActor func testLiteralContextCaptureReusesRecordedGroup() {+        let app = launch(initialInput: "Jason at Swimming")+        tap(childScope("Avery", in: app)); tap(app.buttons["ask.submit"])+        XCTAssertTrue(app.staticTexts["capture.name"].waitForExistence(timeout: 10))+        XCTAssertEqual(app.staticTexts["capture.name"].label, "Jason")+        XCTAssertFalse(app.textFields["ask.newContext.name"].exists)+        let cancel = app.buttons["ask.cancelCapture"]+        scrollTo(cancel, in: app); tap(cancel)+        tap(app.buttons["Home options"]); tap(app.buttons["All groups"])+        XCTAssertTrue(app.buttons["context.open.Swimming"].exists)+        app.terminate()+    }+}++extension WorkspaceUITests {+    @MainActor func testMissingContextPreSaveCancelRetainsDraftAndNoNewGroup() {+        let input = "Jason at tennis"+        let app = launch(initialInput: input)+        tap(childScope("Avery", in: app)); tap(app.buttons["ask.submit"])+        let cancel = app.buttons["ask.newContext.cancel"]+        XCTAssertTrue(cancel.waitForExistence(timeout: 10)); scrollTo(cancel, in: app); tap(cancel)+        XCTAssertEqual(inlineField("home.ask", in: app).value as? String, input)+        XCTAssertFalse(app.buttons["ask.cancelCapture"].exists)+        scrollTo(app.buttons["ask.hideKeyboard"], in: app, towardStart: true); tap(app.buttons["ask.hideKeyboard"])+        tap(app.buttons["Home options"]); tap(app.buttons["All groups"])+        XCTAssertFalse(app.buttons["context.open.tennis"].exists)+        XCTAssertTrue(app.buttons["context.open.Swimming"].exists)+        app.terminate()+    }++    @MainActor func testAlreadyConnectedFriendRoutesToExistingEditorWithoutCreatingGroup() {+        let app = launch(initialInput: "Sam at tennis")+        tap(childScope("Avery", in: app)); tap(app.buttons["ask.submit"])+        let edit = app.buttons["Edit Sam’s recorded relationship"]+        XCTAssertTrue(edit.waitForExistence(timeout: 10)); scrollTo(edit, in: app)+        XCTAssertFalse(app.buttons["ask.newContext.save"].exists)+        tap(edit)+        tap(app.buttons["Person details"])+        XCTAssertTrue(app.staticTexts["person.name"].waitForExistence(timeout: 10))+        XCTAssertEqual(app.staticTexts["person.name"].label, "Sam")+        XCTAssertFalse(app.buttons["ask.cancelCapture"].exists)+        app.terminate()+    }+}++extension WorkspaceUITests {+    @MainActor func testMissingContextReviewAtLargestTextKeepsConfirmationReachable() {+        let app = launch(contentSize: "UICTContentSizeCategoryAccessibilityXXXL", initialInput: "Jason at tennis")+        tap(childScope("Avery", in: app)); tap(app.buttons["ask.submit"])+        let create = app.buttons["ask.newContext.save"]+        XCTAssertTrue(create.waitForExistence(timeout: 10)); scrollTo(create, in: app); assertTouchTarget(create)+        screenshot(app, name: "Missing context confirmation at largest text")+        tap(create)+        let saved = app.staticTexts["capture.name"]+        XCTAssertTrue(saved.waitForExistence(timeout: 10)); XCTAssertEqual(saved.label, "Jason")+        let cancel = app.buttons["ask.cancelCapture"]+        scrollTo(cancel, in: app); tap(cancel)+        XCTAssertTrue(app.staticTexts["Capture discarded."].waitForExistence(timeout: 10))+        app.terminate()+    }+}

Docs (10)

CHANGELOG.md Modified
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b91338c..7dc12bd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,13 @@  ### Added +- Inline missing-context creation in Ask or tell (T-2448), with literal friend/group+  parsing, editable context name, existing-group reuse and explicit parent placement.+- Atomic friend/context/membership capture with immutable reviewed placement,+  canonical-context ambiguity guards and history-bound saved-result cancellation.+- Reusable context review and committed capture IDs/disposition/outcome/lifetime+  for the separately implemented onboarding workflow.+ - Deliberate keyboard Send and an always-visible send icon with native multiline   editing, paste/IME boundaries and duplicate/in-flight guards. - Local-only Apple speech transcription with editable Stop review, original-draft
README.md Modified
diff --git a/README.md b/README.mdindex 1a671df..962ace1 100644--- a/README.md+++ b/README.md@@ -86,8 +86,13 @@ Select a child chip and enter a name or a short sentence. A resolved grounded capture saves immediately with one inline **Edit/Cancel** result; unresolved child, group or namesake choices stay unsaved until explicitly resolved. Available on-device parsing extracts entered facts; short literal name/description capture-remains available when parsing is unavailable. Edit opens the existing saved editor.-Cancel discards only an unchanged new capture while those results remain visible.+remains available when parsing is unavailable. “Jason at swimming” and “Met Rachel+at school” separate the friend and group without a model. A missing group offers+inline Name and Inside review, including Top level, or explicit recorded-group reuse.+Confirmation saves the friend, group and membership together for the existing child;+Ask or tell never creates your own child. Edit opens the existing saved editor.+Cancel discards only an unchanged new capture while those results remain visible,+including its new group; reused or later-used groups are preserved. Leaving the results makes it an ordinary saved record. Quit and reopen to read it.  Open a captured Connection to record its first meeting independently of Context
docs/halo_family_design_pack/10-initial-implementation-results.md Modified
diff --git a/docs/halo_family_design_pack/10-initial-implementation-results.md b/docs/halo_family_design_pack/10-initial-implementation-results.mdindex 95fb508..aebb473 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,79 @@ # Implementation evidence +## T-2448 inline missing-context capture — verified 2026-10-13 UTC++Full requirements/design and sequential critic/independent peer review were committed+as `fe7b0c4` before source work, on `T-2448/ask-context-creation` in `/tmp/halo-t2448`+from current `origin/main` `fa25918`. The deletion checkout and onboarding spec work+remain separate. The current T-2448 ticket was read and updated in place; no duplicate.++“Jason at swimming” and “Met Rachel at school” now separate literal friend/group spans+without model availability. Missing/ambiguous contexts open inline Name/Inside review+with existing-group reuse, Top level or a current parent. Confirmation creates the+context, friend/Connection and membership in one existing graph transaction. No own+ChildProfile or schema is added. Choices retain full physical/canonical ancestry;+confirmation revalidates family/store, exact child, current permissions, eligibility,+cycles, placement, active siblings and duplicate context UUIDs. Existing Connections+route to their editor. Cancel review restores the draft without writing.++Saved-card Edit/Cancel lifetime is retained. Receipts own only newly created graph+rows/context, excluding parents and reused records. Relationship snapshots and bounded+history reject later use, update/delete, use-and-unlink or rename-back before any+cancellation deletion. The reusable receipt returns committed local object IDs,+created/reused flags, saved outcome and visibility; T-2445 owns durable onboarding+checkpoints, history witnesses and resume reconciliation. Cancellation capability is+in memory only. Local checks do not prove distributed context uniqueness or visibility+of unimported remote changes.++Four source reviews (reuse, quality, efficiency, spec/docs) are clear after unsafe+prose fallback and concurrent-Connection editor routing fixes. Late history/canonical+identity guards received clear quality and efficiency rechecks. Native pixels for+parent selection and the retained recorded tree after cancellation were inspected.++Final domain: **302/302 tests in 33 suites, 26.514 seconds**, driver **40.860 seconds**,+exit **0**, JUnit zero failures/errors/skips. Strict lint: **0/157**. Sequential iOS+Simulator/macOS Debug builds pass, driver **54.382 seconds**, exit **0**. Package+coverage export reports **94.49% lines overall** (test executable scope, not native UI):+CaptureContextSelection **95.87%**, CaptureProposal **98.08%**, CaptureReceipt **97.31%**,+ProposedCaptureResolution **89.16%**. These are measured lines, not proof of all branches,+model accuracy, native extensions or live transport.++Seven affected native journeys have passing assertions on the same final host:+already-connected editor, existing saved-card Cancel/Settings lifetime, unique-context+reuse, Met/top-level creation/Edit lifetime, pre-save Cancel, largest-text creation/Cancel+and nested parent placement/joint cancellation. The seven-case invocation records+**six passes/one driver failure in 188.272 seconds**, then a reporting stall stopped+by its owned **450.019-second** bound (exit **143**, incomplete result bundle). The+nested case had already saved/cancelled successfully, then tapped the parent record+link instead of its disclosure, failing to find Class Blue. The corrected driver+retains the classroom and new-context-absence assertions and passes **1/1 in 31.273+seconds**, driver **41.278 seconds**, exit **0**, normal `TEST SUCCEEDED`. Only this+affected case was rerun. The dedicated simulator is Shutdown and its runner exited.++Earlier evidence remains: baseline proposal resolution **16/16**; expected parser and+creation red attempts stopped at missing-interface compilation, no cases executed;+parser/capture **32/32**, transaction/capture **40/40**, review fixes **41/41**, history+focused **23/23**, first full gate **300/300** before the last two safety regressions.+Initial native red: **0 pass/1 expected missing-review-control failure, 31.726 seconds**,+normal runner exit **2**. First implemented retry hit **300.009 seconds**, exit **143**,+without finalized case evidence. Raw-log retry exposed a real **34.33-point** Create+button target: **0 pass/1 failure, 17.855 seconds**, normal driver exit **2**. Moving the+minimum dimensions into button labels corrects it; largest-text and normal journeys+now pass. An intermediate final platform attempt stopped at one lint indentation+violation before builds; corrected lint/platform gate above passes.++Evidence remains under `/tmp/halo-t2448-*.log` and matching receipts; final domain+JUnit/LCOV and hashes are in `/tmp/halo-t2448-review-inputs/final`; successful native+bundle `/tmp/halo-t2448-ui-nested-retry-1.xcresult` and inspected attachments+`/tmp/halo-t2448-native-screens`. Failed/incomplete bundles are retained separately.+Only the UI driver changed between the mixed native run and affected retry; final+host bytes and persistence source stayed unchanged.++Broader native/macOS interaction, real speech/model extraction, actual sharing/cloud+concurrency and physical-device behavior remain separate acceptance. No real family+records, native Contacts, live cloud deletion, main publication, merge or phone install+were performed. Feature/draft publication is authorized after this verification.+ ## Saved cards, deliberate input and native actions — verified 2026-10-13  Source checkpoint `0fcdb47` implements the requested saved-card, keyboard/dictation
docs/halo_family_design_pack/README.md Modified
diff --git a/docs/halo_family_design_pack/README.md b/docs/halo_family_design_pack/README.mdindex 01a1fc8..ecfc55e 100644--- a/docs/halo_family_design_pack/README.md+++ b/docs/halo_family_design_pack/README.md@@ -4,6 +4,7 @@ **Broader product family:** Halo   **Platform:** Native iOS   **Status:** Direction F and reviewed follow-ups use [draft PR #2](https://github.com/ArjenSchwarz/halo-family/pull/2). Shared saved cards, deliberate native Send/local dictation and the general Liquid Glass action pass are implemented and reviewed; 281 domain tests, lint and both platforms pass. Affected phone evidence retains mixed runs and passing corrections. The physical phone contains verified optimized Release `9031353` (app inputs identical to `e40bb33`), installed on 2026-10-13. The user accepted keyboard Send, native buttons and dictation on that build. [Implementation evidence](10-initial-implementation-results.md) owns exact results and remaining acceptance. No merge/main push occurs.+**T-2448:** Reviewed inline missing-context capture is implemented on the isolated `T-2448/ask-context-creation` feature: 302 domain cases, clean strict lint and both platforms pass; seven affected native journeys have passing evidence across a retained mixed run and corrected one-case retry. The onboarding capture seam is reusable; exact failures and runner bounds remain in [implementation evidence](10-initial-implementation-results.md). Feature/draft publication is being completed; no main push, merge or phone install. **Storage:** On-device + iCloud/CloudKit only   **Collaboration:** Shared `FamilySpace` between parents/co-parents 
specs/ask-context-creation/decision_log.md Added
diff --git a/specs/ask-context-creation/decision_log.md b/specs/ask-context-creation/decision_log.mdnew file mode 100644index 0000000..4cefb53--- /dev/null+++ b/specs/ask-context-creation/decision_log.md@@ -0,0 +1,29 @@+# T-2448 decisions++## Authority++Current ticket 3297D09F-63F4-479F-8FF9-D46A884990D0 was read on 2026-10-13, status idea, revision r1:d0faedcb04d2a78e2d7a3e01eff575180c8cdb253e20b92b606682648b747bb2. Its initial future-feature limits are superseded for implementation by the direct request “Good. Then let's implement the missing-context creation ticket now as a key dependency here” and this delegated instruction. Spec review and commit must precede source work. Feature push/draft PR authorized; merge/main push, physical install and live cloud deletion excluded.++## Quick decisions++| ID | Decision | Basis |+| --- | --- | --- |+| Q1 | Full spec named ask-context-creation on T-2448/ask-context-creation | Ticket explicitly requires proper requirements/design; separate origin/main worktree requested. |+| Q2 | Reuse current one-save capture transaction and conservative whole-operation Cancel rejection after adoption/change | Existing receipt semantics and direct stale/shared-record safeguards; no new broad deletion behavior. |+| Q3 | Family-scoped contexts, existing-child-scoped Connection | Current data model owns Context at FamilySpace; no new child ownership boundary. |+| Q4 | No schema change and no automatic creation on parse | Existing Context/ConnectionContext cover storage; ticket requires reviewable confirmation. |+| Q5 | “Met Rachel at school” records membership without inferred first meeting | Existing origin contract requires explicit first-meeting assertion. |+| Q6 | Reject same-name active siblings appearing during new-context review | Avoid silent context duplication or substitution; explicit reuse resolves the new state. |++| Q7 | Already-connected friends route to existing editor; no context created by this result | Existing Ask namesake/duplicateConnection behavior; adding membership to an existing Connection requires different ownership and is outside new-result capture. |+| Q8 | Freeze child and parent placement during context review; unsafe context assertions fail grounding | Reviewer identified re-resolution and model-bypass gaps in applying requested stale-state safety. |++No new durable product choice is required beyond the supplied intent and established record lifetime/ownership contract. Any discovered ambiguity affecting these contracts is raised to the parent before implementation.++## Implementation review resolutions++- Reuse/quality/spec review found unsafe prose slipping through literal or name-only fallback. A shared unsafe-token rule and conservative multiword name grammar retain unsupported drafts; model extraction remains grounded. No whole-input sentence-name fallback is introduced.+- A reused Person gaining a Connection during context review now returns to the existing editor choices after atomic rollback.+- Context choices show canonical UUID distinctions and retain ancestor UUIDs as well as physical placement. Duplicate canonical Context identities reject both reviewed selection and transactional reuse.+- Persistent history rejects later updates/deletes of owned capture rows, including use-and-unlink and rename-back, preserving Cancel safety after ABA changes without a schema field.+- Parent supplied the T-2445 dependency contract during implementation. CaptureReceipt returns committed local object IDs for family/child/Person/Connection/Context, created/reused flags, save outcome and current visibility. T-2445 owns durable checkpoints/history witnesses/resume reconciliation and may resolve canonical UUIDs through the repository. The receipt's deletion capability remains in memory only.
specs/ask-context-creation/design.md Added
diff --git a/specs/ask-context-creation/design.md b/specs/ask-context-creation/design.mdnew file mode 100644index 0000000..6116034--- /dev/null+++ b/specs/ask-context-creation/design.md@@ -0,0 +1,42 @@+# Inline missing-context capture design++## Integration and parity audit++| Existing symbol/file | Equivalent needed | Plan |+| --- | --- | --- |+| Persistence/CaptureProposal.swift, CaptureProposalParser.swift | Yes | Bounded deterministic literal parser precedes the optional model; name-only fallback refuses relational sentences. |+| Persistence/HaloQuestions.swift resolveQuestion | Yes | Preserve questions first, route literal friend/context phrases into capture rather than whole-string Person search. |+| Persistence/ProposedCaptureResolution.swift saveProposedCapture | Yes | Resolve existing child and namesake Person; expose missing/ambiguous context review and explicit new-context input. |+| Persistence/CaptureReceipt.swift confirmedCapture/discardCapture | Yes | Create context within the existing one-save transaction, receipt owns only actually inserted context and capture graph. |+| AskHaloView.swift context-choice results/revalidate/endResults | Yes | Reusable inline context-review component, current scope revalidation and draft reset on lifetime changes. |+| CaptureConfirmationView.swift | No | Currently unused legacy form; no new path depends on it. |+| CaptureRepository.swift typed widget/Intent | No | Explicit existing-reference path retains its API; it does not parse text or create contexts. |+| ContextsView.swift creation form/RelationshipMutations.swift | Baseline | Match Name/Inside/Top level choices; extract only transaction-local insertion if needed, retain ordinary create behavior. |++Paths above are relative to `Halo Family/Halo Family/` unless prefixed Persistence.++## Literal parsing++`ProposedCapture.literalMemory(in:)` accepts bounded friend-name spans followed by one “ at ” separator, optionally prefixed by “Met ”. Each span must be short, nonempty and free of sentence/question punctuation, negation and relational verbs; noninitial name words must start uppercase or be a known name particle; reject repeated separators and unsafe grammar. Preserve exact source case/spans for grounding. “Met” alone records membership, not a first-meeting origin. Run before FoundationModels availability/word-count checks. Other prose continues through the grounded model; nameOnly rejects standalone “at”/“from” relational constructions. Grounding rejects negated or unsafe context assertions even when the model supplies literal spans, so deterministic rejection cannot be bypassed through model output.++## Context selection contract++`CaptureContextCreation` carries the reviewed name and optional immutable parent CaptureContextSelection snapshot. `CaptureContextSelection` carries the displayed ContextRow and its full ancestor rows/IDs, so same-label ancestor moves are detected. The Ask review retains a frozen child ID; callbacks never rebuild an expected snapshot from refreshed repository state. `saveProposedCapture` accepts it separately from an explicit existing context ID and rejects conflicting choices. Context matching remains inside the selected FamilySpace; contexts are family-owned, while the resolved existing ChildProfile owns the new Connection. No other family's contexts or own children can be reused. Eligible contexts/parents must be active and unended; matching uses normalized name/full path and requires a unique identity.++Missing or ambiguous resolution makes no write. When the Person already has a Connection to the selected child, route to its existing Edit link without creating any context or changing the Connection. The inline review shows the friend and child, existing context choices with path plus stable-ID distinction, editable new name, and an Inside picker with Top level and the same path/stable-ID distinctions as existing-context choices. Deliberate Create and remember invokes the shared repository path. Parent selection never creates a parent. Existing context choices remain available when creation is offered.++## Atomic persistence and stale choices++`confirmedCapture` receives the expected family ID and validates the exact resolved child against that family/store inside `FamilyRepository.write`. Opening context review freezes the resolved child ID; a changed roster cannot silently substitute another child. A reviewed parent includes its ID, name, parent ID and displayed path; confirmation compares this placement snapshot, including ancestry, against current state. Existing context selection similarly carries its displayed ContextRow for stale name/path/placement checks. `confirmedCapture` resolves existing Person, existing context or parent inside the transaction. For a new context, validate the name and parent and reject an active normalized same-name sibling under that exact parent; return context choice for explicit reuse. Validate parent ancestry for cycles, same-family/store ancestors. Ancestor archival/end dates do not cascade to eligible descendants; the directly selected context or parent must be current. Insert context and capture/membership before the single save. Any error discards the private transaction context; publish a receipt only after save succeeds. Existing matching continues to re-fetch and validate immediately before mutation. This is local transaction safety, not distributed uniqueness across offline clients.++## Cancel ownership++Receipt snapshots include the actually inserted context and all its relationship sets. The existing guard compares current metadata/links for every owned row before any deletion. Parent and reused context/Person are excluded. Another membership, origin, child context, role, nested context or edit of the new context changes its snapshot and rejects the entire Cancel; no partial cancellation or orphan pruning. Reject later history updates/deletes to any capture-owned row even when its current values/links match again. Preserve the history/audit guard and visibility invalidation on Edit, photo, scope/page/background/navigation and new query. No persisted deletion capability or schema field is added.++## Reusable UI seam++Place `CaptureContextReview` in the host beside `CaptureConfirmationView`. Inputs: proposed friend/context strings, reviewed CaptureContextSelection choices, child label, `onExisting(CaptureContextSelection)` and `onCreate(CaptureContextCreation)`. Draft state belongs to this keyed review; repository errors retain review and refresh choices, invalidating a removed/changed parent selection rather than silently rebuilding its snapshot; the user deliberately reselects before confirmation. Ask owns the child/person selections and result receipt; onboarding can supply the same selections and embed this component. No onboarding storage or device dependency is introduced. The successful CaptureReceipt returns committed family/child/Person/Connection/Context IDs, created-versus-reused flags, saved outcome and in-memory visibility. Onboarding owns durable checkpoints/history witnesses/resume reconciliation; it must not persist the temporary cancellation capability.++## Verification++Swift Testing example tables cover short phrase parsing, question exclusion and rejected unsafe/ambiguous phrases; persistence fixtures cover missing/unique/ambiguous contexts, namesake Persons, child/family isolation, duplicate sibling appearing after review, stale/archived/ended/foreign parents and references, read-only denial and no partial writes. Cancel fixtures cover joint creation, existing Person/context/parent retention, context adoption/edit and expired receipts. Fresh synthetic UI journeys exercise literal phrase → inline review → parent selection → create → saved card → Cancel, and existing-context reuse plus Edit lifetime. Targeted development journeys precede full domain, strict lint and sequential iOS/macOS builds; final affected UI journeys retain every failure and exact counts. No model accuracy, live cloud convergence or phone behavior is claimed.
specs/ask-context-creation/implementation.md Added
diff --git a/specs/ask-context-creation/implementation.md b/specs/ask-context-creation/implementation.mdnew file mode 100644index 0000000..c33da5b--- /dev/null+++ b/specs/ask-context-creation/implementation.md@@ -0,0 +1,17 @@+# T-2448 implementation explanation++## Beginner++“Jason at swimming” and “Met Rachel at school” separate the friend from the group without needing an on-device language model. A missing group opens inline review: its name can be edited and its parent chosen, or a recorded group can be used. Confirming saves the friend relationship and group together. Cancel review writes nothing and restores the draft; the saved-card Cancel removes only the unchanged new result while it remains visible.++## Intermediate++`ProposedCapture.literalMemory` precedes optional model parsing, and shared unsafe-token checks protect the name-only fallback. `CaptureContextReview` exposes immutable existing/new placement selections. Ask freezes the resolved existing child and submits a `CaptureTarget` to `confirmedCapture`; all graph writes share the existing transaction and final save. A namesake must be explicitly reused; an already-connected Person returns to the existing editor. No ChildProfile or schema is created by this path.++## Expert++Context selections retain physical ancestor rows and canonical UUIDs. Transaction validation rechecks expected family/store, exact child, permissions, eligibility, cycles, full placement, duplicate UUIDs and active same-name siblings. Receipt snapshots own only the created Person/Connection graph and actually inserted context. Current links/metadata plus bounded persistent history prevent cancellation after adoption, mutation, use-and-unlink or rename-back. Parent and reused Person/context remain outside deletion ownership. Local validation does not guarantee distributed uniqueness or observe remote edits that have not arrived.++## Completeness assessment++Parsing, inline review, explicit placement, atomic save, reuse, stale-state guards and temporary cancellation are implemented. CaptureReceipt supplies committed local object IDs, creation flags, save outcome and visibility for onboarding; T-2445 owns durable checkpoint/history/resume logic. Full synthetic domain and platform gates pass; final native results are recorded in implementation evidence. Actual model accuracy, macOS interaction, live sharing/CloudKit concurrency and physical-device behavior remain separate acceptance. No live family data, cloud deletion, own-child creation, main publication, merge or phone install was performed.
specs/ask-context-creation/requirements.md Added
diff --git a/specs/ask-context-creation/requirements.md b/specs/ask-context-creation/requirements.mdnew file mode 100644index 0000000..9c64a54--- /dev/null+++ b/specs/ask-context-creation/requirements.md@@ -0,0 +1,35 @@+# Inline missing-context capture (T-2448)++Ask or tell must keep a friend's name separate from where they were met, including when that group has not been recorded. This path is a dependency for the separate friendly onboarding task and must remain reusable without onboarding-specific storage.++## Non-goals++- Own-child creation, automatic context creation, bulk cleanup or ordinary-record deletion.+- Schema changes, invented first-meeting facts, live cloud operations or physical installation.+- Implementing onboarding screens or changing existing relationship editors.++## 1. Literal capture++**User story:** As a parent, I want a short memory interpreted correctly, so that I remember the friend and group separately.++1. <a name="1.1"></a>WHEN I send “Jason at swimming” or “Met Rachel at school”, Halo SHALL extract Jason/Rachel as the friend and swimming/school as the context even without a language model or matching context.  +2. <a name="1.2"></a>WHEN an input cannot be safely separated, Halo SHALL retain the draft or offer review rather than save the sentence as a Person name.  +3. <a name="1.3"></a>Halo SHALL retain recorded-question behavior, namesake choices and current-family child selection; capture SHALL create no ChildProfile.  ++## 2. Review and placement++**User story:** As a parent, I want to choose the group and its parent, so that the friend belongs in the right place.++1. <a name="2.1"></a>WHEN no unique current context matches, Halo SHALL offer existing current family contexts and an inline new-context review with editable name, selected child and a parent choice including Top level, without writing before confirmation.  +2. <a name="2.2"></a>WHEN a unique current context matches, Halo SHALL reuse it; ambiguous names SHALL require identity selection with full paths and record distinctions.  +3. <a name="2.3"></a>WHEN creation is confirmed, Halo SHALL save the friend Person/Connection, context and membership together; existing friend reuse SHALL preserve the Person; IF that friend already has a Connection for this child, Halo SHALL offer its existing editor without creating another context or Connection.  +4. <a name="2.4"></a>IF a matching sibling appears after review begins, or the chosen child, family, parent, Person or context becomes unavailable or changes scope, Halo SHALL reject the stale choice with no partial records and require review.  ++## 3. Saved-result lifetime++**User story:** As a parent, I want the existing Edit and Cancel actions, so that I can correct a new capture safely.++1. <a name="3.1"></a>WHILE saved results remain visible, Cancel SHALL remove only unchanged records created by that capture, including its jointly-created context, and SHALL retain pre-existing Persons, contexts and parents.  +2. <a name="3.2"></a>IF the created graph changes or the new context acquires another reference, Cancel SHALL refuse the whole operation and preserve all records.  +3. <a name="3.3"></a>WHEN results are dismissed, replaced, edited or left, the saved records SHALL become ordinary records and the temporary Cancel capability SHALL expire.  +4. <a name="3.4"></a>The same proposal, context-review and atomic persistence path SHALL be usable by onboarding with an explicitly supplied family and existing child.  
specs/ask-context-creation/review.md Added
diff --git a/specs/ask-context-creation/review.md b/specs/ask-context-creation/review.mdnew file mode 100644index 0000000..7978783--- /dev/null+++ b/specs/ask-context-creation/review.md@@ -0,0 +1,13 @@+# Specification review — 2026-10-13++Design-critic and independent peer/explanation review ran sequentially before source changes. Critic found unsafe model fallback, expected-family/child identity, existing-Connection completion and parent distinction gaps. The plan addresses these through grounding rejection, frozen child validation inside the expected-family transaction, existing editor routing and identity-labelled choices. Peer found immutable callback payload and ancestry-identity gaps; reviewed snapshots now include the full ancestor rows/IDs.++Beginner validation: short memories separate friend/group; missing group is reviewed before any save; unchanged new result is cancellable while visible.+Intermediate validation: deterministic parsing precedes model; reviewed selections enter one atomic write; receipt owns only new records.+Expert validation: current family/store authorization, full placement snapshot and exact child validate in the transaction; link snapshots reject context adoption; local sibling checks do not establish distributed uniqueness.++Final peer verdict: no remaining blocking product/design decision, sufficient self-containment to implement. Independent subagents supplied both reviews; no external third-party AI validator was available. No runtime correctness is claimed by review. Baseline ProposedCaptureResolutionTests passed 16/16 in 0.856 seconds, exit 0. Full/targeted new-feature gates remain pending.++## Implementation review++Four independent source reviews cover reuse, quality, efficiency and spec adherence. Unsafe short-prose/name fallback and newly-connected Person editor routing findings were fixed and rechecked. Full canonical ancestor identity snapshots and persistent-history ABA cancellation guards received final quality/efficiency review; no remaining blocker. Full domain 302/302, strict lint 0/157 and sequential platforms pass. All seven affected native journeys have passing assertion evidence across the qualified mixed run and corrected one-case retry; original failure and reporting stalls are retained in the central evidence document.
specs/ask-context-creation/tasks.md Added
diff --git a/specs/ask-context-creation/tasks.md b/specs/ask-context-creation/tasks.mdnew file mode 100644index 0000000..0bb6cb2--- /dev/null+++ b/specs/ask-context-creation/tasks.md@@ -0,0 +1,41 @@+---+references:+    - requirements.md+    - design.md+    - decision_log.md+---+# T-2448 inline context creation++- [x] 1. Write literal-memory parsing and unsafe-context regression tests <!-- id:4rp0iov -->+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3)++- [x] 2. Implement bounded literal capture before optional model parsing and preserve recorded questions <!-- id:4rp0iow -->+  - Blocked-by: 4rp0iov (Write literal-memory parsing and unsafe-context regression tests)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3)++- [x] 3. Write atomic context creation, stale placement and receipt ownership tests <!-- id:4rp0iox -->+  - Blocked-by: 4rp0iow (Implement bounded literal capture before optional model parsing and preserve recorded questions)+  - Stream: 1+  - Requirements: [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3)++- [x] 4. Implement scoped context review inputs and one-save capture with guarded cancellation <!-- id:4rp0ioy -->+  - Blocked-by: 4rp0iox (Write atomic context creation, stale placement and receipt ownership tests)+  - Stream: 1+  - Requirements: [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3)++- [x] 5. Write synthetic UI journeys for parent selection, create, reuse, Cancel and Edit lifetime <!-- id:4rp0ioz -->+  - Blocked-by: 4rp0ioy (Implement scoped context review inputs and one-save capture with guarded cancellation)+  - Stream: 1+  - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [3.1](requirements.md#3.1), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4)++- [x] 6. Implement reusable inline context review in Ask or tell <!-- id:4rp0ip0 -->+  - Blocked-by: 4rp0ioz (Write synthetic UI journeys for parent selection, create, reuse, Cancel and Edit lifetime)+  - Stream: 1+  - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [3.1](requirements.md#3.1), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4)++- [x] 7. Verify integrated capture with full domain, strict lint, sequential platform and affected native gates <!-- id:4rp0ip1 -->+  - Blocked-by: 4rp0ip0 (Implement reusable inline context review in Ask or tell)+  - Stream: 1+  - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [2.4](requirements.md#2.4), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4)

Things to double-check

Native evidence qualification

Original seven-case run: six passes/one driver failure in 188.272s; reporting stopped at 450.019s, exit143/incomplete bundle. Only failed nested case retried: 1/1 in31.273s, driver41.278s, exit0/normal TEST SUCCEEDED. Host bytes unchanged; only UI driver changed. Earlier expected red, 300-second incomplete retry and 34pt failure remain in central evidence.

Scope and remaining acceptance

No real family records, live cloud deletion, native Contacts, physical installation, main push or merge. Full domain/package coverage does not measure native UI, extensions, model accuracy or live CloudKit concurrency. Dedicated simulator is Shutdown.