Feature preservation and draft PR preparation. Current source: 971 inputs, fingerprint b6de963d…6486. Broader performance and publication gates remain open.
Saved chapter links, exact authored link notes and archive/convergence behavior remain preserved from earlier reviewed feature commits.
The repair fixes Mac chapter re-entry and strict nonzero wide Today restoration without changing navigation ownership or assertions.
Raw screenshots, native attachments, logs and library data remain outside the repository and this review.
Core/fast/native/Mac results retain their b6de source binding; all966inputs outside fiveUITestdrivers are identical. Full iPad33 retains efe8binding; only a private CharacterExtraction driver differs, with no affected iPad/sharedhelper/fixture/product inputs.
Full phone25d:246passed/0failed/2standard skips across245decl/248actual executions;9591.694s,natural0,zero warnings/issues; root and peer accepted. Full iPad33 keeps efe8binding; Core/fast/native/Mac keep b6debinding.
Focused driver validation21/21 includes the formerly failed record-pill journey; every original pill/alias/no-fact/count/UTF-8/44pt/Save-Cancel oracle remains. Both previous failed full runs are preserved as failures, not waived or relabeled.
Scoped UI qualified; broader performance fixes remain
Current complete standard phone UI is independently accepted:245 declarations/248 actual executions,246 passed,zero failed,two exact standard physical-performance simulator skips,9591.694s,natural Make/wrapper0,source971 exact and zero warnings/issues. Current full iPad33/33 retains its accepted efe8source binding; Core/fast/native/Mac results retain b6de bindings with unchanged dependency proofs. Five evidenced UITest driver repairs preserve all original semantic oracles. Earlier failed full runs, including the efe8 missing-wrapper-receipt uncertainty, remain retained unchanged. The branch is ready for a reviewable draft preservation PR; original hard performance failures, the full current52-method performance inventory and final broader publication review prevent merge/publication acceptance.
f5115bbeebdf0f936b42b335969d38bce48de415 T-2468: repair UI acceptance discovery and record qualified gates dc676a968d6d15867b7f125b0c14e4cdd82db1a9 T-2468: repair Mac chapter re-entry and wide Today restoration 6b71307d7408dcd2b1ef302d2bf1147e1ce7c6cd T-2468: record recovered UI qualification and remaining publication gates a9fe5b75b9bacf6472be6bffbb6d5150f904efbc T-2468: scope selected histories and fix work-list environment reads 9f71c5dcf392c155827242e9293b0bbda8737354 T-2468: preserve validated association read and save-path repairs 1c3a66a01fd09a7e794882caeb65b0b576422b57 T-2468: record current duplicate budgets and full performance inventory 6916357228f7cbaf9279306d129d9ed439fc91b3 T-2468: distinguish current and historical qualification records 25da7b800611941f4ec14fdfb4a7dc22cec12eb1 T-2468: document chapter association checkpoint 3376bc2a1206de4aa6058f832ba1ad69669b8f3f T-2468: add chapter associations and note-first record history c7f140c8eda0041a35eaa8f7ba67108e6bf5d851 T-2468: revise associations around the extraction-owned ledger Character and place history remembers supported chapter links and their notes. The repair keeps Today usable after opening a chapter or Work and returning, and preserves where the reader had scrolled.
The existing extraction-owned association ledger, note-head receipts, save-time known-name links and archive/merge hooks remain. The Mac inspector moves inside its Today dashboard stack, guarded by the existing revision binding. Wide Today initializes ScrollPosition from its saved anchor; the noted timeline remains lazy.
The presenter lifetime change keeps the same navigation owner, typed path, factories and reset boundary. Retired dismissals cannot clear a newer selection; transactions propagate through the existing owned binding. iPad hosting stays outside the stack. Exact scalar note/readback and strict same-Y return tests retain their original oracles. A matched diagnostic does not establish universal Observation or large-day performance bounds.
Packages/AsterismCore/Sources/AsterismCore/AssociationLedger.swift
Why it matters. Preserves durable membership independently from authored notes.
What to look at. Association ledger and source/record receipt types
Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+SaveTimeKnownLinks.swift
Why it matters. Saved notes immediately update supported known character/place links while retaining authored history.
What to look at. Save-time known-link integration
Asterism/Asterism/Layout/WideRootView.swift
Why it matters. The original full Save/reopen journey now re-enters the real editor after a Work return.
What to look at. todayStack and TodayStackItemBinding.presentation
Asterism/Asterism/Views/TodayView.swift
Why it matters. Close and replacement-State Work returns preserve the original genuine nonzero position.
What to look at. initializer and wide scroll composition
Asterism/Asterism/Support/PlatformModifiers.swift
Why it matters. Preserves compile-time platform policy and actual chapter title/date controls.
What to look at. Inspector/accessibility/history-preview adapters
Original hard budgets remain failures. This repair preserves earlier fixes and prepares a draft; it introduces no performance redesign or threshold waiver.
Accepted current checks bind the same 971 product inputs. Historical failures and post-principal cleanup qualifications remain explicit.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| minor | Current qualification summaries | Current-facing spec summaries described older source and pending Mac authentication. | Dated b6de acceptance and remaining gates now precede historical receipts. |
| minor | Operational authority | Old merge/install authority appeared in a current task summary. | Historical authority is labelled; current scope is commit/push/PR preparation only. |
| major | Native UI acceptance discovery | Saved rows and review controls could be unrealized, clipped by toolbar chrome or rejected by the driver before native activation. | Five evidence-supported UITest driver repairs retain original semantic oracles; focused21 and completephone246/2standard skips are independently accepted. |
| minor | Core test card provenance | The structured Core card used a later preservation HEAD rather than the actual dirty pre-commit snapshot. | Actual Core planHEAD6b71307d/dirtytrue and completion07:48:38UTC restored; b6desource binding unchanged and no tests rerun. |
| major | Broader performance and publication gates | Original duplicate-observation/settling and capture hard budgets remain breached; complete current52-method performance and finalpublication review remain due. | Explicitly outside this scoped repair; failures and budgets retained without waiver. Draft preservation only, no merge or installation. |
Source: local run at 2026-10-20T07:48:38.898137+00:00 · snapshot 6b71307d7408dcd2b1ef302d2bf1147e1ce7c6cd (dirty working tree)
Baseline: none
Execution: passed · JUnit: 1 file · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
Totals: 4060 passed · 0 failed · 55 skipped · 0 errored · 0 flaky
Derived by declaration name, from the diff (no baseline run).
Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base 47eef29f13baaa2fa043c8fc2bbd2efca6ff120a.
254 files: 219 code · 35 docs. Click to expand.
diff --git a/Asterism/Asterism.xcodeproj/project.pbxproj b/Asterism/Asterism.xcodeproj/project.pbxprojindex c53d9a86..a641e143 100644--- a/Asterism/Asterism.xcodeproj/project.pbxproj+++ b/Asterism/Asterism.xcodeproj/project.pbxproj@@ -113,11 +113,6 @@ /* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ /* Begin PBXFileSystemSynchronizedRootGroup section */- A10000000000000000000046 /* SharedUI */ = {- isa = PBXFileSystemSynchronizedRootGroup;- path = SharedUI;- sourceTree = "<group>";- }; A10000000000000000000005 /* AsterismShareExtension */ = { isa = PBXFileSystemSynchronizedRootGroup; exceptions = (@@ -135,6 +130,11 @@ path = AsterismShareExtensionMac; sourceTree = "<group>"; };+ A10000000000000000000046 /* SharedUI */ = {+ isa = PBXFileSystemSynchronizedRootGroup;+ path = SharedUI;+ sourceTree = "<group>";+ }; D4A9C79630091593004199A5 /* Asterism */ = { isa = PBXFileSystemSynchronizedRootGroup; exceptions = (@@ -250,8 +250,8 @@ dependencies = ( ); fileSystemSynchronizedGroups = (- A10000000000000000000046 /* SharedUI */, A10000000000000000000005 /* AsterismShareExtension */,+ A10000000000000000000046 /* SharedUI */, ); name = AsterismShareExtension; packageProductDependencies = (@@ -276,9 +276,9 @@ dependencies = ( ); fileSystemSynchronizedGroups = (- A10000000000000000000046 /* SharedUI */, A10000000000000000000005 /* AsterismShareExtension */, A10000000000000000000026 /* AsterismShareExtensionMac */,+ A10000000000000000000046 /* SharedUI */, ); name = AsterismShareExtensionMac; packageProductDependencies = (@@ -1015,6 +1015,44 @@ CURRENT_PROJECT_VERSION = 1; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = V24684SCZN;+ "EXCLUDED_SOURCE_FILE_NAMES[sdk=macosx*]" = (+ AccessibilityJourneyUITests.swift,+ AnnouncementUITests.swift,+ BackgroundExportSettingsUITests.swift,+ ChapterNotesUITests.swift,+ CharacterExtractionUITests.swift,+ ComposedSurfaceUITests.swift,+ CreatorRolesSettingsUITests.swift,+ CreatorsUITests.swift,+ DuplicateResolutionUITests.swift,+ EmptyLibrarySettingsUITests.swift,+ EntryToWorkLinkUITests.swift,+ LibraryDiagnosticsUITests.swift,+ M4ScaleTodayPerformanceUITests.swift,+ PendingCaptureSettingsUITests.swift,+ PublicationReturnDateUITests.swift,+ ReparseSheetUITests.swift,+ SearchUITests.swift,+ SeriesUITests.swift,+ SitesSettingsUITests.swift,+ StatsUITests.swift,+ TodayUITests.swift,+ UIJourneySupport.swift,+ WideLayoutUITests.swift,+ WorkCoverUITests.swift,+ WorkDetailActionsUITests.swift,+ WorkDetailConnectionsUITests.swift,+ WorkDetailCreditsUITests.swift,+ WorkDetailStatusUITests.swift,+ WorkRecordCopyOfferUITests.swift,+ WorkRecordCopyUITests.swift,+ WorkTypesSettingsUITests.swift,+ WorksAndAssignmentUITests.swift,+ WorksCreatorOptionsUITests.swift,+ WorksListOptionsUITests.swift,+ WorksLoadGateUITests.swift,+ WorksSeriesOptionsUITests.swift,+ ); GENERATE_INFOPLIST_FILE = YES; IPHONEOS_DEPLOYMENT_TARGET = 26.0; MACOSX_DEPLOYMENT_TARGET = 26.5;@@ -1041,6 +1079,44 @@ CURRENT_PROJECT_VERSION = 1; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = V24684SCZN;+ "EXCLUDED_SOURCE_FILE_NAMES[sdk=macosx*]" = (+ AccessibilityJourneyUITests.swift,+ AnnouncementUITests.swift,+ BackgroundExportSettingsUITests.swift,+ ChapterNotesUITests.swift,+ CharacterExtractionUITests.swift,+ ComposedSurfaceUITests.swift,+ CreatorRolesSettingsUITests.swift,+ CreatorsUITests.swift,+ DuplicateResolutionUITests.swift,+ EmptyLibrarySettingsUITests.swift,+ EntryToWorkLinkUITests.swift,+ LibraryDiagnosticsUITests.swift,+ M4ScaleTodayPerformanceUITests.swift,+ PendingCaptureSettingsUITests.swift,+ PublicationReturnDateUITests.swift,+ ReparseSheetUITests.swift,+ SearchUITests.swift,+ SeriesUITests.swift,+ SitesSettingsUITests.swift,+ StatsUITests.swift,+ TodayUITests.swift,+ UIJourneySupport.swift,+ WideLayoutUITests.swift,+ WorkCoverUITests.swift,+ WorkDetailActionsUITests.swift,+ WorkDetailConnectionsUITests.swift,+ WorkDetailCreditsUITests.swift,+ WorkDetailStatusUITests.swift,+ WorkRecordCopyOfferUITests.swift,+ WorkRecordCopyUITests.swift,+ WorkTypesSettingsUITests.swift,+ WorksAndAssignmentUITests.swift,+ WorksCreatorOptionsUITests.swift,+ WorksListOptionsUITests.swift,+ WorksLoadGateUITests.swift,+ WorksSeriesOptionsUITests.swift,+ ); GENERATE_INFOPLIST_FILE = YES; IPHONEOS_DEPLOYMENT_TARGET = 26.0; MACOSX_DEPLOYMENT_TARGET = 26.5;
diff --git a/Asterism/Asterism/CharacterExtraction/CharacterExtractionCoordinator.swift b/Asterism/Asterism/CharacterExtraction/CharacterExtractionCoordinator.swiftindex 4d21d1d3..d1403c5e 100644--- a/Asterism/Asterism/CharacterExtraction/CharacterExtractionCoordinator.swift+++ b/Asterism/Asterism/CharacterExtraction/CharacterExtractionCoordinator.swift@@ -34,6 +34,7 @@ final class CharacterExtractionCoordinator { /// without asking the coordinator to remember which page is open. private(set) var manualOutcomes: [UUID: ManualPassOutcome] = [:] + private let onMutation: @MainActor () async -> Void private let library: any LibraryProviding private let model: any CharacterExtractionModelClient private let extractor: CharacterExtractor@@ -54,6 +55,9 @@ final class CharacterExtractionCoordinator { /// preview and nothing else, because the commit dedups against the store. /// Refreshed by every pass over the work and by `reconcile()`. private var contexts: [UUID: CharacterExtractionContext] = [:]+ /// Captured display provenance from this work's attempts, including sources+ /// with no actionable new pair. It conveys no commit/coverage authority.+ private var capturedEvidence: [UUID: [ProposalKey: [ProposalSourceEvidence]]] = [:] /// The attempt is the coordinator's, never the caller's: a view that goes /// away must not cancel work the ledger has already recorded. private var attemptTask: Task<SourceOutcome, Never>?@@ -64,8 +68,10 @@ final class CharacterExtractionCoordinator { model: any CharacterExtractionModelClient, environment: any SuggestionEnvironment = SystemSuggestionEnvironment(), lane: ModelLane = .shared,- timeout: Duration = CharacterExtractionBounds.attemptTimeout+ timeout: Duration = CharacterExtractionBounds.attemptTimeout,+ onMutation: @escaping @MainActor () async -> Void = {} ) {+ self.onMutation = onMutation self.library = library self.model = model self.extractor = CharacterExtractor(model: model, timeout: timeout)@@ -77,12 +83,23 @@ final class CharacterExtractionCoordinator { // MARK: - Reads /// The rows the review sheet shows for one work (Req 2.1).- func held(for work: UUID) -> [ExtractionProposal] { ledger.held(for: work) }+ func held(for work: UUID) -> [ExtractionProposal] {+ ledger.held(for: work).filter { proposal in+ guard proposal.displayedKind == .character else { return true }+ guard proposal.target != .unresolved else { return false }+ guard let context = contexts[work] else { return !proposal.isBundle }+ let targets = context.records(of: .character).map { record in+ MatchTarget(id: record.id, currentNameKey: RecordNameKey.normalize(record.name),+ retainedKey: record.retainedKey, aliasKeys: record.aliases.map(RecordNameKey.normalize), isTorn: record.isTorn)+ }+ return RecordMatching.recognition(nameKey: proposal.nameKey, among: targets) == .noMatch+ }+ } /// Whether the work's page shows the proposals indicator (Req 2.1).- func hasProposals(for work: UUID) -> Bool { !ledger.held(for: work).isEmpty }+ func hasProposals(for work: UUID) -> Bool { !held(for: work).isEmpty } - var worksWithProposals: Set<UUID> { ledger.worksWithProposals }+ var worksWithProposals: Set<UUID> { Set(ledger.worksWithProposals.filter { !held(for: $0).isEmpty }) } /// The work's last candidate read, or nil when no pass or reconcile has /// seen the work in this run. The reclassify preview's input (Req 2.2).@@ -250,7 +267,7 @@ final class CharacterExtractionCoordinator { recordIDs: Dictionary( uniqueKeysWithValues: RecordKind.allCases.map { ($0, Set(row.records(of: $0).map(\.id)))- }))+ }), eligibility: row.eligibilityBySource, sourceGuards: row.mentionIndex.sourceGuards) // The newest read of a tracked work is the one a reclassify preview // should be run against (Req 2.2). contexts[row.workID] = CharacterExtractionContext(row)@@ -260,6 +277,8 @@ final class CharacterExtractionCoordinator { for work in tracked where states[work] == nil { contexts[work] = nil } let invalidated = ledger.reconcile(against: states)+ for row in rows { ledger.refreshMentionDecisions(for: row.workID, index: row.mentionIndex) }+ for row in rows { await routeHeldRecognised(in: row) } pruneContexts() if !invalidated.isEmpty { CharacterExtractionLog.note("reconcile invalidated \(invalidated.count) work(s)")@@ -280,6 +299,7 @@ final class CharacterExtractionCoordinator { private func pruneContexts() { let tracked = ledger.trackedWorks contexts = contexts.filter { tracked.contains($0.key) }+ capturedEvidence = capturedEvidence.filter { tracked.contains($0.key) } } /// Req 1.2: the sweep stops with the foreground, and its attempt with it. A@@ -293,6 +313,7 @@ final class CharacterExtractionCoordinator { func memoryWarning() { // The retained reads go with the rows they were kept to preview. contexts.removeAll()+ capturedEvidence.removeAll() if ledger.memoryWarning() != nil { attemptTask?.cancel() } } @@ -329,7 +350,7 @@ final class CharacterExtractionCoordinator { await process(candidate, pass: .manual) - let held = ledger.held(for: workID)+ let held = held(for: workID) manualOutcomes[workID] = held.isEmpty ? .noProposals : .proposals(held.count) } @@ -346,6 +367,7 @@ final class CharacterExtractionCoordinator { ) async { let context = CharacterExtractionContext(candidate) contexts[candidate.workID] = context+ await routeHeldRecognised(in: candidate) let revisions = candidate.revisionsBySource let sources = candidate.extractionSources(includingCovered: pass == .manual) var covered: [CompletedSource] = []@@ -369,9 +391,9 @@ final class CharacterExtractionCoordinator { } let outcome = await attempt( source, context: context, revisions: revisions, pass: pass)- if outcome == .producedNone {+ if outcome == .producedNone, !ledger.held(for: candidate.workID).contains(where: { $0.citedRevisions[source.source] != nil }) { covered.append(- CompletedSource(ref: source.source, fingerprint: source.fingerprint))+ CompletedSource(ref: source.source, fingerprint: source.fingerprint, mentionEligibilityDigest: source.mentionEligibilityDigest)) } } @@ -379,6 +401,19 @@ final class CharacterExtractionCoordinator { guard !covered.isEmpty else { return } do {+ // Pending registration changes completion eligibility, not saved+ // source text. Refresh that bookkeeping only after every local key+ // settled, retaining the exact original source/guard basis.+ if covered.contains(where: { $0.mentionEligibilityDigest != nil }) {+ guard let current = try await library.extractionCandidates(limit: 1, workIDs: [candidate.workID]).first else { return }+ covered = covered.compactMap { captured in+ guard let source = current.sources.first(where: { $0.ref == captured.ref && $0.fingerprint == captured.fingerprint }) else { return nil }+ if let id = captured.ref.entryID,+ candidate.mentionIndex.sourceGuards[id] != current.mentionIndex.sourceGuards[id] { return nil }+ return source.completedSource+ }+ guard !covered.isEmpty else { return }+ } let written = try await library.advanceCoverage( workID: candidate.workID, sources: covered) CharacterExtractionLog.note(@@ -412,7 +447,7 @@ final class CharacterExtractionCoordinator { while true { switch ledger.start(- key, fingerprint: source.fingerprint, pass: pass,+ key, fingerprint: source.attemptFingerprint, pass: pass, environment: currentEnvironment ) { case .refuse(let reason):@@ -480,11 +515,59 @@ final class CharacterExtractionCoordinator { let started = self.environment.now do { let outcome = try await self.extractor.attempt(source)- let proposals = CharacterExtractionAssembler.assemble(- outcome.candidates, revisions: revisions, context: context, pass: pass)- self.settle(- key, .proposals(proposals), modelPhase: outcome.modelPhase, label: label)- return proposals.isEmpty ? .producedNone : .produced+ // Model work is complete; subsequent guarded I/O owns no lane.+ token.release()+ var routingContext = context+ if case .entry(let entryID) = source.source,+ !context.mentionIndex.pendingReviewReferences[entryID, default: []].isEmpty {+ // A review can settle while the model is awaiting. Reuse+ // only still-relevant original keys from a fresh guarded+ // read; stale captured references cannot resurrect a row.+ guard let current = try await self.library.extractionCandidates(limit: 1, workIDs: [source.workID]).first,+ current.sources.contains(where: { $0.ref == source.source && $0.fingerprint == source.fingerprint }),+ current.mentionIndex.sourceGuards[entryID] == context.mentionIndex.sourceGuards[entryID] else {+ throw LibraryRepositoryError.invalidInput(operation: "routing extracted character links", reason: "source changed during pending recovery")+ }+ routingContext = CharacterExtractionContext(current)+ self.contexts[source.workID] = routingContext+ }+ let grounded = self.recoverPendingCandidates(outcome.candidates, source: source, context: routingContext)+ for candidate in grounded {+ guard var evidence = candidate.sourceEvidence else { continue }+ evidence.isDecisionBasis = false+ let candidateKey = ProposalKey(kind: candidate.kind, nameKey: candidate.nameKey)+ self.capturedEvidence[source.workID, default: [:]][candidateKey] = ProposalSourceEvidence.merged(+ (self.capturedEvidence[source.workID]?[candidateKey, default: []] ?? []) + [evidence])+ }+ let proposals = CharacterExtractionAssembler.assembleNoteFirst(+ grounded, revisions: revisions, context: routingContext, pass: pass).map { proposal in+ var value = proposal+ let informational = proposal.returnedKinds.flatMap { kind in+ self.capturedEvidence[source.workID]?[ProposalKey(kind: kind, nameKey: proposal.nameKey), default: []] ?? []+ }+ value.sourceEvidence = ProposalSourceEvidence.merged(informational + proposal.sourceEvidence)+ return value+ }+ do {+ let durable = try await self.preservePendingMentions(proposals, context: routingContext, workID: source.workID)+ try Task.checkCancellation()+ let routed = await self.routeRecognised(durable.map { .init(proposal: $0, origin: $0.key) }, workID: source.workID)+ if Task.isCancelled {+ self.settle(key, .cancelled, modelPhase: outcome.modelPhase, label: label)+ if routed.didCommit { await self.onMutation() }+ return .unsettled+ }+ self.settle(key, .proposals(routed.review.map(\.proposal)), modelPhase: outcome.modelPhase, label: label)+ if routed.didCommit { await self.onMutation() }+ if Task.isCancelled { return .unsettled }+ if routed.unresolved { return .unsettled }+ return routed.review.isEmpty ? .producedNone : .produced+ } catch {+ CharacterExtractionLog.failure("\(label): pending review was not published — \(CharacterExtractionLog.describe(error))")+ self.settle(key, error is CancellationError ? .cancelled : .failed,+ modelPhase: outcome.modelPhase, label: label)+ return .unsettled+ } } catch is CancellationError { self.settle( key, .cancelled, modelPhase: self.elapsed(since: started), label: label)@@ -508,6 +591,260 @@ final class CharacterExtractionCoordinator { } } + /// Directory changes can turn an old creation/folded row into a recognised+ /// character without another model call or another approval tap.+ private func routeHeldRecognised(in candidate: ExtractionCandidate) async {+ let held = ledger.held(for: candidate.workID)+ guard !held.isEmpty else { return }+ let context = CharacterExtractionContext(candidate)+ guard held.contains(where: { proposal in+ proposal.displayedKind == .character && RecordMatching.recognition(nameKey: proposal.nameKey,+ among: candidate.records(of: .character)) != .noMatch+ }) else { return }+ var rerouted: [HeldContribution] = []+ for original in held {+ guard original.displayedKind == .character else { rerouted.append(.init(proposal: original, origin: original.key)); continue }+ let recognition = RecordMatching.recognition(nameKey: original.nameKey,+ among: candidate.records(of: .character))+ guard recognition != .noMatch else { rerouted.append(.init(proposal: original, origin: original.key)); continue }+ var proposal = original+ proposal.isNoteFirst = true; proposal.facts = []+ proposal.returnedKinds = [.character]+ switch recognition {+ case .noMatch: break+ case .unique(let id):+ proposal.target = context.mentionIndex.canLink(kind: .character, recordID: id) ? .existing(id) : .unresolved+ case .ambiguous: proposal.target = .unresolved+ }+ let target: UUID? = if case .existing(let id) = proposal.target { id } else { nil }+ proposal.mentions = proposal.citedRevisions.compactMap { source, fingerprint in+ guard case .entry(let entryID) = source,+ context.mentionIndex.eligibleEntries.contains(entryID),+ let sourceGuard = context.mentionIndex.sourceGuards[entryID] else { return nil }+ if let target, context.mentionIndex.isSuppressed(entryID: entryID, kind: .character,+ recordID: target, spellingKey: proposal.nameKey) { return nil }+ return .init(entryID: entryID, noteFingerprint: fingerprint,+ spellingKeys: [proposal.nameKey], observedRejectionIDs: target.map {+ context.mentionIndex.rejectionIDs(entryID: entryID, kind: .character,+ recordID: $0, spellingKeys: [proposal.nameKey])+ } ?? [], sourceGuard: sourceGuard)+ }+ if original.isDualKind && original.kind == .character {+ // The formerly folded place is a separate pending obligation+ // before the character's original key can settle.+ var place = original+ place.kind = .place; place.displayedKind = .place+ place.returnedKinds = [.place]; place.isNoteFirst = true; place.facts = []+ place.target = candidate.match(nameKey: place.nameKey, kind: .place).map { .existing($0.id) } ?? .newRecord+ let placeID: UUID? = if case .existing(let id) = place.target { id } else { nil }+ place.mentions = original.citedRevisions.compactMap { source, fingerprint in+ guard case .entry(let entryID) = source,+ context.mentionIndex.eligibleEntries.contains(entryID),+ let sourceGuard = context.mentionIndex.sourceGuards[entryID] else { return nil }+ return context.mentionIndex.refreshed(.init(entryID: entryID, noteFingerprint: fingerprint,+ spellingKeys: [place.nameKey], sourceGuard: sourceGuard), kind: .place,+ recordID: placeID, reconsider: place.isManual)+ }+ place.reviewAcknowledgements = []+ rerouted.append(.init(proposal: place, origin: original.key))+ }+ rerouted.append(.init(proposal: proposal, origin: original.key))+ }+ do {+ let durable = try await preservePendingMentions(rerouted.map(\.proposal), context: context, workID: candidate.workID)+ let contributions = zip(durable, rerouted).map { HeldContribution(proposal: $0.0, origin: $0.1.origin) }+ let routed = await routeRecognised(contributions, workID: candidate.workID)+ replaceCapturedHeld(held, with: routed.review, workID: candidate.workID)+ if routed.didCommit { await onMutation() }+ } catch {+ // Never leave known characters behind an approval button when a+ // guarded write fails. Durable obligations remain available to retry.+ replaceCapturedHeld(held, with: rerouted.filter { $0.proposal.displayedKind != .character || $0.proposal.target == .newRecord }, workID: candidate.workID)+ CharacterExtractionLog.failure("known character routing failed — \(CharacterExtractionLog.describe(error))")+ }+ }++ /// Origin is per contribution, not destination key: a folded character can+ /// yield a place whose key is also held independently for another source.+ private struct HeldContribution {+ var proposal: ExtractionProposal+ var origin: ProposalKey+ }++ /// Awaited writes may have admitted a sibling or a newer revision of the+ /// same key. Replace only unchanged captured rows; never wipe the work.+ private func replaceCapturedHeld(_ captured: [ExtractionProposal], with replacements: [HeldContribution], workID: UUID) {+ let bases = Dictionary(captured.map { ($0.key, $0) }, uniquingKeysWith: { first, _ in first })+ let current = ledger.held(for: workID)+ let changed = Set(current.filter { bases[$0.key] != $0 }.map(\.key))+ let removed = Set(bases.keys).subtracting(current.map(\.key))+ var result = current.filter { changed.contains($0.key) }+ for contribution in replacements {+ let proposal = contribution.proposal+ guard !changed.contains(proposal.key), !removed.contains(proposal.key),+ !changed.contains(contribution.origin), !removed.contains(contribution.origin) else { continue }+ if let index = result.firstIndex(where: { $0.key == proposal.key }) {+ result[index] = CharacterExtractionLedger.merged(result[index], into: proposal)+ } else { result.append(proposal) }+ }+ ledger.replaceHeld(result, for: workID)+ }++ /// Pending keys are obligations, not model output. Reground their literal+ /// spelling against the same guarded current chapter before classifying them.+ /// An empty retry must never erase an ambiguous chapter obligation.+ private func recoverPendingCandidates(_ candidates: [GroundedCandidate], source: ExtractionSource,+ context: CharacterExtractionContext) -> [GroundedCandidate] {+ var result = candidates+ var keys = Set(candidates.map { ProposalKey(kind: $0.kind, nameKey: $0.nameKey) })+ var pending: Set<ProposalKey> = []+ if case .entry(let entryID) = source.source,+ context.mentionIndex.eligibleEntries.contains(entryID),+ context.mentionIndex.sourceGuards[entryID] != nil {+ pending.formUnion(context.mentionIndex.pendingReviewReferences[entryID, default: []].compactMap {+ guard $0.key.kind == .place || RecordMatching.recognition(nameKey: $0.key.nameKey,+ among: context.records(of: .character).map { record in+ MatchTarget(id: record.id, currentNameKey: RecordNameKey.normalize(record.name),+ retainedKey: record.retainedKey, aliasKeys: record.aliases.map(RecordNameKey.normalize), isTorn: record.isTorn)+ }) != .noMatch else { return nil }+ return ProposalKey(kind: $0.key.kind, nameKey: $0.key.nameKey)+ })+ }+ for held in ledger.held(for: source.workID)+ where held.citedRevisions[source.source] == source.fingerprint {+ for kind in held.returnedKinds { pending.insert(.init(kind: kind, nameKey: held.nameKey)) }+ }+ for key in pending.sorted(by: { $0.rowID < $1.rowID }) where keys.insert(key).inserted {+ // Fallback recovery is not an explicit manual reconsideration. A+ // committed candidate Skip remains effective on an empty response.+ let records = context.records(of: key.kind).map { record in+ MatchTarget(id: record.id, currentNameKey: RecordNameKey.normalize(record.name),+ retainedKey: record.retainedKey, aliasKeys: record.aliases.map(RecordNameKey.normalize), isTorn: record.isTorn)+ }+ if RecordMatching.recognition(nameKey: key.nameKey, among: records) == .noMatch,+ context.suppressedNameKeys(of: key.kind).contains(key.nameKey) { continue }+ let literal = RecordMentionGrounding.evidence(names: [key.nameKey], in: source.text)+ guard let name = literal.first?.spelling else { continue }+ result.append(.init(name: name, nameKey: key.nameKey, kind: key.kind, proposedAliases: [],+ source: source.source, facts: [], sourceEvidence: .init(source: source, spellings: literal.map(\.spelling))))+ }+ return result+ }++ private func routeRecognised(_ contributions: [HeldContribution], workID: UUID) async+ -> (review: [HeldContribution], unresolved: Bool, didCommit: Bool) {+ var review: [HeldContribution] = []+ let proposals = contributions.map(\.proposal)+ var unresolved = false, didCommit = false+ for (index, contribution) in contributions.enumerated() {+ if Task.isCancelled {+ // Preserve ordinary decisions, but launch no more unattended+ // writes after cancellation. Earlier committed links still publish.+ review += contributions.dropFirst(index).filter {+ $0.proposal.displayedKind != .character || $0.proposal.target == .newRecord+ }+ return (review, true, didCommit)+ }+ let proposal = contribution.proposal+ guard proposal.displayedKind == .character else { review.append(contribution); continue }+ switch proposal.target {+ case .newRecord:+ review.append(contribution)+ case .unresolved:+ unresolved = true+ case .existing:+ // No held row, aliases, facts or reconsideration authority can+ // leak through the narrow automatic repository operation.+ let isChapter = proposal.sourceEvidence.contains { $0.isChapter && $0.isDecisionBasis }+ if isChapter && proposal.mentions.isEmpty {+ unresolved = unresolved || !proposal.reviewAcknowledgements.allSatisfy { $0.references.isEmpty }+ continue+ }+ var request = proposal.decisionRequest(workID: workID, action: .accept)+ request.returnedKinds = [.character]+ request.proposedAliases = []; request.facts = []; request.untickedFacts = []+ request.displayedKeys = [proposal.nameKey]+ // Each key acknowledges only itself; coverage cannot leap over+ // another unresolved/new/place key from this source.+ request.completedSources = request.completedSources.map { source in+ CompletedSource(ref: source.ref, fingerprint: source.fingerprint,+ mentionEligibilityDigest: proposals.contains { $0.key != proposal.key && $0.citedRevisions[source.ref] != nil }+ ? nil : source.mentionEligibilityDigest)+ }+ let outcome: DecisionOutcome+ do {+ outcome = if proposal.kind == .place {+ try await library.commitReclassifiedRecognisedCharacter(request)+ } else {+ try await library.commitRecognisedCharacter(request)+ }+ } catch {+ unresolved = true+ CharacterExtractionLog.failure("known character save failed — \(CharacterExtractionLog.describe(error))")+ continue+ }+ if case .committed = outcome {+ didCommit = true+ } else {+ unresolved = true+ }+ }+ }+ return (review, unresolved, didCommit)+ }++ /// Persist only actual proposed chapter mentions, before exposing held RAM.+ /// Fact-only/generic/nonchapter sources retain their existing coverage lane.+ private func preservePendingMentions(_ proposals: [ExtractionProposal], context: CharacterExtractionContext,+ workID: UUID) async throws -> [ExtractionProposal] {+ let grouped = Dictionary(grouping: proposals.flatMap { proposal in+ proposal.mentions.compactMap { mention -> (ExtractionProposal, AssociationMentionDecision)? in+ let key = AssociationReviewKey(kind: proposal.kind, nameKey: proposal.nameKey)+ if context.mentionIndex.pendingReviewReferences[mention.entryID, default: []].contains(where: { $0.key == key }) {+ return nil+ }+ if proposal.kind == .character, case .existing(let id) = proposal.target,+ let pair = context.mentionIndex.pair(entryID: mention.entryID, kind: .character, recordID: id),+ context.mentionIndex.activePairs.contains(pair) { return nil }+ return (proposal, mention)+ }+ }, by: { $0.1.entryID })+ guard !grouped.isEmpty else { return proposals }+ let requests = try grouped.sorted { $0.key.uuidString < $1.key.uuidString }.map { entryID, values in+ let guards = Set(values.compactMap { $0.1.sourceGuard })+ guard guards.count == 1, let sourceGuard = guards.first,+ values.allSatisfy({ $0.1.sourceGuard == sourceGuard }) else {+ throw LibraryRepositoryError.invalidInput(operation: "preserving pending mention review", reason: "source guard unavailable")+ }+ let items = values.map { proposal, mention in+ let target: UUID? = if case .existing(let id) = proposal.target { id } else { nil }+ return AssociationPendingReviewItem(key: .init(kind: proposal.kind, nameKey: proposal.nameKey),+ targetID: target, spellingKeys: mention.spellingKeys)+ }+ return AssociationPendingReviewRequest(marker: .init(workID: workID, entryID: entryID,+ sourceGuard: sourceGuard, items: items), originalEligibilityBase: context.mentionIndex.coverageBases[entryID],+ originalEligibilityDigest: context.mentionIndex.eligibilityByEntry[entryID])+ }+ let results = try await library.recordPendingMentionReviews(requests)+ let byEntry = Dictionary(grouping: results, by: \.entryID)+ guard requests.allSatisfy({ byEntry[$0.marker.entryID]?.count == 1 }) else {+ throw LibraryRepositoryError.invalidInput(operation: "preserving pending mention review", reason: "pending review was not preserved")+ }+ return proposals.map { proposal in+ var result = proposal+ let key = AssociationReviewKey(kind: proposal.kind, nameKey: proposal.nameKey)+ let entries = Set(proposal.mentions.map(\.entryID))+ result.reviewAcknowledgements.removeAll { entries.contains($0.entryID) && byEntry[$0.entryID] != nil }+ for entryID in entries {+ guard let saved = byEntry[entryID]?.first, saved.workID == workID else { continue }+ result.citedMentionEligibility[.entry(entryID)] = saved.completionDigest+ result.reviewAcknowledgements.append(.init(workID: workID, entryID: entryID,+ references: saved.references.filter { $0.key == key }))+ }+ return result+ }+ }+ private func settle( _ key: ExtractionSourceKey, _ settlement: ExtractionSettlement, modelPhase: Duration, label: String
diff --git a/Asterism/Asterism/CharacterExtraction/CharacterExtractor.swift b/Asterism/Asterism/CharacterExtraction/CharacterExtractor.swiftindex dcf491e2..acfd7ca1 100644--- a/Asterism/Asterism/CharacterExtraction/CharacterExtractor.swift+++ b/Asterism/Asterism/CharacterExtraction/CharacterExtractor.swift@@ -51,7 +51,10 @@ actor CharacterExtractor { try await model.extract(source) } - let grounded = CharacterGrounding.ground(result, from: source)+ // Test doubles/obsolete held shapes cannot reintroduce generated facts.+ let names = ExtractionResult(characters: result.characters.map { .init(name: $0.name) },+ places: result.places.map { .init(name: $0.name) })+ let grounded = CharacterGrounding.ground(names, from: source) for drop in grounded.drops { CharacterExtractionLog.note( "\(CharacterExtractionLog.describe(source.source)): dropped a \(drop.kind.rawValue) "
diff --git a/Asterism/Asterism/CharacterExtraction/CharacterReviewModel.swift b/Asterism/Asterism/CharacterExtraction/CharacterReviewModel.swiftindex 00e3a7c5..c50727fa 100644--- a/Asterism/Asterism/CharacterExtraction/CharacterReviewModel.swift+++ b/Asterism/Asterism/CharacterExtraction/CharacterReviewModel.swift@@ -71,6 +71,7 @@ struct CharacterReviewRow: Identifiable, Equatable, Sendable { /// The record a bundle enriches, for the existing facts it is shown /// beside (Q38). let targetID: UUID?+ let sourceEvidence: [ProposalSourceEvidence] var aliases: [CharacterReviewAlias] var proposedFacts: [CharacterReviewFact] /// The target record's facts as they stand, so the reader can see what the@@ -107,7 +108,8 @@ struct CharacterReviewRow: Identifiable, Equatable, Sendable { /// which still offers the destination a name it does not have is a real /// addition, and disabling Keep on it threw that alias away. var canAccept: Bool {- kind == originalKind || !proposedFacts.isEmpty || proposal.facts.isEmpty+ guard projected.target != .unresolved else { return false }+ return kind == originalKind || !proposedFacts.isEmpty || proposal.facts.isEmpty || aliases.contains { !$0.isStruck } } }@@ -161,6 +163,7 @@ final class CharacterReviewModel: Identifiable { /// The work's last candidate read, as the coordinator retains it. The /// reclassify preview's suppression input (Req 2.2), and nil before any /// pass has seen the work in this run.+ private let currentHeld: (@MainActor () -> [ExtractionProposal])? private let extractionContext: @MainActor () -> CharacterExtractionContext? /// Whether a row's decision is being committed. One flag for the sheet — /// decisions commit one save each and the guard in `decide` serialises@@ -179,18 +182,21 @@ final class CharacterReviewModel: Identifiable { onDecision: @escaping @MainActor (ProposalKey, Set<RecordKind>) -> Void, onReRoute: @escaping @MainActor (ProposalKey, UUID?) -> Void, onReclassify: @escaping @MainActor (ProposalKey, RecordKind, UUID?) -> Void,- refresh: @escaping @MainActor () async -> [ExtractionProposal]+ refresh: @escaping @MainActor () async -> [ExtractionProposal],+ currentHeld: (@MainActor () -> [ExtractionProposal])? = nil ) { self.workID = workID self.inputs = ReviewInputs( characters: characters, places: places, captureOrder: captureOrder,- suppressedFacts: extractionContext()?.suppressedFacts ?? [:])+ suppressedFacts: extractionContext()?.suppressedFacts ?? [:],+ mentionIndex: extractionContext()?.mentionIndex ?? .empty) self.library = library self.extractionContext = extractionContext self.onDecision = onDecision self.onReRoute = onReRoute self.onReclassify = onReclassify self.refresh = refresh+ self.currentHeld = currentHeld // Snapshot at open (Req 2.7). let inputs = self.inputs self.rows = proposals.map { Self.row(from: $0, inputs: inputs) }@@ -245,6 +251,10 @@ final class CharacterReviewModel: Identifiable { } rows[rowIndex] = rebuilt onReclassify(row.key, kind, rebuilt.targetID)+ if rebuilt.proposal.isNoteFirst, kind == .character,+ rebuilt.projected.target != .newRecord {+ Task { [weak self] in await self?.refreshRows() }+ } } /// Dismissing leaves undecided rows exactly where they are (Req 2.6): the@@ -266,12 +276,51 @@ final class CharacterReviewModel: Identifiable { defer { isSubmitting = false } disclosure = nil routesToCheckLibrary = false+ if row.proposal.isNoteFirst, row.kind == .character, row.projected.target != .newRecord {+ // A kind switch may race its automatic refresh. Neither Keep nor+ // Skip may turn that recognised character back into human approval.+ await refreshRows()+ return+ } // Q59: from the **projection**. Building it from the held row would send // a place decision the character kind's fact set.- let request = row.projected.decisionRequest(+ var request = row.projected.decisionRequest( workID: workID, action: action, struckAliases: row.struckAliases, untickedFacts: row.untickedFacts)+ request.reviewedKey = .init(kind: row.proposal.kind, nameKey: row.proposal.nameKey)+ request.reviewAcknowledgements = row.proposal.reviewAcknowledgements++ let remaining = rows.filter { other in+ guard other.id != row.id else { return false }+ if action == .skip, row.projected.returnedKinds.count > 1,+ other.proposal.nameKey == row.proposal.nameKey { return false }+ return true+ }+ // Another window or manual pass can settle a new held sibling after+ // this sheet's display snapshot. Consult only the current value ledger,+ // at this final preparation boundary, without rereading or model work.+ let remainingHeld = (currentHeld?() ?? []).filter { proposal in+ if proposal.key == row.key { return false }+ if action == .skip, request.nameKeySuppressedKinds.contains(proposal.kind),+ proposal.nameKey == row.proposal.nameKey { return false }+ return true+ }+ if row.proposal.isNoteFirst {+ // Guard every captured source, but certify only sources whose last+ // key is settling. Generic/standalone notes have no chapter marker.+ request.completedSources.removeAll { source in+ remaining.contains { $0.proposal.citedRevisions[source.ref] != nil }+ || remainingHeld.contains { $0.citedRevisions[source.ref] != nil }+ }+ } else {+ request.completedSources = request.completedSources.map { source in+ CompletedSource(ref: source.ref, fingerprint: source.fingerprint,+ mentionEligibilityDigest: remaining.contains(where: { $0.proposal.citedRevisions[source.ref] != nil })+ || remainingHeld.contains(where: { $0.citedRevisions[source.ref] != nil })+ ? nil : source.mentionEligibilityDigest)+ }+ } let outcome: DecisionOutcome do {@@ -358,6 +407,7 @@ final class CharacterReviewModel: Identifiable { "character review refresh could not re-read the work's records") } inputs.suppressedFacts = extractionContext()?.suppressedFacts ?? [:]+ inputs.mentionIndex = extractionContext()?.mentionIndex ?? .empty // Both kept per row, not per value: one row per proposal key per work // (Q83/Q100), and two rows proposing the same alias string — or the same // fact — are two decisions. Keyed globally, one row's strike travelled to@@ -415,6 +465,7 @@ final class CharacterReviewModel: Identifiable { private(set) var characters: [WorkRecordPresentation] private(set) var places: [WorkRecordPresentation] var captureOrder: [UUID: Int]+ var mentionIndex: AssociationMentionIndex var suppressedFacts: [RecordKind: Set<RecordFactIdentity>] /// The two reductions of a kind's presentations every row asks for,@@ -441,11 +492,13 @@ final class CharacterReviewModel: Identifiable { characters: [WorkRecordPresentation] = [], places: [WorkRecordPresentation] = [], captureOrder: [UUID: Int] = [:],- suppressedFacts: [RecordKind: Set<RecordFactIdentity>] = [:]+ suppressedFacts: [RecordKind: Set<RecordFactIdentity>] = [:],+ mentionIndex: AssociationMentionIndex = .empty ) { self.characters = characters self.places = places self.captureOrder = captureOrder+ self.mentionIndex = mentionIndex self.suppressedFacts = suppressedFacts derived = [.character: Derived(characters), .place: Derived(places)] }@@ -457,7 +510,7 @@ final class CharacterReviewModel: Identifiable { ) { self = ReviewInputs( characters: characters, places: places, captureOrder: captureOrder,- suppressedFacts: suppressedFacts)+ suppressedFacts: suppressedFacts, mentionIndex: mentionIndex) } func records(of kind: RecordKind) -> [WorkRecordPresentation] {@@ -541,7 +594,15 @@ final class CharacterReviewModel: Identifiable { var projected = proposal projected.displayedKind = kind projected.target = target.map { .existing($0.id) } ?? .newRecord- projected.facts = facts+ if proposal.isNoteFirst, kind == .character {+ switch RecordMatching.recognition(nameKey: proposal.nameKey,+ among: inputs.records(of: .character).map(ReviewInputs.matchTarget)) {+ case .noMatch: projected.target = .newRecord+ case .unique(let id): projected.target = .existing(id)+ case .ambiguous: projected.target = .unresolved+ }+ }+ projected.facts = proposal.isNoteFirst ? [] : facts return projected } @@ -557,10 +618,18 @@ final class CharacterReviewModel: Identifiable { // only a preview can move it back — including a merged row's, which the // ledger carried over from the older row (Q69). let isPristine = proposal.displayedKind == proposal.kind- let projected = isPristine && displayed == proposal.kind+ var projected = isPristine && displayed == proposal.kind ? proposal : project(proposal, to: displayed, inputs: inputs) + // A refusal refresh re-displays the target and its current narrow+ // decision basis together, including pristine retargeted rows.+ let displayedTarget: UUID? = if case .existing(let id) = projected.target { id } else { nil }+ projected.mentions = projected.mentions.compactMap {+ inputs.mentionIndex.refreshed($0, kind: displayed, recordID: displayedTarget,+ reconsider: proposal.isManual && !(proposal.isNoteFirst && displayed == .character && displayedTarget != nil))+ }+ let targetID: UUID? = if case .existing(let id) = projected.target { id } else { nil } let target = targetID.flatMap { id in inputs.records(of: displayed).first { $0.id == id } } let captureOrder = inputs.captureOrder@@ -581,6 +650,7 @@ final class CharacterReviewModel: Identifiable { isDualKind: proposal.isDualKind, crossKindHint: hint(for: proposal.nameKey, displayedAs: displayed, inputs: inputs), targetID: targetID,+ sourceEvidence: projected.sourceEvidence, aliases: proposal.proposedAliases.map { CharacterReviewAlias(name: $0, isStruck: false) },
diff --git a/Asterism/Asterism/ContentView.swift b/Asterism/Asterism/ContentView.swiftindex efa02278..9465b88c 100644--- a/Asterism/Asterism/ContentView.swift+++ b/Asterism/Asterism/ContentView.swift@@ -153,7 +153,7 @@ struct ContentView: View { // there rather than by remembering this line (Q51). for key in WorksListStorageKey.seededLaunchResets { if ProcessInfo.processInfo.environment["ASTERISM_UI_TEST_RESTORE_NAVIGATION"] == "1",- [RestoreStorageKey.selectedSidebarItem, RestoreStorageKey.todayPath, RestoreStorageKey.libraryPath].contains(key) { continue }+ [RestoreStorageKey.selectedSidebarItem, RestoreStorageKey.todayPath, RestoreStorageKey.libraryPath, RestoreStorageKey.selectedTab, RestoreStorageKey.selectedTodayEntryID, RestoreStorageKey.selectedWorkID].contains(key) { continue } UserDefaults.standard.removeObject(forKey: key) } // `launch-to-today` Q17: nil for every scenario but the one that@@ -755,6 +755,7 @@ struct ContentView: View { WorkDetailView( model: detailModel, currentDay: model.currentDay, calendar: model.calendar,+ snapshotGeneration: model.snapshotGeneration, // Q56's chapter-row route, on this sheet's own // stack: the rows are the same rows, so they open the // same screen rather than being dead here.
diff --git a/Asterism/Asterism/Layout/AppScreens.swift b/Asterism/Asterism/Layout/AppScreens.swiftindex 9349cce5..49d23131 100644--- a/Asterism/Asterism/Layout/AppScreens.swift+++ b/Asterism/Asterism/Layout/AppScreens.swift@@ -292,6 +292,7 @@ struct AppScreens { currentDay: model.currentDay, calendar: model.calendar, lastSavedLatestWorkID: navigation.lastSavedLatestWorkID, latestSaveGeneration: navigation.latestSaveGeneration,+ snapshotGeneration: model.snapshotGeneration, onResolveDuplicate: navigation.resolveRoute( for: workID, type: .work, workload: { model.todayPresentation.duplicateWorkload }),
diff --git a/Asterism/Asterism/Layout/EntryDetailRoute.swift b/Asterism/Asterism/Layout/EntryDetailRoute.swiftindex 6fc15343..6c11ae56 100644--- a/Asterism/Asterism/Layout/EntryDetailRoute.swift+++ b/Asterism/Asterism/Layout/EntryDetailRoute.swift@@ -55,7 +55,8 @@ struct EntryDetailRoute: View { // T-2301: the two signals are one fact about the host. A pushed // screen paints its own sky and is left after a landed update; // a column of a window does neither.- leavesAfterUpdate: showsSky+ leavesAfterUpdate: showsSky,+ snapshotGeneration: model.snapshotGeneration ) // See the note on the type: without this the wide tree's detail // column keeps the first entry's `@State` models forever.
diff --git a/Asterism/Asterism/Layout/SettingsScreen.swift b/Asterism/Asterism/Layout/SettingsScreen.swiftindex 4c32ff75..8a37a073 100644--- a/Asterism/Asterism/Layout/SettingsScreen.swift+++ b/Asterism/Asterism/Layout/SettingsScreen.swift@@ -83,6 +83,9 @@ struct SettingsScreen: View { }, workTypesModel: model.workTypesModel(), creatorRolesModel: model.creatorRolesModel(),+ detachedAssociationNotesModel: model.detachedAssociationNotesModel(),+ snapshotGeneration: model.snapshotGeneration,+ onAssociationNoteSaved: { await model.associationNoteSaved() }, // The preserved-capture surfaces. The sentences are the model's, // like every other notice here; what this view owns is where a // tapped entry goes.
diff --git a/Asterism/Asterism/Layout/WideRootView.swift b/Asterism/Asterism/Layout/WideRootView.swiftindex 3129523d..d0a9204a 100644--- a/Asterism/Asterism/Layout/WideRootView.swift+++ b/Asterism/Asterism/Layout/WideRootView.swift@@ -17,6 +17,7 @@ struct WideRootView: View { @AccessibilityFocusState private var inspectorFocused: Bool @FocusState private var inspectorKeyboardFocused: Bool @State private var inspectorCoverIsDrawn = false+ @State private var todayStackRevision = 0 @State private var sidebarSeries: [SeriesDisplay] = [] @State private var sidebarCreatorCount = 0 private var hubScreens: AppScreens { AppScreens(model: model, navigation: navigation, isWide: false, showSettings: showSettings, paintsOwnSky: false) }@@ -154,7 +155,8 @@ struct WideRootView: View { /// row's work, or a chapter inside it — so Req 8.1's announcement and focus /// move fire for a release row exactly as they do for a note. private var todayPane: some View {- NavigationStack(path: $navigation.todayPath) {+ let ownerRevision = todayStackRevision+ return NavigationStack(path: $navigation.todayPath) { screens.today(onShowSettings: showsSettingsRow && navigation.sidebarVisibility == .detailOnly ? showSettings : nil) .sidebarToggleToolbar(navigation: navigation, enabled: !(showsSettingsRow && navigation.sidebarVisibility == .detailOnly)) .toolbar {@@ -165,18 +167,35 @@ struct WideRootView: View { .navigationDestination(for: WorksRoute.self) { route in screens.route(route, on: .today).columnSky() }- .navigationDestination(item: $navigation.selectedTodayEntryID) { id in+ .navigationDestination(item: TodayStackItemBinding.owned(+ $navigation.selectedTodayEntryID,+ ownerRevision: ownerRevision,+ currentRevision: { todayStackRevision })) { id in EntryDetailRoute(model: model, navigation: navigation, entryID: id, showsSky: false) .columnSky() } .navigationDestination(isPresented: $navigation.showingDiagnostics) { screens.diagnostics().columnSky() } .columnSky()+ // Hosting the inspector on the dashboard keeps a popped chapter+ // reopenable without replacing the navigation owner or path.+ // A retired presenter cannot dismiss a later stack's selection.+ .macInspector(isPresented: TodayStackItemBinding.presentation(+ TodayStackItemBinding.owned(+ $navigation.todayInspectorEntryID,+ ownerRevision: ownerRevision,+ currentRevision: { todayStackRevision }))) {+ todayInspector+ .environment(\.thumbnailLoader, model.thumbnailLoader)+ .inspectorColumnWidth(min: 340, ideal: 380, max: 440)+ }+ }+ // Keep forward navigation on the same stack. Rebuild only after a+ // final return to the dashboard, retaining the stale-controller reset.+ .id(todayStackRevision)+ .onChange(of: navigation.todayPath.isEmpty && navigation.selectedTodayEntryID == nil) { wasDashboard, isDashboard in+ if !wasDashboard && isDashboard { todayStackRevision &+= 1 } }- // The split-view detail retains its pushed controller after an inspector- // closes, even when its bound path returns to empty. Give the dashboard- // and a pushed page separate stack identities; nested pushes keep theirs.- .id(navigation.todayPath.isEmpty && navigation.selectedTodayEntryID == nil)- .inspector(isPresented: Binding(get: { navigation.todayInspectorEntryID != nil }, set: { if !$0 { navigation.todayInspectorEntryID = nil } })) {+ .nonMacInspector(isPresented: Binding(get: { navigation.todayInspectorEntryID != nil }, set: { if !$0 { navigation.todayInspectorEntryID = nil } })) { todayInspector .environment(\.thumbnailLoader, model.thumbnailLoader) .inspectorColumnWidth(min: 340, ideal: 380, max: 440)@@ -519,3 +538,28 @@ private struct InspectorCharacters: View { }.task { await model.load() } } }++/// A destroyed Today stack may not clear selection owned by a later stack.+/// The owner is captured once; the shared revision is read when the callback+/// arrives. Getter and all other writes retain the original binding semantics.+@MainActor+internal enum TodayStackItemBinding {+ static func owned(+ _ original: Binding<UUID?>,+ ownerRevision: Int,+ currentRevision: @escaping @MainActor @Sendable () -> Int+ ) -> Binding<UUID?> {+ Binding(get: { original.wrappedValue }, set: { value, transaction in+ if value == nil && currentRevision() != ownerRevision { return }+ original.transaction(transaction).wrappedValue = value+ })+ }++ /// Inspector presentation writes dismiss a selection; opening never invents one.+ static func presentation(_ selection: Binding<UUID?>) -> Binding<Bool> {+ Binding(get: { selection.wrappedValue != nil }, set: { presented, transaction in+ guard !presented else { return }+ selection.transaction(transaction).wrappedValue = nil+ })+ }+}
diff --git a/Asterism/Asterism/Localizable.xcstrings b/Asterism/Asterism/Localizable.xcstringsindex 615c5c47..fec210b1 100644--- a/Asterism/Asterism/Localizable.xcstrings+++ b/Asterism/Asterism/Localizable.xcstrings@@ -64,6 +64,18 @@ } } },+ "%@ · %@ · %@" : {+ "comment" : "A record copy preview row. The first argument is the record's name. The second argument is the record's type. The third argument is whether the record will be copied or skipped.",+ "isCommentAutoGenerated" : true,+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "new",+ "value" : "%1$@ · %2$@ · %3$@"+ }+ }+ }+ }, "%@ — %@" : { "comment" : "A subheading that displays the number of times a sync failure was observed, followed by the detail of the failure. The first argument is the count of times the failure was observed. The second argument is the detail of the failure.", "isCommentAutoGenerated" : true,@@ -100,14 +112,14 @@ } } },- "%@, %@ citing this note" : {- "comment" : "A label that describes the name of a character or place and the number of times it cites a note. The first argument is the name of the character or place. The second argument is the number of times it cites the note.",+ "%@, %@ referencing this note" : {+ "comment" : "A label that describes the name of a place or character and the number of times it is referenced in the note. The first argument is the name of the place or character. The second argument is the name of the place or character.", "isCommentAutoGenerated" : true, "localizations" : { "en" : { "stringUnit" : { "state" : "new",- "value" : "%1$@, %2$@ citing this note"+ "value" : "%1$@, %2$@ referencing this note" } } }@@ -124,6 +136,30 @@ } } },+ "%@, %@, %@%@" : {+ "comment" : "A label describing a record in a record copy view. The first argument is the record's name. The second argument is the record's type (e.g., \"person\", \"location\", \"work\"). The third argument is whether the record is selected. The fourth argument is the record's unavailable reason, if any.",+ "isCommentAutoGenerated" : true,+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "new",+ "value" : "%1$@, %2$@, %3$@%4$@"+ }+ }+ }+ },+ "%@, %@, chapter link note" : {+ "comment" : "A label that describes the chapter link note for a chapter. The first argument is the name of the chapter. The second argument is the record kind (`pair.kind`).",+ "isCommentAutoGenerated" : true,+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "new",+ "value" : "%1$@, %2$@, chapter link note"+ }+ }+ }+ }, "%@, %@, from %@" : { "comment" : "A sentence that describes a work, including its title, the line it's on, and the site it's on.", "isCommentAutoGenerated" : true,@@ -136,14 +172,14 @@ } } },- "%@, %lld facts" : {- "comment" : "A label that describes the pill's name and",+ "%@, %@, position %@, %@" : {+ "comment" : "A label describing a source of a record copy offer. The first argument is the work's title. The second argument is the series label. The third argument is the series position. The fourth argument is whether the source is the selected source.", "isCommentAutoGenerated" : true, "localizations" : { "en" : { "stringUnit" : { "state" : "new",- "value" : "%1$@, %2$lld facts"+ "value" : "%1$@, %2$@, position %3$@, %4$@" } } }@@ -238,6 +274,18 @@ } } },+ "%lld copied, %lld skipped in %@." : {+ "comment" : "A message that appears in a sheet that is presented after a record copy operation. The first argument is the number of records that were copied. The second argument is the number of records that were skipped. The third argument is the name of the destination work.",+ "isCommentAutoGenerated" : true,+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "new",+ "value" : "%1$lld copied, %2$lld skipped in %3$@."+ }+ }+ }+ }, "%lld entries after merge" : { },@@ -398,6 +446,10 @@ "comment" : "The title of the intent.", "isCommentAutoGenerated" : true },+ "Add note" : {+ "comment" : "A button label for adding a note to a chapter link.",+ "isCommentAutoGenerated" : true+ }, "Add the role %@" : { "comment" : "A label for a pill button that lets the user add or remove a role from a credit. The argument is the role's label.", "isCommentAutoGenerated" : true@@ -414,16 +466,8 @@ "comment" : "Description of the AddPageToReadIntent intent.", "isCommentAutoGenerated" : true },- "Adds to a %@ you already have." : {- "comment" : "A note that a bundle adds to a character",- "isCommentAutoGenerated" : true- }, "After" : { - },- "Already kept (%lld)" : {- "comment" : "A group of facts that are already in the",- "isCommentAutoGenerated" : true }, "Already resolved" : { @@ -482,6 +526,10 @@ "comment" : "The label of a button that cancels a cover candidate sheet.", "isCommentAutoGenerated" : true },+ "Cancel this preview and open Check Library from the main library to resolve unavailable records." : {+ "comment" : "A description of the action to take when the user is unable to copy records.",+ "isCommentAutoGenerated" : true+ }, "Cannot apply teaching" : { },@@ -489,6 +537,14 @@ "comment" : "A heading for the details of a capture.", "isCommentAutoGenerated" : true },+ "Captured saved note" : {+ "comment" : "A description of a saved source that is not a chapter.",+ "isCommentAutoGenerated" : true+ },+ "Captured source unavailable" : {+ "comment" : "A message displayed when a source's text is unavailable.",+ "isCommentAutoGenerated" : true+ }, "Change status" : { "comment" : "The title of a sheet that allows a user to change the status of a work.", "isCommentAutoGenerated" : true@@ -500,6 +556,9 @@ "Change title" : { "comment" : "Choice to change the title of the page.", "isCommentAutoGenerated" : true+ },+ "Changes after combine" : {+ }, "Chapter" : { "comment" : "The name of the chapter field in a note.",@@ -509,19 +568,42 @@ "comment" : "A label for the provenance of the chapter.", "isCommentAutoGenerated" : true },+ "Chapter designation (optional)" : {+ "comment" : "A label for the chapter designation field in the entry correction form.",+ "isCommentAutoGenerated" : true+ },+ "Chapter link note" : {+ "comment" : "The title of a screen that allows a user to edit a note for a chapter link.",+ "isCommentAutoGenerated" : true+ },+ "Chapter refresh interrupted" : {+ "comment" : "A message that appears when chapter refresh fails.",+ "isCommentAutoGenerated" : true+ }, "Chapter will be named" : { "comment" : "A label for the chapter name preview.", "isCommentAutoGenerated" : true }, "Chapter: manual protection (preserved)" : { + },+ "Chapters (%lld)" : {+ "comment" : "A label showing the number of chapters in a record. The argument is the number of chapters.",+ "isCommentAutoGenerated" : true }, "Chapters Releasing Today" : { "comment" : "Title of the \"Which chapters release today?\" intent.", "isCommentAutoGenerated" : true },+ "Chapters could not be loaded." : {+ "comment" : "A message displayed when a user can't load a list of chapters.",+ "isCommentAutoGenerated" : true+ }, "Chapters will stay unsettled" : { + },+ "Chapters · review needed" : {+ }, "Check Library" : { "comment" : "A button that opens a screen to check the library.",@@ -535,10 +617,18 @@ "comment" : "A button that asks whether a", "isCommentAutoGenerated" : true },+ "Checking whether copying completed…" : {+ "comment" : "A message that appears while the system checks whether the copy operation has completed.",+ "isCommentAutoGenerated" : true+ }, "Checking your library…" : { "comment" : "A loading message for the library diagnostics view.", "isCommentAutoGenerated" : true },+ "Choose an earlier source to review" : {+ "comment" : "A button that opens a view for selecting an earlier source to review.",+ "isCommentAutoGenerated" : true+ }, "Choose file…" : { },@@ -546,6 +636,14 @@ "comment" : "A button that opens a system-provided photo picker.", "isCommentAutoGenerated" : true },+ "Choose the note and rating to keep" : {+ "comment" : "A section in the entry correction view that allows the user to choose which note and rating to keep when correcting an entry.",+ "isCommentAutoGenerated" : true+ },+ "Choose…" : {+ "comment" : "A placeholder text for a picker view.",+ "isCommentAutoGenerated" : true+ }, "Clear" : { "comment" : "The label of a button that clears a suggestion.", "isCommentAutoGenerated" : true@@ -558,6 +656,10 @@ "comment" : "A button that clears the selection of a URL's components.", "isCommentAutoGenerated" : true },+ "Clear note" : {+ "comment" : "A button that clears the note for a chapter link.",+ "isCommentAutoGenerated" : true+ }, "Clear search" : { "comment" : "A button that clears the search field.", "isCommentAutoGenerated" : true@@ -586,9 +688,41 @@ }, "Confirm merge into %@" : { + },+ "Content" : {+ "comment" : "A section of the record copy view that displays the user's ability to include notes.",+ "isCommentAutoGenerated" : true }, "Continue" : { + },+ "Copied characters and places" : {+ "comment" : "The title of a dialog that appears when a record is copied.",+ "isCommentAutoGenerated" : true+ },+ "Copy %lld" : {+ "comment" : "A button that copies the selected characters and places. The argument is the count of selected items.",+ "isCommentAutoGenerated" : true+ },+ "Copy characters and places" : {+ "comment" : "A title for the screen that lets the user choose which characters and places to copy from a record.",+ "isCommentAutoGenerated" : true+ },+ "Copy draft" : {+ "comment" : "A button that copies the draft text of a note to the clipboard.",+ "isCommentAutoGenerated" : true+ },+ "Copy text" : {+ "comment" : "A button that copies the text of a detached chapter link note to the clipboard.",+ "isCommentAutoGenerated" : true+ },+ "Copy this record" : {+ "comment" : "A button that either skips or copies a record.",+ "isCommentAutoGenerated" : true+ },+ "Correct entry" : {+ "comment" : "A title for a screen that allows a user to correct an entry.",+ "isCommentAutoGenerated" : true }, "Could not load the copies" : { @@ -621,6 +755,10 @@ "comment" : "The button to create a new role.", "isCommentAutoGenerated" : true },+ "Create a separate chapter" : {+ "comment" : "A toggle that allows users to create a separate chapter if they're creating a chapter.",+ "isCommentAutoGenerated" : true+ }, "Create the creator %@ and credit them" : { "comment" : "A button that creates a new creator and adds them to the list of creators. The argument is the creator's name.", "isCommentAutoGenerated" : true@@ -722,11 +860,23 @@ }, "Delete work, keep its notes" : { + },+ "Destination" : {+ "comment" : "A section header for the list of possible destinations for a work record copy.",+ "isCommentAutoGenerated" : true+ },+ "Detached link notes" : {+ "comment" : "A title for a list of notes that are not attached to a chapter link.",+ "isCommentAutoGenerated" : true }, "Differing copies" : { "comment" : "A label that indicates that the record has been split", "isCommentAutoGenerated" : true },+ "Discard copy review" : {+ "comment" : "A button that discards the copy review flow.",+ "isCommentAutoGenerated" : true+ }, "Discard the new order" : { "comment" : "A button that discards the user's changes to the order.", "isCommentAutoGenerated" : true@@ -743,10 +893,18 @@ "comment" : "A hint for the crop step.", "isCommentAutoGenerated" : true },+ "Earlier work" : {+ "comment" : "A section that lists the earlier works that the user can review.",+ "isCommentAutoGenerated" : true+ }, "Edit" : { "comment" : "A button that starts editing the reading order of a series.", "isCommentAutoGenerated" : true },+ "Edit link note" : {+ "comment" : "A button that opens a sheet for editing a link note.",+ "isCommentAutoGenerated" : true+ }, "Edit this creator" : { "comment" : "A button that opens a screen for editing a creator.", "isCommentAutoGenerated" : true@@ -771,6 +929,14 @@ "comment" : "A label for the number of entries evaluated in the review.", "isCommentAutoGenerated" : true },+ "Entry" : {+ "comment" : "A label for the entry type picker in the manual entry view.",+ "isCommentAutoGenerated" : true+ },+ "Entry kind" : {+ "comment" : "A label for the kind of entry being corrected.",+ "isCommentAutoGenerated" : true+ }, "Entry note" : { },@@ -786,6 +952,20 @@ "comment" : "A label for the example URL in the URL details editor.", "isCommentAutoGenerated" : true },+ "Existing %@: %@" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "new",+ "value" : "Existing %1$@: %2$@"+ }+ }+ }+ },+ "Existing chapter" : {+ "comment" : "A caption displayed underneath the name of a chapter",+ "isCommentAutoGenerated" : true+ }, "Export" : { },@@ -808,6 +988,10 @@ "comment" : "A subheading displaying the date and time of the backup's export.", "isCommentAutoGenerated" : true },+ "Facts, quotes and citations, extraction coverage and suppression decisions are not copied. Entries, work notes, ratings, progress and other work details stay where they are." : {+ "comment" : "A description of the content that is not copied when copying a record.",+ "isCommentAutoGenerated" : true+ }, "Find" : { "comment" : "The label of a button that opens a find panel.", "isCommentAutoGenerated" : true@@ -824,6 +1008,10 @@ "comment" : "Description of the Find Works intent.", "isCommentAutoGenerated" : true },+ "From" : {+ "comment" : "A heading for the source record.",+ "isCommentAutoGenerated" : true+ }, "Genre tags (comma-separated)" : { },@@ -849,6 +1037,13 @@ "How these two works are related — “adaptation”, “sequel”, anything you like." : { "comment" : "A description of what the user can enter in the", "isCommentAutoGenerated" : true+ },+ "I understand; allow retry" : {+ "comment" : "A button that lets the user retry the copy process.",+ "isCommentAutoGenerated" : true+ },+ "ID: %@" : {+ }, "Import" : { "comment" : "The label of a button that imports a backup.",@@ -869,12 +1064,40 @@ "comment" : "A label displayed while the backup is being imported.", "isCommentAutoGenerated" : true },+ "Include record notes" : {+ "comment" : "A toggle that allows the user to include notes from the record being copied.",+ "isCommentAutoGenerated" : true+ }, "Increase latest chapter" : { "comment" : "A button that increases the latest chapter number.", "isCommentAutoGenerated" : true },+ "Informational saved context" : {+ "comment" : "A description of a saved source that is not a decision basis.",+ "isCommentAutoGenerated" : true+ }, "Keep" : { + },+ "Keep content" : {+ "comment" : "A label for choosing which content to keep when correcting an entry.",+ "isCommentAutoGenerated" : true+ },+ "Keep my draft" : {+ "comment" : "A button that keeps the user's draft entry when choosing to keep the content of an existing entry.",+ "isCommentAutoGenerated" : true+ },+ "Keep selected entry content" : {+ "comment" : "A button that keeps the content of the selected entry when adding a new note.",+ "isCommentAutoGenerated" : true+ },+ "Keep separate" : {+ "comment" : "A label for a picker item that lets the user choose to keep the new entry in a separate chapter.",+ "isCommentAutoGenerated" : true+ },+ "Keep separate?" : {+ "comment" : "A confirmation dialog for keeping separate records for matching names.",+ "isCommentAutoGenerated" : true }, "Keep the other notes too" : { "comment" : "A toggle that lets the user decide whether to keep the notes of the other variants.",@@ -922,6 +1145,10 @@ }, "Link" : { + },+ "Link note information needs review" : {+ "comment" : "A message displayed when a link note's metadata needs review.",+ "isCommentAutoGenerated" : true }, "Link to %@" : { "comment" : "The title of the view.",@@ -939,6 +1166,10 @@ "comment" : "Description of the intent that lists the works in the library with a chapter expected today.", "isCommentAutoGenerated" : true },+ "Loading chapters…" : {+ "comment" : "A placeholder text that appears when loading chapters.",+ "isCommentAutoGenerated" : true+ }, "Loading copies…" : { "comment" : "The loading text for the duplicate resolution sheet.", "isCommentAutoGenerated" : true@@ -959,6 +1190,10 @@ "comment" : "The text that appears when the review is loading.", "isCommentAutoGenerated" : true },+ "Loading skipped links…" : {+ "comment" : "A placeholder text that appears while loading skipped character links.",+ "isCommentAutoGenerated" : true+ }, "Loading works…" : { "comment" : "A loading message for the works.", "isCommentAutoGenerated" : true@@ -1032,11 +1267,27 @@ }, "Multiple Works match the parsed title. Assignment will remain unresolved." : { + },+ "Multiple chapters" : {+ "comment" : "A description of a work that can have multiple chapters.",+ "isCommentAutoGenerated" : true+ },+ "Multiple link notes" : {+ "comment" : "A caption displayed under a record history row if the record has multiple link notes.",+ "isCommentAutoGenerated" : true+ },+ "Multiple saved notes" : {+ "comment" : "A description of a note that has been saved more than once.",+ "isCommentAutoGenerated" : true }, "Name" : { "comment" : "A label for the character's name.", "isCommentAutoGenerated" : true },+ "Names and explicit aliases are copied. Earlier names travel only when listed as aliases." : {+ "comment" : "A description of how names and aliases are handled when copying records.",+ "isCommentAutoGenerated" : true+ }, "New Series" : { "comment" : "The button that adds a new series.", "isCommentAutoGenerated" : true@@ -1057,6 +1308,10 @@ "comment" : "A row that lets the user create a new creator. The argument is the creator's name.", "isCommentAutoGenerated" : true },+ "New entry" : {+ "comment" : "A label for a button that creates a new entry.",+ "isCommentAutoGenerated" : true+ }, "New role" : { "comment" : "A button that adds a new role to the user's list.", "isCommentAutoGenerated" : true@@ -1103,6 +1358,17 @@ "comment" : "A label that describes a conflict-free review.", "isCommentAutoGenerated" : true },+ "No currently available records were found for this diagnosis. The unresolved count has not been changed." : {++ },+ "No link note" : {+ "comment" : "A description of a note that has been cleared.",+ "isCommentAutoGenerated" : true+ },+ "No linked chapters" : {+ "comment" : "A message displayed when a record has no linked chapters.",+ "isCommentAutoGenerated" : true+ }, "No matching works" : { "comment" : "A description for the empty state when the search query has no matches.", "isCommentAutoGenerated" : true@@ -1118,6 +1384,10 @@ "comment" : "A label that says there are no suggestions available for a work.", "isCommentAutoGenerated" : true },+ "No supported skipped character links" : {+ "comment" : "A message displayed when a user has no skipped character links.",+ "isCommentAutoGenerated" : true+ }, "No unattached notes" : { "comment" : "A label displayed when a user has no unattached notes.", "isCommentAutoGenerated" : true@@ -1145,6 +1415,10 @@ "comment" : "A button that lets the user dismiss a Work that is not the same as another Work. The argument is the title of the Work that the user is dismissing.", "isCommentAutoGenerated" : true },+ "Not now" : {+ "comment" : "A button that dismisses a record copy offer without saving the work.",+ "isCommentAutoGenerated" : true+ }, "Not yet" : { "comment" : "A button that moves a work to the reading section of the library.", "isCommentAutoGenerated" : true@@ -1154,6 +1428,10 @@ }, "Note" : { + },+ "Note for this chapter link" : {+ "comment" : "A heading for the note section of a chapter link.",+ "isCommentAutoGenerated" : true }, "Noted today" : { "comment" : "A label for a checkmark in a list item.",@@ -1193,6 +1471,10 @@ "comment" : "The label of a button that dismisses an alert.", "isCommentAutoGenerated" : true },+ "One chapter" : {+ "comment" : "A description of a single chapter of a work.",+ "isCommentAutoGenerated" : true+ }, "Open ${work}" : { },@@ -1220,10 +1502,18 @@ "comment" : "The label of a button that opens a web page.", "isCommentAutoGenerated" : true },+ "Open chapter" : {+ "comment" : "A button that opens a chapter in a record history row.",+ "isCommentAutoGenerated" : true+ }, "Open chapter ↗" : { "comment" : "A button that opens a chapter in a web browser.", "isCommentAutoGenerated" : true },+ "Open destination" : {+ "comment" : "A button that opens the destination work.",+ "isCommentAutoGenerated" : true+ }, "Open entry %@ from %@" : { "comment" : "A sentence that describes the action to take to open the entry. The first argument is the entry's accessibility title. The second argument is the site name.", "isCommentAutoGenerated" : true,@@ -1275,7 +1565,7 @@ "comment" : "Intent description for opening a work in Asterism.", "isCommentAutoGenerated" : true },- "Opens this %@'s name, aliases and facts" : {+ "Opens this %@'s name, aliases and note" : { "comment" : "A hint for a line in the edit session's collection.", "isCommentAutoGenerated" : true },@@ -1291,6 +1581,10 @@ "comment" : "A label for the outcome of a work.", "isCommentAutoGenerated" : true },+ "Pages usually contain" : {+ "comment" : "A label for a picker that lets the user choose how",+ "isCommentAutoGenerated" : true+ }, "Path components" : { "comment" : "A heading for the path components of a URL.", "isCommentAutoGenerated" : true@@ -1307,6 +1601,10 @@ "comment" : "A label for the position of a member in a series.", "isCommentAutoGenerated" : true },+ "Position %@ has more than one earlier work. Choose the source deliberately, including when only one is currently available." : {+ "comment" : "A description of a section of the review interface that lets the user choose which of several earlier works to use as a source for a new work.",+ "isCommentAutoGenerated" : true+ }, "Position in the series" : { "comment" : "A label for the position of a series in a work.", "isCommentAutoGenerated" : true@@ -1327,6 +1625,18 @@ "comment" : "A description of the backup process.", "isCommentAutoGenerated" : true },+ "Preparing copies…" : {+ "comment" : "A label that appears while the system is preparing copies.",+ "isCommentAutoGenerated" : true+ },+ "Preparing notes export" : {+ "comment" : "The text that appears when the system is busy preparing",+ "isCommentAutoGenerated" : true+ },+ "Preview" : {+ "comment" : "A section header for the preview of the records that will be copied.",+ "isCommentAutoGenerated" : true+ }, "Preview (%lld entries)" : { "comment" : "A section header for the preview of a composed rule.", "isCommentAutoGenerated" : true@@ -1358,6 +1668,10 @@ "comment" : "A label for a button that rates up something.", "isCommentAutoGenerated" : true },+ "Rating: %@" : {+ "comment" : "A subheading that appears in a section of the entry correction view, showing the rating for the entry being edited.",+ "isCommentAutoGenerated" : true+ }, "Re-parse" : { "comment" : "A button that triggers a re-parsing of the title.", "isCommentAutoGenerated" : true@@ -1430,6 +1744,22 @@ "comment" : "A button that reconfirms a re-parse.", "isCommentAutoGenerated" : true },+ "Record note" : {+ "comment" : "A label for the note of a record.",+ "isCommentAutoGenerated" : true+ },+ "Recover to this chapter link" : {+ "comment" : "A button that allows a user to recover a note to a chapter link.",+ "isCommentAutoGenerated" : true+ },+ "Refresh choices and preview" : {+ "comment" : "A button that refreshes the list of records to copy and the preview of the changes.",+ "isCommentAutoGenerated" : true+ },+ "Refreshing saved series order…" : {+ "comment" : "A message that appears when the user is reading a record copy offer.",+ "isCommentAutoGenerated" : true+ }, "Refused: %@" : { "comment" : "A button that dismisses the drain report.", "isCommentAutoGenerated" : true@@ -1545,8 +1875,24 @@ } } },+ "Restore link" : {+ "comment" : "A button that restores a skipped character link.",+ "isCommentAutoGenerated" : true+ },+ "Restore only a supported character link for this saved chapter. Detached link notes remain separate." : {+ "comment" : "A description of the skipped character links feature.",+ "isCommentAutoGenerated" : true+ },+ "Resume copy review" : {+ "comment" : "A button that resumes a copy review.",+ "isCommentAutoGenerated" : true+ }, "Retry" : { + },+ "Retry outcome check" : {+ "comment" : "A button that triggers a retry of the outcome check for the record copy process.",+ "isCommentAutoGenerated" : true }, "Returns %@" : { @@ -1558,12 +1904,59 @@ "comment" : "A label for a button that opens a sheet for", "isCommentAutoGenerated" : true },+ "Review addition %@, %@, position %@" : {+ "comment" : "A description of a review of a saved addition. The first argument is the work title. The second argument is the series label. The third argument is the series position.",+ "isCommentAutoGenerated" : true,+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "new",+ "value" : "Review addition %1$@, %2$@, position %3$@"+ }+ }+ }+ },+ "Review again" : {+ "comment" : "A button that triggers a new review of the destination entry.",+ "isCommentAutoGenerated" : true+ },+ "Review changes" : {++ },+ "Review characters and places" : {+ "comment" : "A screen that allows the user to review the characters and places of a work.",+ "isCommentAutoGenerated" : true+ },+ "Review characters and places from %@" : {+ "comment" : "A button that opens a new view for reviewing characters and places.",+ "isCommentAutoGenerated" : true+ },+ "Review latest links" : {+ "comment" : "A button that reloads the list of skipped character links.",+ "isCommentAutoGenerated" : true+ },+ "Review latest saved note" : {+ "comment" : "A button that reloads the note from the server and displays it.",+ "isCommentAutoGenerated" : true+ },+ "Review one added work. Closing this review dismisses the offer for the whole batch; the other additions remain available through Copy characters and places on a work." : {+ "comment" : "A description of the review of a single work in a batch of works.",+ "isCommentAutoGenerated" : true+ },+ "Review opens ordinary copying with no records selected. Nothing is copied until its final Copy button." : {+ "comment" : "A description of the review process for a record copy offer.",+ "isCommentAutoGenerated" : true+ }, "Review suggestions" : { "comment" : "The label of a button that opens a screen to review", "isCommentAutoGenerated" : true }, "Review unavailable" : { + },+ "Reviewing this addition" : {+ "comment" : "A label that appears when a user is reviewing a saved addition.",+ "isCommentAutoGenerated" : true }, "Role name" : { "comment" : "A label for the role's name field.",@@ -1585,8 +1978,40 @@ "comment" : "A button that saves changes to a creator.", "isCommentAutoGenerated" : true },+ "Save a related-work link or shared series membership first. Copying does not create relationships." : {+ "comment" : "A description of the destination section of the work record copy view.",+ "isCommentAutoGenerated" : true+ }, "Save the new order" : { + },+ "Saved additions" : {+ "comment" : "A section of the record copy offer that lists the user's saved additions.",+ "isCommentAutoGenerated" : true+ },+ "Saved chapter note" : {+ "comment" : "A heading for the saved chapter note of a record history row.",+ "isCommentAutoGenerated" : true+ },+ "Saved in %@ at %@" : {+ "comment" : "A footnote that describes the series and position of the saved addition.",+ "isCommentAutoGenerated" : true,+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "new",+ "value" : "Saved in %1$@ at %2$@"+ }+ }+ }+ },+ "Saved notes" : {+ "comment" : "A section header for saved notes.",+ "isCommentAutoGenerated" : true+ },+ "Saved sources (%lld)" : {+ "comment" : "A heading that lists the sources that have been saved for a given proposal. The argument is the number of saved sources.",+ "isCommentAutoGenerated" : true }, "Saving…" : { "comment" : "The text that appears while the user is saving a",@@ -1612,8 +2037,28 @@ "comment" : "A button that shows all the work the user is behind on.", "isCommentAutoGenerated" : true },+ "Select all %@" : {+ "comment" : "A button that selects all of the specified records.",+ "isCommentAutoGenerated" : true+ }, "Select for" : { + },+ "Selected destination" : {+ "comment" : "A label that indicates a destination is selected.",+ "isCommentAutoGenerated" : true+ },+ "Selected entry unavailable — choose again" : {+ "comment" : "A message displayed when the selected entry is unavailable.",+ "isCommentAutoGenerated" : true+ },+ "Selected entry: %@" : {+ "comment" : "A label describing the selected entry in the manual entry view. The argument is the note of the selected entry.",+ "isCommentAutoGenerated" : true+ },+ "Selected source" : {+ "comment" : "A label that indicates a source has been selected.",+ "isCommentAutoGenerated" : true }, "Series" : { "comment" : "The title of the screen.",@@ -1657,11 +2102,23 @@ }, "Shared" : { + },+ "Show 20 more (%lld remaining)" : {+ "comment" : "A button that shows 20 more chapters. The argument is the number of remaining chapters.",+ "isCommentAutoGenerated" : true }, "Show a Period" : { "comment" : "The title of a sheet that lets the user select a period.", "isCommentAutoGenerated" : true },+ "Show chapters" : {+ "comment" : "A button that shows chapters for a record.",+ "isCommentAutoGenerated" : true+ },+ "Show more sources (%lld remaining)" : {+ "comment" : "A button that shows more saved sources. The argument is the number of additional sources to show.",+ "isCommentAutoGenerated" : true+ }, "Sidebar" : { "comment" : "A label for the accessibility value of the sidebar toggle button.", "isCommentAutoGenerated" : true@@ -1670,7 +2127,7 @@ "comment" : "A label for the site name and hostname.", "isCommentAutoGenerated" : true },- "Site or URL" : {+ "Site or URL (optional)" : { "comment" : "A label for a text field that lets the user enter a website or URL.", "isCommentAutoGenerated" : true },@@ -1686,6 +2143,18 @@ "comment" : "The button text for skipping a Work's URL. The argument is the title of the Work.", "isCommentAutoGenerated" : true },+ "Skip this record" : {+ "comment" : "A button that either skips or copies a record.",+ "isCommentAutoGenerated" : true+ },+ "Skipped character links" : {+ "comment" : "A button that shows a list of skipped character links.",+ "isCommentAutoGenerated" : true+ },+ "Some chapter or record information is unavailable or needs review. Detached link notes remain in Settings." : {+ "comment" : "A description of the text that appears when a record's chapters are unavailable.",+ "isCommentAutoGenerated" : true+ }, "Some of these notes have copies that differ" : { },@@ -1695,6 +2164,9 @@ "Sort" : { "comment" : "A sort option for a group of works.", "isCommentAutoGenerated" : true+ },+ "Source URL (optional)" : {+ }, "Split %@ into parts" : { "comment" : "A button that splits a chip into two or more parts. The argument is the name of the chip.",@@ -1738,6 +2210,14 @@ "comment" : "A label that indicates a suggestion.", "isCommentAutoGenerated" : true },+ "Supported spelling: %@" : {+ "comment" : "A label that lists the spelling of a word in a source. The argument is the spelling of the word.",+ "isCommentAutoGenerated" : true+ },+ "Supported spellings: %@" : {+ "comment" : "A list of the spelling keys for a skipped character link. The list is separated by commas.",+ "isCommentAutoGenerated" : true+ }, "Tap a part to change what it supplies. Whole segments cope with changing titles better than parts do." : { },@@ -1822,8 +2302,17 @@ "The series is created straight away and stays even if you cancel this edit." : { },- "Their facts and names move across. Nothing is written until you tap the checkmark." : {-+ "Their names and saved details move across. Nothing is written until you tap the checkmark." : {+ "comment" : "A message in the dialog that appears when the user",+ "isCommentAutoGenerated" : true+ },+ "There are no detached chapter link notes." : {+ "comment" : "A message displayed when a user has no detached chapter link notes.",+ "isCommentAutoGenerated" : true+ },+ "These matching names may represent different records. Existing records will stay unchanged. Future extracted facts can route to either same-name record according to the existing matching rules." : {+ "comment" : "A message that appears when the user is prompted to choose between keeping a record and creating a new one.",+ "isCommentAutoGenerated" : true }, "This backup holds %lld entries and %lld works. Your library currently holds %lld entries and %lld works. Nothing will be deleted." : { "comment" : "A description of the backup and the user's library. The first argument is the number of entries in the backup. The second argument is the number of works in the backup. The third argument is the number of entries in the user's library. The fourth argument is the number of works in the user's library.",@@ -1844,18 +2333,29 @@ "comment" : "A message that appears when a document cannot be", "isCommentAutoGenerated" : true },+ "This entry" : {+ "comment" : "A label for the entry being edited",+ "isCommentAutoGenerated" : true+ }, "This entry arrived %lld times and the copies differ." : { "comment" : "A notice that an entry has been found multiple times, but the copies are different. The argument is the number of times the entry has been found.", "isCommentAutoGenerated" : true }, "This entry has copies that differ" : { + },+ "This entry received changes after it was combined. Review its note and rating before using it as a chapter." : {+ }, "This rule has no text before or after the split, so anything in this component would be read as a Work. Include the surrounding text in the rule to allow it." : { }, "This series is no longer in your library." : { + },+ "This text remains available to copy. Its chapter link needs review before recovery." : {+ "comment" : "A description of a note that cannot be recovered.",+ "isCommentAutoGenerated" : true }, "This title names the Work but does not identify a chapter, and no chapter comes from the URL. Add URL details to source the chapter, or teach anyway and leave chapters unsettled." : { "comment" : "A description of the warning that appears when the",@@ -1873,6 +2373,10 @@ "comment" : "The label for the title field in the New Work form.", "isCommentAutoGenerated" : true },+ "Title (optional)" : {+ "comment" : "A label for the title of an entry correction.",+ "isCommentAutoGenerated" : true+ }, "To Read" : { },@@ -1891,6 +2395,9 @@ "Try Again" : { "comment" : "A button that retries teaching after a failure.", "isCommentAutoGenerated" : true+ },+ "Try again" : {+ }, "Type" : { "comment" : "A picker that lets the user choose a work's type.",@@ -1908,8 +2415,16 @@ "comment" : "Error message shown when the user tries to access the library while the device is locked.", "isCommentAutoGenerated" : true },+ "Unnumbered chapter" : {+ "comment" : "A label for a chapter that is not numbered.",+ "isCommentAutoGenerated" : true+ }, "Update" : { + },+ "Updating chapters" : {+ "comment" : "A description of the user's record history being updated.",+ "isCommentAutoGenerated" : true }, "Use" : { @@ -1918,6 +2433,14 @@ "comment" : "A button that confirms a work's URL.", "isCommentAutoGenerated" : true },+ "Use existing chapter" : {+ "comment" : "A label for a picker that lets the user choose which chapter to use when correcting an entry.",+ "isCommentAutoGenerated" : true+ },+ "Use existing entry" : {+ "comment" : "A picker that lets the user choose an existing entry to use.",+ "isCommentAutoGenerated" : true+ }, "Use suggested URL for %@" : { "comment" : "A button that lets the user confirm a suggested URL for a Work. The argument is the title of the Work.", "isCommentAutoGenerated" : true@@ -2029,6 +2552,10 @@ }, "You have decided every suggestion for this work." : { + },+ "Your copy selections stay here. Return to the work and resume this review after checking the library." : {+ "comment" : "A description of the button that opens the library for the user to review.",+ "isCommentAutoGenerated" : true }, "Your last chapter" : { "comment" : "A label displayed above the user's last read chapter.",@@ -2058,6 +2585,10 @@ } } },+ "Your link note" : {+ "comment" : "A label displayed above the user's link notes.",+ "isCommentAutoGenerated" : true+ }, "also %@" : { "comment" : "A note that a divergent character is also known as.", "isCommentAutoGenerated" : true
diff --git a/Asterism/Asterism/Support/PlatformModifiers.swift b/Asterism/Asterism/Support/PlatformModifiers.swiftindex 4b2983db..ec7a70da 100644--- a/Asterism/Asterism/Support/PlatformModifiers.swift+++ b/Asterism/Asterism/Support/PlatformModifiers.swift@@ -27,6 +27,16 @@ import UniformTypeIdentifiers /// /// A `let`, evaluated once: it is a fact about the binary, not about the run. enum RuntimePlatform {+ /// Copy exactly the authored text through the existing platform seam.+ @MainActor static func copyText(_ text: String) {+ #if os(macOS)+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(text, forType: .string)+ #elseif os(iOS)+ UIPasteboard.general.string = text+ #endif+ }+ static let isMac: Bool = { #if os(macOS) return true@@ -183,6 +193,80 @@ extension View { } } +// MARK: - Inspector hosting and native accessibility++extension View {+ @ViewBuilder+ func macInspector<Inspector: View>(isPresented: Binding<Bool>, @ViewBuilder content: () -> Inspector) -> some View {+ #if os(macOS)+ inspector(isPresented: isPresented, content: content)+ #else+ self+ #endif+ }++ @ViewBuilder+ func nonMacInspector<Inspector: View>(isPresented: Binding<Bool>, @ViewBuilder content: () -> Inspector) -> some View {+ #if os(macOS)+ self+ #else+ inspector(isPresented: isPresented, content: content)+ #endif+ }++ @ViewBuilder+ func macAccessibilityIdentifier(_ identifier: String) -> some View {+ #if os(macOS)+ accessibilityIdentifier(identifier)+ #else+ self+ #endif+ }++ @ViewBuilder+ func macAccessibilityContainer(identifier: String) -> some View {+ #if os(macOS)+ accessibilityElement(children: .contain).accessibilityIdentifier(identifier)+ #else+ self+ #endif+ }+}++/// Native Mac buttons expose their label as a leaf. Keep the real title/date+/// beside the preview button there, while preserving the phone's shared label.+@MainActor @ViewBuilder+func platformRecordHistoryPreview<Heading: View, Preview: View>(+ identifier: String, title: String, value: String, action: @escaping () -> Void,+ @ViewBuilder heading: () -> Heading, @ViewBuilder preview: () -> Preview+) -> some View {+ #if os(macOS)+ VStack(alignment: .leading, spacing: 4) {+ heading()+ .contentShape(Rectangle())+ .onTapGesture(perform: action)+ .accessibilityElement(children: .contain)+ Button(action: action) {+ VStack(alignment: .leading, spacing: 4) { preview() }+ .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityIdentifier(identifier)+ .accessibilityLabel(Text(verbatim: title))+ .accessibilityValue(Text(verbatim: value))+ }+ #else+ Button(action: action) {+ VStack(alignment: .leading, spacing: 4) {+ heading()+ preview()+ }.frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle())+ }+ .buttonStyle(.plain)+ .accessibilityIdentifier(identifier)+ #endif+}+ // MARK: - List and focus chrome extension View {
diff --git a/Asterism/Asterism/UITestLaunchSupport.swift b/Asterism/Asterism/UITestLaunchSupport.swiftindex 5fc4336e..3a404da2 100644--- a/Asterism/Asterism/UITestLaunchSupport.swift+++ b/Asterism/Asterism/UITestLaunchSupport.swift@@ -34,6 +34,9 @@ enum UITestFixtureKind: Equatable { case chapterSpine /// URL-free work with a long accepted cast for manual reference-chip journeys. case manualNoteCast+ /// URL-free saved links, concurrent notes and detached recovery in a UUID test root.+ case associationNotes+ case recordHistory /// One incoherent library shape (Req 1.1, 4.1): the diagnosis surface's UI /// tests need a store the repository's own write paths cannot produce. case tolerated(ToleratedStateFixtureKind)@@ -142,6 +145,17 @@ enum UITestLaunchRequest: Equatable { /// Resolves an isolated, disposable library only for an explicitly requested /// UI-test scenario. Invalid input fails closed instead of opening an App Group. enum UITestLaunchSupport {+ /// Fixed synthetic readback only, behind the existing validated UUID launch.+ static var associationUnicodeReadbackRequested: Bool {+ #if DEBUG && os(macOS)+ guard ProcessInfo.processInfo.environment["ASTERISM_UI_TEST_ASSOCIATION_VERIFY_UNICODE_APPEND"] == "1",+ case .seeded(_, .associationNotes) = request() else { return false }+ return true+ #else+ return false+ #endif+ }+ static let scenarioKey = "ASTERISM_UI_TEST_SCENARIO" static let runIDKey = "ASTERISM_UI_TEST_RUN_ID" /// `today-announcements` Q14: which last-seen version this launch starts@@ -253,60 +267,8 @@ enum UITestLaunchSupport { /// client to hand it to, and a fixture compiled into the shipping binary is /// dead weight that reads as production data. static let cannedExtractionResult = ExtractionResult(- characters: [- ExtractedCharacter(- name: "Ada/Nightjar",- facts: [- ExtractedFact(- statement: "Ada keeps the lighthouse.",- quote: "Ada keeps the lighthouse"),- ExtractedFact(- statement: "Ada is called Nightjar by the crew.",- quote: "the crew call her Nightjar"),- ]),- ExtractedCharacter(- name: "Brede",- facts: [- ExtractedFact(- statement: "Brede rows the tender.",- quote: "Brede rows the tender")- ]),- ExtractedCharacter(- name: "Selkie",- facts: [- ExtractedFact(- statement: "Selkie is moored below the light.",- quote: "Selkie is moored below")- ]),- ],- places: [- ExtractedPlace(- name: "Kestrel Head",- facts: [- ExtractedPlaceFact(- statement: "The lighthouse stands at Kestrel Head.",- quote: "the lighthouse at Kestrel Head"),- // Grounds in the **chapter note** rather than the work's- // generic notes, so the kept place holds one fact with a- // live citation — which is the only way the entry detail's- // Places section (Req 4.4) has anything to draw.- ExtractedPlaceFact(- statement: "The tender passes Kestrel Head.",- quote: "past Kestrel Head"),- ]),- ExtractedPlace(- name: "Selkie",- facts: [- // Deliberately *not* the character copy's wording: the union- // row shows both copies' facts, and two identical lines- // would read as a display bug rather than as one name the- // model filed under both kinds. The quote is the fixture's- // text and stays verbatim.- ExtractedPlaceFact(- statement: "Selkie's mooring lies below the light.",- quote: "moored below the light")- ]),- ])+ characters: [ExtractedCharacter(name: "Ada/Nightjar"), ExtractedCharacter(name: "Brede"), ExtractedCharacter(name: "Selkie")],+ places: [ExtractedPlace(name: "Kestrel Head"), ExtractedPlace(name: "Selkie")]) static func characterExtractionClient( environmentProvider: any ProcessEnvironmentProviding = SystemProcessEnvironment()@@ -441,6 +403,10 @@ enum UITestLaunchSupport { fixture = .composed case seededChapterSpineScenario: fixture = .chapterSpine+ case "seeded-record-history":+ fixture = .recordHistory+ case "seeded-association-notes":+ fixture = .associationNotes case "seeded-manual-note-cast": fixture = .manualNoteCast case seededCharactersScenario:
diff --git a/Asterism/Asterism/ViewModels/AppLibraryModel.swift b/Asterism/Asterism/ViewModels/AppLibraryModel.swiftindex 348538b1..7d5cd789 100644--- a/Asterism/Asterism/ViewModels/AppLibraryModel.swift+++ b/Asterism/Asterism/ViewModels/AppLibraryModel.swift@@ -340,8 +340,8 @@ public final class AppLibraryModel { /// Only unfinished editors, including destinations beneath a pushed work. /// Read-only models remain view-owned; cancel and Save release each session. @ObservationIgnored private var activeWorkEditors: [WorkEditorRoute: WorkDetailModel] = [:]- /// Retains the concrete repository for backup export (conforms to BackupV19SnapshotProviding).- private var backupRepository: (any BackupV19SnapshotProviding)?+ /// Retains the concrete repository for backup export (conforms to BackupV20SnapshotProviding).+ private var backupRepository: (any BackupV20SnapshotProviding)? /// A pre-bootstrap failure used to fail closed on invalid debug launch input. private let startupFailureMessage: String? /// Seeds only a fresh, explicit temporary configuration used by UI tests.@@ -694,7 +694,11 @@ public final class AppLibraryModel { // repository that just opened. Nothing is attempted until an // activation sweeps or an editor opens. self.suggestions = Self.makeSuggestionCoordinator(library: repo)- self.characterExtraction = Self.makeCharacterExtractionCoordinator(library: repo)+ self.characterExtraction = Self.makeCharacterExtractionCoordinator(library: repo, onMutation: { [weak self] in+ // Publish through the same owner generation after background+ // link settlement; do not recurse into extraction reconciliation.+ _ = await self?.refreshAll()+ }) interruptedImport = await repo.interruptedImport() #if DEBUG // `empty-library` Req 3.4, read here because it is the same kind of@@ -1038,13 +1042,13 @@ public final class AppLibraryModel { /// model. The lane is deliberately not a parameter: `ModelLane.shared` is /// the whole guarantee that one request runs at a time app-wide (Req 1.3). private static func makeCharacterExtractionCoordinator(- library: any LibraryProviding+ library: any LibraryProviding, onMutation: @escaping @MainActor () async -> Void ) -> CharacterExtractionCoordinator { var client: any CharacterExtractionModelClient = FoundationCharacterExtractionModelClient() #if DEBUG || ASTERISM_PERFORMANCE_TESTING if let scripted = UITestLaunchSupport.characterExtractionClient() { client = scripted } #endif- return CharacterExtractionCoordinator(library: library, model: client)+ return CharacterExtractionCoordinator(library: library, model: client, onMutation: onMutation) } // MARK: - Preserved captures (pending-capture-queue)@@ -1633,7 +1637,7 @@ public final class AppLibraryModel { let coverFetcher: any CoverFetching = CoverCandidateFetcher() #endif let initialCalendar = calendar- return WorkDetailModel(+ let detail = WorkDetailModel( workID: id, library: repo, calendar: initialCalendar, currentDaySource: { [weak self] in self?.currentDay ?? CivilDay(Date(), calendar: initialCalendar) }, calendarSource: { [weak self] in self?.calendar ?? initialCalendar },@@ -1648,6 +1652,14 @@ public final class AppLibraryModel { await self?.recordConflict(conflict, recordType: .work) }, onEditingChange: onEditingChange)+ #if DEBUG+ if ProcessInfo.processInfo.environment["ASTERISM_UI_TEST_HISTORY_REFRESH"] == "1",+ case .seeded(let testConfiguration, .recordHistory) = UITestLaunchSupport.request(),+ resolvedConfiguration?.rootDirectory == testConfiguration.rootDirectory {+ detail.historyRefreshTestPublish = { [weak self] in await self?.refreshAll() }+ }+ #endif+ return detail } func setLatestModel(@@ -2965,11 +2977,11 @@ public final class AppLibraryModel { /// the other abandoned. Which means only one of them needs to sweep it: /// the backup row's stage does, and Empty Library's is built with /// `scavengesOnInit: false` because both are constructed in the same render.- private func backupExporter() -> BackupV19Exporter? {+ private func backupExporter() -> BackupV20Exporter? { guard let repo = backupRepository, let config = resolvedConfiguration else { return nil } let stagingDir = config.rootDirectory .appending(path: "Library/Caches/BackupExports")- return BackupV19Exporter(repository: repo, stagingDirectory: stagingDir)+ return BackupV20Exporter(repository: repo, stagingDirectory: stagingDir) } /// The per-entry markdown export model (Req 1.5), staged beside the backup@@ -3243,7 +3255,8 @@ public final class AppLibraryModel { /// are the shipping ones. private func seedCharactersFixture(in repo: LibraryRepository) async throws { let entry = try await repo.capture(CaptureDraft(- captureTitle: "Chapter 1 - The Lamp Room",+ captureTitle: ProcessInfo.processInfo.environment["ASTERISM_UI_TEST_SOURCE_ROWS"] == "1"+ ? "The Lamp Room — arrival at the old harbour" : "Chapter 1 - The Lamp Room", captureTitleSource: .host, rawURLString: "https://characters.test/lamp/1", // The place half of the sentence is what gives a *place* fact a@@ -3276,6 +3289,25 @@ public final class AppLibraryModel { releaseDays: reloaded.releaseDays, membership: reloaded.membership, thumbnail: .keep), calendar: calendar)+ #if DEBUG+ if ProcessInfo.processInfo.environment["ASTERISM_UI_TEST_LEGACY_FACTS"] == "1" {+ for (kind, name, aliases, statement, quote, source) in [+ (RecordKind.character, "Ada", ["Nightjar"], "Ada is called Nightjar by the crew.", "the crew call her Nightjar", SourceRef.genericNotes),+ (.character, "Brede", [], "Brede rows the tender.", "Brede rows the tender", .entry(entry.id)),+ (.place, "Kestrel Head", [], "The tender passes Kestrel Head.", "past Kestrel Head", .entry(entry.id))+ ] {+ let key = RecordNameKey.normalize(name)+ let outcome = try await repo.commitDecision(.init(workID: work.id, kind: kind, action: .accept,+ displayedKeys: [key], proposedName: name, proposedAliases: aliases,+ facts: [.init(statement: statement, quote: quote, nameKey: key, source: source)]))+ guard case .committed = outcome else { throw LibraryRepositoryError.invalidInput(operation: "seeding legacy facts", reason: "synthetic seed refused") }+ }+ } else if ProcessInfo.processInfo.environment["ASTERISM_UI_TEST_KNOWN_CHARACTER"] == "1" {+ let outcome = try await repo.commitDecision(.init(workID: work.id, kind: .character, action: .accept,+ displayedKeys: ["brede"], proposedName: "Brede"))+ guard case .committed = outcome else { throw LibraryRepositoryError.invalidInput(operation: "seeding known character", reason: "synthetic seed refused") }+ }+ #endif Self.logger.debug("Seeded the character-extraction UI test fixture") } @@ -4056,6 +4088,25 @@ public final class AppLibraryModel { // record at all — and because the journey it serves relaunches over the // same root, by which time the library holds what the first launch's // drain committed.+ // This one fixture verifies its completed synthetic marker and preserves+ // edits on same-UUID relaunch. It still refuses all unrelated libraries.+ if fixture == .recordHistory {+ #if DEBUG+ try await repository.seedRecordHistoryJourneyFixture()+ return+ #else+ throw LibraryRepositoryError.invalidInput(operation: "preparing history fixture", reason: "requires DEBUG")+ #endif+ }+ if fixture == .associationNotes {+ #if DEBUG+ try await repository.seedAssociationNotesFixture(verifyUnicodeAppend: UITestLaunchSupport.associationUnicodeReadbackRequested)+ return+ #else+ throw LibraryRepositoryError.invalidInput(operation: "preparing UI test fixture",+ reason: "association fixtures require a debug build")+ #endif+ } if fixture == .pendingCaptures { try await seedPendingCaptureFixture() return@@ -4298,3 +4349,12 @@ public final class AppLibraryModel { /// members, so `acquire()` and `release()` stay in the class body where the /// private state they read lives. extension AppLibraryModel: BackgroundExportSession {}++extension AppLibraryModel {+ func detachedAssociationNotesModel() -> DetachedAssociationNotesModel? {+ guard let repository else { return nil }+ return DetachedAssociationNotesModel(library: repository)+ }+ func associationNoteSaved() async { await refreshDiagnosesAndSnapshots() }++}
diff --git a/Asterism/Asterism/ViewModels/AssociationNoteEditorModel.swift b/Asterism/Asterism/ViewModels/AssociationNoteEditorModel.swiftnew file mode 100644index 00000000..f5071ed7--- /dev/null+++ b/Asterism/Asterism/ViewModels/AssociationNoteEditorModel.swift@@ -0,0 +1,90 @@+import AsterismCore+import Foundation+import Observation++@Observable @MainActor+final class AssociationNoteEditorModel {+ let pair: AssociationPair+ let selectedDetachedHeads: [AssociationNoteValue]+ var draftText = "" {+ didSet {+ if !draftText.isEmpty, intendsClear {+ intendsClear = false+ if message == "Save to clear this note." { message = nil }+ }+ }+ }+ private(set) var basis: AssociationNoteBasis?+ private(set) var displayedHeads: [AssociationNoteValue] = []+ private(set) var isSaving = false+ private(set) var isLoading = false+ private(set) var isLoaded = false+ private(set) var didCommit = false+ private(set) var intendsClear = false+ private(set) var message: String?+ private var reviewedLatest = false+ private var initialText = ""+ private let library: any LibraryProviding++ init(pair: AssociationPair, library: any LibraryProviding, selectedDetachedHeads: [AssociationNoteValue] = []) {+ self.pair = pair; self.library = library; self.selectedDetachedHeads = selectedDetachedHeads+ }+ var hasUnsavedChanges: Bool { intendsClear || ExactScalarString(draftText) != ExactScalarString(initialText) }+ var canEdit: Bool { isLoaded && !isLoading && !isSaving && !didCommit }+ var canSave: Bool { basis != nil && canEdit && (hasUnsavedChanges || !selectedDetachedHeads.isEmpty) }+ var canClear: Bool { basis != nil && canEdit && displayedHeads.contains { !$0.text.isEmpty } && selectedDetachedHeads.isEmpty }+ var showsSavedHeads: Bool { displayedHeads.count > 1 || !selectedDetachedHeads.isEmpty || reviewedLatest }++ func load(preservingDraft: Bool = false) async {+ guard !isLoading, !isSaving, !didCommit else { return }+ isLoading = true+ defer { isLoading = false; isLoaded = true }+ do {+ basis = try await library.associationNoteBasis(pair: pair)+ displayedHeads = basis?.heads ?? []+ if preservingDraft { reviewedLatest = true }+ guard basis != nil else {+ message = "This link needs review. Your text remains available to copy."+ return+ }+ if !preservingDraft {+ let candidates = selectedDetachedHeads.isEmpty ? displayedHeads : selectedDetachedHeads+ initialText = candidates.count == 1 ? candidates[0].text : ""+ draftText = initialText+ }+ message = displayedHeads.count > 1 ? "There are differing saved notes. Review each before saving your text." : nil+ } catch { message = "The saved note could not be read. Your draft is unchanged." }+ }+ /// A field action changes only the draft. Save remains the sole writer.+ func stageClear() {+ guard canClear else { return }+ draftText = ""; intendsClear = true+ message = "Save to clear this note."+ }+ /// True is terminal success. Refusal/failure retains the exact draft/basis.+ func save() async -> Bool {+ guard canSave, let basis else { return false }+ isSaving = true; defer { isSaving = false }+ do {+ let result: AssociationNoteWriteOutcome+ if intendsClear {+ result = try await library.clearAssociationNote(basis: basis)+ } else if selectedDetachedHeads.isEmpty {+ result = try await library.saveAssociationNote(basis: basis, text: draftText)+ } else {+ result = try await library.recoverAssociationNotes(basis: basis,+ selectedHeads: selectedDetachedHeads, text: draftText)+ }+ return handle(result)+ } catch { message = "That could not be saved. Your draft is unchanged."; return false }+ }+ private func handle(_ outcome: AssociationNoteWriteOutcome) -> Bool {+ switch outcome {+ case .committed: didCommit = true; return true+ case .reviewRequired: message = "The saved note changed. Review the latest text before saving your draft."+ case .inactive: message = "This link is no longer active. Your draft remains available to copy."+ case .invalidMetadata: message = "This note needs review. Your draft and saved text remain available to copy."+ }+ return false+ }+}
diff --git a/Asterism/Asterism/ViewModels/DetachedAssociationNotesModel.swift b/Asterism/Asterism/ViewModels/DetachedAssociationNotesModel.swiftnew file mode 100644index 00000000..0091256b--- /dev/null+++ b/Asterism/Asterism/ViewModels/DetachedAssociationNotesModel.swift@@ -0,0 +1,34 @@+import AsterismCore+import Foundation+import Observation++@Observable @MainActor+final class DetachedAssociationNotesModel {+ private let library: any LibraryProviding+ private(set) var notes: [DetachedAssociationNoteSnapshot] = []+ private(set) var message: String?+ private(set) var isLoading = false+ private var readRevision = 0+ init(library: any LibraryProviding) { self.library = library }+ func load() async {+ readRevision &+= 1+ let revision = readRevision+ isLoading = true+ defer { if revision == readRevision { isLoading = false } }+ do {+ let values = try await library.detachedAssociationNotes()+ guard revision == readRevision, !Task.isCancelled else { return }+ notes = values; message = nil+ } catch {+ guard revision == readRevision, !Task.isCancelled else { return }+ message = "Saved link notes could not be read. Try again."+ }+ }+ nonisolated static func originalContext(raw: AssociationRawNote, head: AssociationNoteValue?) -> String? {+ head?.originalContext ?? (try? JSONDecoder().decode(String.self, from: raw.originalContextData))+ }+ func editor(for note: DetachedAssociationNoteSnapshot) -> AssociationNoteEditorModel? {+ guard note.canRecover, let pair = note.pair, let head = note.head else { return nil }+ return AssociationNoteEditorModel(pair: pair, library: library, selectedDetachedHeads: [head])+ }+}
diff --git a/Asterism/Asterism/ViewModels/EntryDetailModel.swift b/Asterism/Asterism/ViewModels/EntryDetailModel.swiftindex dd5886fb..b3856ab9 100644--- a/Asterism/Asterism/ViewModels/EntryDetailModel.swift+++ b/Asterism/Asterism/ViewModels/EntryDetailModel.swift@@ -134,6 +134,7 @@ public final class EntryDetailModel { }) } } private let library: any LibraryProviding+ public private(set) var chapterAssociations: [ChapterAssociationSnapshot] = [] public let capabilities: AsterismCapabilities private let onMutation: @Sendable () async -> Void /// Where a refused write goes (Req 2.10, Q47). The draft stays here; the@@ -271,21 +272,47 @@ public final class EntryDetailModel { state = .loading do { let detail = try await library.entryTeachingDetail(id: entryID)+ guard !Task.isCancelled else { return } let snapshot = detail.entry self.entry = snapshot self.teachingDetail = detail+ self.chapterAssociations = detail.chapterAssociations.filter { !$0.activeAcceptanceIDs.isEmpty } self.draftTitle = snapshot.authoredTarget?.title ?? "" self.draftSourceURL = snapshot.sourceURLs.first ?? "" self.draftNote = snapshot.note self.draftRating = snapshot.rating state = .ready } catch {+ guard !Task.isCancelled else { return } unavailability = Self.unavailability(for: error) state = .error(message: error.localizedDescription) Self.logger.error("Entry detail load failed: \(String(describing: error), privacy: .public)") } } + /// Association-only publication never replaces the reader's chapter drafts.+ public func refreshAssociations() async {+ guard entry != nil else { return }+ do {+ let values = try await library.chapterAssociations(entryID: entryID)+ guard !Task.isCancelled else { return }+ chapterAssociations = values.filter { !$0.activeAcceptanceIDs.isEmpty }+ } catch { Self.logger.error("Chapter associations could not refresh: \(String(describing: error), privacy: .public)") }+ }+ func associationNoteEditor(for pair: AssociationPair) -> AssociationNoteEditorModel? {+ guard chapterAssociations.contains(where: { $0.pair == pair }) else { return nil }+ return AssociationNoteEditorModel(pair: pair, library: library)+ }+ func skippedCharacterLinksModel() -> SkippedCharacterLinksModel {+ SkippedCharacterLinksModel(entryID: entryID, library: library, chapterTitle: screenTitle) { [weak self] in+ await self?.associationNoteSaved()+ }+ }+ func associationNoteSaved() async {+ await onMutation()+ await refreshAssociations()+ }+ /// What a failed load means for the reader. /// /// Only `recordNotFound` for an Entry says the record is gone. A quarantine
diff --git a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift b/Asterism/Asterism/ViewModels/SettingsBackupModel.swiftindex 23bac07a..c7485a19 100644--- a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift+++ b/Asterism/Asterism/ViewModels/SettingsBackupModel.swift@@ -5,7 +5,7 @@ import OSLog // MARK: - Backup Exporting Protocol /// Test seam abstracting the exporter's operations needed by the Settings-/// surface. Conforms `BackupV19Exporter` to this protocol via extension below.+/// surface. Conforms `BackupV20Exporter` to this protocol via extension below. /// /// Settings exports 15/16 (`work-thumbnails` Req 8.1): the archive /// carries the reader's named places and their suppressions, a Work's site@@ -19,6 +19,7 @@ public protocol BackupExporting: Sendable { } extension BackupV19Exporter: BackupExporting {}+extension BackupV20Exporter: BackupExporting {} // MARK: - Export Stage
diff --git a/Asterism/Asterism/ViewModels/SkippedCharacterLinksModel.swift b/Asterism/Asterism/ViewModels/SkippedCharacterLinksModel.swiftnew file mode 100644index 00000000..b3375305--- /dev/null+++ b/Asterism/Asterism/ViewModels/SkippedCharacterLinksModel.swift@@ -0,0 +1,48 @@+import AsterismCore+import Foundation+import Observation++/// An independent explicit action, never a field in the parent chapter draft.+@Observable @MainActor+final class SkippedCharacterLinksModel {+ enum State { case loading, ready, error }+ private(set) var state: State = .loading+ private(set) var links: [SkippedCharacterLinkSnapshot] = []+ private(set) var isSubmitting = false+ private(set) var message: String?+ let entryID: UUID+ let chapterTitle: String+ private var requestGeneration = 0+ private let library: any LibraryProviding+ private let onMutation: @MainActor () async -> Void+ init(entryID: UUID, library: any LibraryProviding, chapterTitle: String = "Saved chapter", onMutation: @escaping @MainActor () async -> Void = {}) {+ self.entryID = entryID; self.chapterTitle = chapterTitle; self.library = library; self.onMutation = onMutation+ }+ func load() async {+ guard !isSubmitting else { return }+ requestGeneration += 1; let request = requestGeneration+ state = .loading+ do {+ let captured = try await library.skippedCharacterLinks(entryID: entryID)+ guard request == requestGeneration, !Task.isCancelled else { return }+ links = captured; state = .ready; message = nil+ } catch {+ guard request == requestGeneration, !Task.isCancelled else { return }+ state = .error; message = "Skipped links could not be loaded. Try again."+ }+ }+ func restore(_ captured: SkippedCharacterLinkSnapshot) async {+ guard !isSubmitting, state == .ready, links.contains(captured), captured.pair.entryID == entryID else { return }+ requestGeneration += 1+ isSubmitting = true; defer { isSubmitting = false }+ do {+ switch try await library.restoreCharacterLink(captured) {+ case .committed:+ links.removeAll { $0 == captured }; message = nil+ await onMutation()+ case .refused:+ message = "This link changed or is no longer supported. Review the latest links before restoring."+ }+ } catch { message = "The link could not be restored. Your saved notes are unchanged." }+ }+}
diff --git a/Asterism/Asterism/ViewModels/WorkDetailModel.swift b/Asterism/Asterism/ViewModels/WorkDetailModel.swiftindex 060d73d9..96a59418 100644--- a/Asterism/Asterism/ViewModels/WorkDetailModel.swift+++ b/Asterism/Asterism/ViewModels/WorkDetailModel.swift@@ -85,35 +85,214 @@ public final class WorkDetailModel { /// Two notes numbered and shared alike then keep the order they arrived in /// instead of moving between loads. private static func chapterOrder(_ rows: [WorkChapterRow]) -> [WorkChapterRow] {- rows.enumerated().sorted(by: precedesInChapterOrder).map(\.element)- }-- private static func precedesInChapterOrder(- _ left: (offset: Int, element: WorkChapterRow),- _ right: (offset: Int, element: WorkChapterRow)- ) -> Bool {- let lhs = left.element- let rhs = right.element- // The placement where both have one; a note with one before a note- // without. `ChapterPlacement` is the scale — one derivation shared with- // the share sheet's catch-up selection (share-sheet-last-note Decision- // 4), so the spine and the sheet cannot come apart about order. The- // `lastSharedAt` fallback below stays here: it is what an *unplaced*- // row falls back to on this page, and the sheet has no such fallback.- switch (- ChapterPlacement(sequencePosition: lhs.sequencePosition, chapterKey: lhs.chapterKey),- ChapterPlacement(sequencePosition: rhs.sequencePosition, chapterKey: rhs.chapterKey)- ) {- case (.some(let leftPlacement), .some(let rightPlacement)):- if leftPlacement != rightPlacement { return leftPlacement < rightPlacement }- case (.some, .none): return true- case (.none, .some): return false- case (.none, .none): break- }- if lhs.lastSharedAt != rhs.lastSharedAt {- return lhs.lastSharedAt < rhs.lastSharedAt- }- return left.offset < right.offset+ WorkChapterRow.inChapterOrder(rows)+ }++ // MARK: - Selected chapter-linked history++ public enum RecordHistoryState: Sendable, Equatable {+ case idle, loading, ready, error+ }+ public private(set) var selectedRecordHistory: RecordHistorySelection?+ public private(set) var recordHistory: RecordHistorySnapshot?+ public private(set) var recordHistoryState: RecordHistoryState = .idle+ public var isRecordHistorySectionExpanded = false+ public private(set) var isRefreshingRecordHistory = false+ public private(set) var visibleRecordHistoryLimit = 20+ public private(set) var expandedRecordHistoryPairs: Set<AssociationPair> = []+ private struct HistoryReadTarget: Equatable {+ let publication: Int?+ let forceRevision: Int+ }+ private struct HistoryReadOperation {+ let token: Int+ let selection: RecordHistorySelection+ let target: HistoryReadTarget+ let worker: Task<RecordHistorySnapshot, Error>+ }+ public private(set) var recordHistoryNeedsValidation = false+ @ObservationIgnored private var recordHistoryRequest = 0+ @ObservationIgnored private var historyPublication: Int?+ @ObservationIgnored private var historyForceRevision = 0+ @ObservationIgnored private var completedHistoryTarget: HistoryReadTarget?+ @ObservationIgnored private var historyRead: HistoryReadOperation?+ private var desiredHistoryTarget: HistoryReadTarget {+ .init(publication: historyPublication, forceRevision: historyForceRevision)+ }+ #if DEBUG+ // Only the UUID-contained refresh fixture supplies this callback. It uses+ // the real owner publication and repository; ordinary app paths stay nil.+ var historyRefreshTestPublish: (@MainActor () async -> Int?)?+ private(set) var historyRefreshTestStarts = 0+ private(set) var historyRefreshTestCompletions = 0+ private(set) var historyRefreshTestPublications = 0+ func publishHistoryRefreshTestInvalidations() async {+ guard let publish = historyRefreshTestPublish, let generation = await publish() else { return }+ historyRefreshTestPublications += 1+ let a = Task { await self.refreshRecordHistory(publicationGeneration: generation) }+ let b = Task { await self.refreshRecordHistory(publicationGeneration: generation) }+ await refreshRecordHistory(publicationGeneration: generation)+ await a.value; await b.value+ }+ var historyRefreshTestMetrics: String {+ "starts=\(historyRefreshTestStarts);completed=\(historyRefreshTestCompletions);publications=\(historyRefreshTestPublications);capture=\(recordHistory?.generation ?? "none");holdMs=250"+ }+ #endif+ public var visibleRecordHistoryRows: [RecordHistoryRow] {+ Array((recordHistory?.rows ?? []).prefix(visibleRecordHistoryLimit))+ }+ public var remainingRecordHistoryCount: Int { max(0, (recordHistory?.rows.count ?? 0) - visibleRecordHistoryRows.count) }++ public func selectRecordHistory(kind: RecordKind, recordID: UUID) async {+ let selection = RecordHistorySelection(workID: workID, kind: kind, recordID: recordID)+ if selectedRecordHistory != selection {+ clearRecordHistorySelection()+ selectedRecordHistory = selection+ }+ // Asking for the already selected record owes no new mutation epoch.+ await requestRecordHistory(publicationGeneration: nil, force: false)+ }+ public func clearRecordHistorySelection() {+ let previous = historyRead+ recordHistoryRequest += 1; historyRead = nil+ selectedRecordHistory = nil; recordHistory = nil+ recordHistoryState = .idle; isRefreshingRecordHistory = false+ recordHistoryNeedsValidation = false+ visibleRecordHistoryLimit = 20; expandedRecordHistoryPairs = []+ isRecordHistorySectionExpanded = false+ historyPublication = nil; historyForceRevision = 0; completedHistoryTarget = nil+ previous?.worker.cancel()+ }+ public func refreshRecordHistory(publicationGeneration: Int? = nil) async {+ // An explicit unversioned reload (Save, load or retry) is a new read+ // obligation. It never erases a known global publication generation.+ await requestRecordHistory(publicationGeneration: publicationGeneration, force: publicationGeneration == nil)+ }+ private func requestRecordHistory(publicationGeneration: Int?, force: Bool) async {+ guard let selection = selectedRecordHistory, !Task.isCancelled else { return }+ if let publicationGeneration {+ historyPublication = max(historyPublication ?? publicationGeneration, publicationGeneration)+ }+ if force { historyForceRevision += 1 }+ if completedHistoryTarget != desiredHistoryTarget { recordHistoryNeedsValidation = true }+ while selectedRecordHistory == selection, !Task.isCancelled {+ if recordHistoryState == .ready, !recordHistoryNeedsValidation,+ completedHistoryTarget == desiredHistoryTarget { return }+ if let cancelled = historyRead, cancelled.worker.isCancelled {+ cancelRecordHistory(cancelled)+ }+ let operation: HistoryReadOperation+ let isCreator: Bool+ if let current = historyRead {+ operation = current; isCreator = false+ } else {+ operation = startRecordHistory(selection: selection); isCreator = true+ }+ let result = await withTaskCancellationHandler {+ await operation.worker.result+ } onCancel: { [weak self] in+ // Capture this invocation's immutable worker, never whatever+ // newer operation the model may now own. A joined waiter owns+ // no cancellation authority over the shared repository read.+ guard isCreator else { return }+ operation.worker.cancel()+ Task { @MainActor [weak self] in self?.cancelRecordHistory(operation) }+ }+ finishRecordHistory(operation, result: result)+ // A failed/interrupted current read stays retryable, without an+ // autonomous retry loop. Newer owed work has its own active read.+ if historyRead == nil, completedHistoryTarget != desiredHistoryTarget { return }+ }+ }+ private func startRecordHistory(selection: RecordHistorySelection) -> HistoryReadOperation {+ recordHistoryRequest += 1+ let target = desiredHistoryTarget, selectedLibrary = library+ #if DEBUG+ let fixtureHold = historyRefreshTestPublish != nil+ #endif+ let worker = Task { @MainActor [weak self] in+ #if DEBUG+ if fixtureHold { self?.historyRefreshTestStarts += 1 }+ #endif+ let snapshot = try await selectedLibrary.recordHistory(workID: selection.workID, kind: selection.kind, recordID: selection.recordID)+ #if DEBUG+ if fixtureHold {+ self?.historyRefreshTestCompletions += 1+ try await Task.sleep(for: .milliseconds(250))+ }+ #endif+ return snapshot+ }+ let operation = HistoryReadOperation(token: recordHistoryRequest, selection: selection, target: target, worker: worker)+ historyRead = operation; recordHistoryNeedsValidation = true; isRefreshingRecordHistory = true+ recordHistoryState = recordHistory == nil ? .loading : .ready+ // Finishing/draining belongs to the model, including when every view+ // waiter has disappeared. Each worker still performs exactly one read.+ Task { @MainActor [weak self] in+ let result = await worker.result+ self?.finishRecordHistory(operation, result: result)+ }+ return operation+ }+ private func cancelRecordHistory(_ operation: HistoryReadOperation) {+ guard historyRead?.token == operation.token, selectedRecordHistory == operation.selection else { return }+ historyRead = nil; recordHistoryNeedsValidation = true+ if desiredHistoryTarget != operation.target {+ _ = startRecordHistory(selection: operation.selection)+ } else {+ isRefreshingRecordHistory = false+ recordHistoryState = recordHistory == nil ? .idle : .ready+ }+ }+ private func finishRecordHistory(_ operation: HistoryReadOperation, result: Result<RecordHistorySnapshot, Error>) {+ guard historyRead?.token == operation.token, selectedRecordHistory == operation.selection else { return }+ if operation.worker.isCancelled { cancelRecordHistory(operation); return }+ if case .failure(let error) = result, error is CancellationError {+ cancelRecordHistory(operation); return+ }+ historyRead = nil+ guard desiredHistoryTarget == operation.target else {+ // A later publication or post-mutation reload remains owed. Never+ // publish this earlier capture or certify that later obligation.+ _ = startRecordHistory(selection: operation.selection)+ return+ }+ isRefreshingRecordHistory = false+ switch result {+ case .success(let snapshot):+ guard snapshot.selection == operation.selection else {+ recordHistoryState = .error; recordHistoryNeedsValidation = true; return+ }+ if recordHistory != snapshot { recordHistory = snapshot }+ recordHistoryState = .ready; recordHistoryNeedsValidation = false+ completedHistoryTarget = operation.target+ expandedRecordHistoryPairs.formIntersection(Set(snapshot.rows.map(\.id)))+ visibleRecordHistoryLimit = min(max(20, visibleRecordHistoryLimit), max(20, snapshot.rows.count))+ case .failure(let error):+ recordHistoryState = .error; recordHistoryNeedsValidation = true+ Self.logger.error("Record history could not load: \(String(describing: error), privacy: .public)")+ }+ }+ public func showMoreRecordHistory() {+ guard recordHistoryState == .ready, let snapshot = recordHistory else { return }+ visibleRecordHistoryLimit = min(snapshot.rows.count, visibleRecordHistoryLimit + 20)+ }+ public func recordHistoryDetail(for pair: AssociationPair, expectedGeneration: String) -> RecordHistoryDetail? {+ guard recordHistoryState == .ready else { return nil }+ return recordHistory?.detail(for: pair, expectedGeneration: expectedGeneration)+ }+ public func setRecordHistoryExpanded(_ pair: AssociationPair, expanded: Bool, expectedGeneration: String) {+ guard recordHistoryDetail(for: pair, expectedGeneration: expectedGeneration) != nil else { return }+ if expanded { expandedRecordHistoryPairs.insert(pair) } else { expandedRecordHistoryPairs.remove(pair) }+ }+ func recordHistoryNoteEditor(for pair: AssociationPair) -> AssociationNoteEditorModel? {+ guard recordHistoryState == .ready, !isRefreshingRecordHistory, !recordHistoryNeedsValidation,+ recordHistory?.rows.contains(where: { $0.id == pair }) == true else { return nil }+ return AssociationNoteEditorModel(pair: pair, library: library)+ }+ func recordHistoryNoteSaved() async {+ await onMutation()+ await refreshRecordHistory() } // MARK: - Characters (`character-extraction` Reqs 3.2, 3.7, 5.1–5.3)@@ -562,6 +741,7 @@ public final class WorkDetailModel { resetWorkURLHostnameIfNeeded() state = .ready if !isEditing || !preservingDrafts { await loadWorkURL() }+ if selectedRecordHistory != nil { await refreshRecordHistory() } } catch { state = .error(message: error.localizedDescription) Self.logger.error("Work load failed: \(String(describing: error), privacy: .public)")
diff --git a/Asterism/Asterism/Views/AssociationNoteClipboard.swift b/Asterism/Asterism/Views/AssociationNoteClipboard.swiftnew file mode 100644index 00000000..0f0bd5c8--- /dev/null+++ b/Asterism/Asterism/Views/AssociationNoteClipboard.swift@@ -0,0 +1,5 @@+enum AssociationNoteClipboard {+ @MainActor static func copy(_ text: String) {+ RuntimePlatform.copyText(text)+ }+}
diff --git a/Asterism/Asterism/Views/AssociationNoteEditorView.swift b/Asterism/Asterism/Views/AssociationNoteEditorView.swiftnew file mode 100644index 00000000..88fc7faa--- /dev/null+++ b/Asterism/Asterism/Views/AssociationNoteEditorView.swift@@ -0,0 +1,62 @@+import AsterismCore+import SwiftUI++struct AssociationNoteEditorView: View {+ @State private var model: AssociationNoteEditorModel+ @Environment(\.dismiss) private var dismiss+ let onSaved: @MainActor () async -> Void++ init(model: AssociationNoteEditorModel, onSaved: @escaping @MainActor () async -> Void) {+ _model = State(initialValue: model); self.onSaved = onSaved+ }+ var body: some View {+ NavigationStack {+ Form {+ if model.showsSavedHeads && !model.displayedHeads.isEmpty {+ Section("Saved notes") {+ ForEach(model.displayedHeads, id: \.id) { head in+ Text(head.text.isEmpty ? "Cleared note" : head.text)+ .textSelection(.enabled)+ }+ }+ }+ Section("Note for this chapter link") {+ TextEditor(text: $model.draftText)+ .frame(minHeight: 160)+ .disabled(!model.canEdit)+ .accessibilityIdentifier(model.isLoaded && !model.isLoading+ ? "association-note-text" : "association-note-loading-text")+ Button("Copy draft") { AssociationNoteClipboard.copy(model.draftText) }+ .accessibilityIdentifier("association-note-copy-draft")+ if let message = model.message {+ Text(message).foregroundStyle(.secondary)+ .accessibilityIdentifier("association-note-message")+ Button("Review latest saved note") { Task { await model.load(preservingDraft: true) } }+ .disabled(model.isSaving)+ .accessibilityIdentifier("association-note-review-latest")+ }+ }+ if model.canClear {+ Section {+ Button("Clear note", role: .destructive) { model.stageClear() }+ .accessibilityIdentifier("association-note-clear")+ }+ }+ }+ .navigationTitle("Chapter link note")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Cancel") { dismiss() }.disabled(model.isSaving || model.didCommit)+ .accessibilityIdentifier("association-note-cancel")+ }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") { Task { if await model.save() { await onSaved(); dismiss() } } }+ .disabled(!model.canSave)+ .accessibilityIdentifier("association-note-save")+ }+ }+ .task { await model.load() }+ }+ .frame(minWidth: 320, minHeight: 360)+ }+}
diff --git a/Asterism/Asterism/Views/CharacterEditorView.swift b/Asterism/Asterism/Views/CharacterEditorView.swiftindex c58932cc..db4c42a8 100644--- a/Asterism/Asterism/Views/CharacterEditorView.swift+++ b/Asterism/Asterism/Views/CharacterEditorView.swift@@ -108,15 +108,6 @@ struct CharacterEditorView: View { ConstellationSectionHeader("Aliases", accent: .violet) } - if !draft.facts.isEmpty {- Section {- ForEach(draft.facts, id: \.identity) { fact in- factRow(fact)- }- } header: {- ConstellationSectionHeader("Facts", accent: .violet)- }- } Section { structuralActions(combineTargets: combineTargets)@@ -143,7 +134,7 @@ struct CharacterEditorView: View { } Button("Cancel", role: .cancel) { isCombining = false } } message: {- Text("Their facts and names move across. Nothing is written until you tap the checkmark.")+ Text("Their names and saved details move across. Nothing is written until you tap the checkmark.") } }
diff --git a/Asterism/Asterism/Views/CharacterReviewView.swift b/Asterism/Asterism/Views/CharacterReviewView.swiftindex 0d541639..58eab4f1 100644--- a/Asterism/Asterism/Views/CharacterReviewView.swift+++ b/Asterism/Asterism/Views/CharacterReviewView.swift@@ -1,3 +1,4 @@+import AsterismIntelligence import AsterismCore import ConstellationKit import SwiftUI@@ -99,7 +100,7 @@ struct CharacterReviewView: View { @ViewBuilder private func rowContent(_ row: CharacterReviewRow) -> some View { if row.isBundle {- Text("Adds to a \(RecordKindPresentation.noun(row.kind)) you already have.")+ Text("Existing \(RecordKindPresentation.noun(row.kind)): \(row.name)") .font(.caption) .foregroundStyle(.secondary) .accessibilityIdentifier("character-review-bundle-note")@@ -129,6 +130,8 @@ struct CharacterReviewView: View { .accessibilityIdentifier("character-review-dual-\(row.id)") } + ProposalSourceEvidenceView(evidence: row.sourceEvidence, rowID: row.id)+ ForEach(row.aliases) { alias in // Q92: shown and strikeable before accepting, never installed // silently. "A/B" in these notes is as often a pairing as a second@@ -143,19 +146,6 @@ struct CharacterReviewView: View { .accessibilityIdentifier("character-review-alias-\(alias.name)") } - ForEach(row.proposedFacts) { fact in- Toggle(isOn: factBinding(row: row, fact: fact)) {- VStack(alignment: .leading, spacing: 4) {- Text(fact.statement)- Text("“\(fact.quote)”")- .font(.caption)- .foregroundStyle(.secondary)- }- }- .frame(minHeight: AsterismLayout.minHitTarget)- .accessibilityIdentifier("character-review-fact-\(fact.id)")- }- if row.proposedFacts.isEmpty, row.aliases.isEmpty { Text(RecordKindPresentation.nameOnlyNote(row.kind)) .font(.caption)@@ -163,19 +153,6 @@ struct CharacterReviewView: View { .accessibilityIdentifier("character-review-name-only-\(row.id)") } - // Req 2.1: a bundle is shown *beside* what the character already holds,- // so the reader can see what is being added to rather than guessing.- if !row.existingFacts.isEmpty {- DisclosureGroup("Already kept (\(row.existingFacts.count))") {- ForEach(row.existingFacts) { fact in- Text(fact.statement)- .font(.caption)- .foregroundStyle(.secondary)- }- }- .accessibilityIdentifier("character-review-existing-\(row.id)")- }- // Req 2.2: the reader's one-tap correction of the model's kind, on the // rows that are theirs to re-file. `ConstellationSegmentedControl` // rather than a `Picker`: §7 defines the segmented capsule once, and it
diff --git a/Asterism/Asterism/Views/DetachedAssociationNotesView.swift b/Asterism/Asterism/Views/DetachedAssociationNotesView.swiftnew file mode 100644index 00000000..df74440a--- /dev/null+++ b/Asterism/Asterism/Views/DetachedAssociationNotesView.swift@@ -0,0 +1,47 @@+import AsterismCore+import SwiftUI++struct DetachedAssociationNotesView: View {+ @State private var model: DetachedAssociationNotesModel+ @State private var editor: AssociationNoteEditorModel?+ let onSaved: @MainActor () async -> Void+ let snapshotGeneration: Int+ init(model: DetachedAssociationNotesModel, snapshotGeneration: Int = 0, onSaved: @escaping @MainActor () async -> Void) {+ _model = State(initialValue: model); self.onSaved = onSaved; self.snapshotGeneration = snapshotGeneration+ }+ var body: some View {+ List {+ if let message = model.message { Text(message) }+ if model.notes.isEmpty && !model.isLoading && model.message == nil {+ Text("There are no detached chapter link notes.").foregroundStyle(.secondary)+ }+ ForEach(model.notes) { note in+ Section {+ Text(note.raw.text).textSelection(.enabled)+ .accessibilityIdentifier("detached-association-note-text")+ Button("Copy text") { AssociationNoteClipboard.copy(note.raw.text) }+ .accessibilityIdentifier("detached-association-note-copy")+ if let context = DetachedAssociationNotesModel.originalContext(raw: note.raw, head: note.head) {+ Text(context).font(.caption).foregroundStyle(.secondary)+ }+ if note.canRecover {+ Button("Recover to this chapter link") { editor = model.editor(for: note) }+ .accessibilityIdentifier("detached-association-note-recover")+ } else {+ Text("This text remains available to copy. Its chapter link needs review before recovery.")+ .font(.caption).foregroundStyle(.secondary)+ }+ }+ }+ }+ .navigationTitle("Detached link notes")+ .task(id: snapshotGeneration) { await model.load() }+ .sheet(isPresented: Binding(get: { editor != nil }, set: { if !$0 { editor = nil } })) {+ if let editor {+ AssociationNoteEditorView(model: editor) {+ await model.load(); await onSaved()+ }+ }+ }+ }+}
diff --git a/Asterism/Asterism/Views/EntryDetailView.swift b/Asterism/Asterism/Views/EntryDetailView.swiftindex 70585a64..bf2dc4c6 100644--- a/Asterism/Asterism/Views/EntryDetailView.swift+++ b/Asterism/Asterism/Views/EntryDetailView.swift@@ -24,6 +24,9 @@ struct EntryDetailView: View { @State private var showingComposedTeaching = false @State private var showingReparse = false @State private var showingCorrection = false+ @State private var associationEditor: AssociationNoteEditorModel?+ @State private var skippedLinks: SkippedCharacterLinksModel?+ let snapshotGeneration: Int /// Q49: collapsed by default. Capture evidence and the recovery actions are /// the screen's error-handling surface, not part of reading a note. @State private var showingCaptureDetails = false@@ -58,8 +61,10 @@ struct EntryDetailView: View { onOpenWork: ((UUID) -> Void)? = nil, exportModel: MarkdownExportModel? = nil, showsSky: Bool = true,- leavesAfterUpdate: Bool = true+ leavesAfterUpdate: Bool = true,+ snapshotGeneration: Int = 0 ) {+ self.snapshotGeneration = snapshotGeneration self.onResolveDuplicate = onResolveDuplicate self.onOpenWork = onOpenWork self.showsSky = showsSky@@ -108,13 +113,24 @@ struct EntryDetailView: View { // stack renders behind the stack's own opaque backing and never // reaches the screen. In the wide tree the window owns it (Req 3.1). .screenSky(showsSky)- .task { await model.load() }+ .task(id: snapshotGeneration) {+ if model.entry == nil { await model.load() }+ else { await model.refreshAssociations() }+ }+ .sheet(isPresented: Binding(get: { associationEditor != nil }, set: { if !$0 { associationEditor = nil } })) {+ if let associationEditor {+ AssociationNoteEditorView(model: associationEditor) { await model.associationNoteSaved() }+ }+ }+ .sheet(isPresented: Binding(get: { skippedLinks != nil }, set: { if !$0 { skippedLinks = nil } })) {+ if let skippedLinks { SkippedCharacterLinksView(model: skippedLinks) }+ } // `app-intents` Req 4.5: this screen has no edit mode — the note and // the rating are always editable — so an unsaved change is what holds // the reader's place against an open intent, with the two sheets it // raises. .intentEditSession(- active: model.hasUnsavedChanges || showingComposedTeaching || showingReparse)+ active: model.hasUnsavedChanges || showingComposedTeaching || showingReparse || skippedLinks != nil || associationEditor != nil) } @ViewBuilder@@ -206,6 +222,7 @@ struct EntryDetailView: View { .accessibilityIdentifier("entry-detail-delete-button") } + chapterAssociationsSection citingCharactersSection citingPlacesSection @@ -442,15 +459,43 @@ struct EntryDetailView: View { .fixedSize(horizontal: false, vertical: true) } + @ViewBuilder+ private var chapterAssociationsSection: some View {+ if model.entry?.workID != nil {+ Section {+ ForEach(model.chapterAssociations) { association in+ Button {+ associationEditor = model.associationNoteEditor(for: association.pair)+ } label: {+ VStack(alignment: .leading, spacing: 4) {+ Text(association.recordName)+ if association.noteHeads.count > 1 {+ Text("Multiple saved notes").font(.caption).foregroundStyle(.secondary)+ } else if let note = association.noteHeads.first, !note.text.isEmpty {+ Text(note.text).font(.caption).foregroundStyle(.secondary).lineLimit(2)+ } else {+ Text("Add note").font(.caption).foregroundStyle(.secondary)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .contentShape(Rectangle())+ }+ .accessibilityIdentifier("entry-association-\(association.pair.kind.rawValue)-\(association.pair.recordID.uuidString)")+ .accessibilityLabel("\(association.recordName), \(RecordKindPresentation.noun(association.pair.kind)), chapter link note")+ }+ Button("Skipped character links") { skippedLinks = model.skippedCharacterLinksModel() }+ .accessibilityIdentifier("entry-skipped-character-links")+ } header: { ConstellationSectionHeader("Chapter links", accent: .violet) }+ }+ }+ /// `character-extraction` Req 5.4: who this note is about, where any /// character says so. Absent rather than empty — most notes name nobody the /// reader has kept, and an empty section on every entry would be noise on /// the screen where they write. ///- /// A count rather than a list of statements: a character can cite one entry- /// several times, and saying "3 facts" is more honest than the name three- /// times. The facts themselves live on the work page, which is where they- /// are edited.+ /// Legacy reference names remain useful context. Fact counts and prose are+ /// hidden while the underlying citation data remains unchanged. @ViewBuilder private var citingCharactersSection: some View { citingRecordsSection(model.citingCharacters, kind: .character)@@ -472,15 +517,11 @@ struct EntryDetailView: View { if !records.isEmpty { Section { ForEach(records) { record in- LabeledContent(record.name) {- Text(Pluralisation.count(record.factCount, "fact", "facts"))- .font(.caption)- .foregroundStyle(.secondary)- }+ Text(record.name) .accessibilityIdentifier( "entry-detail-citing-\(RecordKindPresentation.noun(kind))") .accessibilityLabel(- "\(record.name), \(Pluralisation.count(record.factCount, "fact", "facts")) citing this note")+ "\(record.name), \(RecordKindPresentation.noun(kind)) referencing this note") } } header: { ConstellationSectionHeader(
diff --git a/Asterism/Asterism/Views/ProposalSourceEvidenceView.swift b/Asterism/Asterism/Views/ProposalSourceEvidenceView.swiftnew file mode 100644index 00000000..7c19d1ca--- /dev/null+++ b/Asterism/Asterism/Views/ProposalSourceEvidenceView.swift@@ -0,0 +1,54 @@+import ConstellationKit+import AsterismCore+import AsterismIntelligence+import SwiftUI++/// Exact captured display values; expansion never rereads or generates prose.+struct ProposalSourceEvidenceView: View {+ let evidence: [ProposalSourceEvidence]+ let rowID: String+ @State private var limit = 20+ var body: some View {+ VStack(alignment: .leading, spacing: 10) {+ Text("Saved sources (\(evidence.count))").font(.subheadline.bold())+ if evidence.isEmpty { Text("Captured source unavailable").foregroundStyle(.secondary) }+ ForEach(Array(evidence.prefix(limit))) { source in+ DisclosureGroup {+ Text(verbatim: source.text)+ .textSelection(.enabled)+ .fixedSize(horizontal: false, vertical: true)+ .accessibilityIdentifier("review-source-text-\(rowID)-\(source.id)")+ } label: {+ VStack(alignment: .leading, spacing: 4) {+ SourceTitleDateRow(title: Self.presentationTitle(source), date: source.capturedAt,+ identifier: "review-source-\(rowID)-\(source.id)")+ if !source.isChapter {+ Text(sourceLabel(source)).font(.caption).foregroundStyle(.secondary)+ }+ Text("Supported spelling: \(source.spellings.joined(separator: ", "))")+ .font(.caption)+ Text(source.isDecisionBasis ? "Captured saved note" : "Informational saved context")+ .font(.caption).foregroundStyle(.secondary)+ Text(verbatim: source.text).font(.caption).lineLimit(2)+ }+ .accessibilityIdentifier("review-source-\(rowID)-\(source.id)")+ }+ .accessibilityElement(children: .contain)+ }+ if evidence.count > limit {+ Button("Show more sources (\(evidence.count - limit) remaining)") { limit += 20 }+ .frame(minHeight: AsterismLayout.minHitTarget)+ .accessibilityIdentifier("review-sources-more-\(rowID)")+ }+ }+ }+ static func presentationTitle(_ source: ProposalSourceEvidence) -> String {+ if source.isChapter { return SourceTitleDateRow.chapterTitle(source.displayTitle) }+ if !source.displayTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return source.displayTitle }+ return source.source == .genericNotes ? "Work generic notes" : "Standalone note"+ }+ private func sourceLabel(_ source: ProposalSourceEvidence) -> String {+ if source.source == .genericNotes { return "Work generic notes" }+ return source.isChapter ? "Chapter note" : "Standalone note · not a chapter"+ }+}
diff --git a/Asterism/Asterism/Views/RecordHistoryView.swift b/Asterism/Asterism/Views/RecordHistoryView.swiftnew file mode 100644index 00000000..425748bd--- /dev/null+++ b/Asterism/Asterism/Views/RecordHistoryView.swift@@ -0,0 +1,120 @@+import ConstellationKit+import AsterismCore+import SwiftUI++/// Only the focused typed record owns the model's selected immutable snapshot.+struct RecordHistoryView: View {+ @Bindable var model: WorkDetailModel+ let kind: RecordKind+ let recordID: UUID+ let onSelectEntry: ((UUID) -> Void)?+ @State private var editor: AssociationNoteEditorModel?+ private var isSelected: Bool {+ model.selectedRecordHistory?.kind == kind && model.selectedRecordHistory?.recordID == recordID+ }+ var body: some View {+ VStack(alignment: .leading, spacing: 10) {+ if !isSelected {+ Button("Show chapters") { Task { await model.selectRecordHistory(kind: kind, recordID: recordID) } }+ .frame(minHeight: AsterismLayout.minHitTarget)+ .accessibilityIdentifier("record-history-select-\(kind.rawValue)-\(recordID.uuidString)")+ } else {+ selectedContent+ }+ }+ .buttonStyle(.borderless)+ .intentEditSession(active: editor != nil)+ .sheet(isPresented: Binding(get: { editor != nil }, set: { if !$0 { editor = nil } })) {+ if let editor { AssociationNoteEditorView(model: editor) { await model.recordHistoryNoteSaved() } }+ }+ }+ @ViewBuilder private var selectedContent: some View {+ switch model.recordHistoryState {+ case .idle, .loading: ProgressView("Loading chapters…")+ case .error:+ Text("Chapters could not be loaded.")+ Button("Try again") { Task { await model.refreshRecordHistory() } }+ .frame(minHeight: AsterismLayout.minHitTarget)+ case .ready:+ if let snapshot = model.recordHistory {+ DisclosureGroup(isExpanded: $model.isRecordHistorySectionExpanded) {+ historyRows(snapshot)+ } label: {+ Text(snapshot.activeChapterCount.map { "Chapters (\($0))" } ?? "Chapters · review needed")+ .font(.headline)+ .frame(minHeight: AsterismLayout.minHitTarget, alignment: .leading)+ .accessibilityIdentifier("record-history-count")+ .accessibilityValue(model.isRefreshingRecordHistory ? "Updating chapters" :+ model.recordHistoryNeedsValidation ? "Chapter refresh interrupted" : "")+ }++ if snapshot.availability != .available {+ Text("Some chapter or record information is unavailable or needs review. Detached link notes remain in Settings.")+ .font(.caption).foregroundStyle(.secondary)+ .accessibilityIdentifier("record-history-unavailable")+ }+ if snapshot.rows.isEmpty, snapshot.availability == .available {+ Text("No linked chapters").foregroundStyle(.secondary)+ }++ }+ }+ }+ @ViewBuilder private func historyRows(_ snapshot: RecordHistorySnapshot) -> some View {+ ForEach(model.visibleRecordHistoryRows) { row in+ chapterRow(row, generation: snapshot.generation)+ }+ if model.remainingRecordHistoryCount > 0 {+ Button("Show 20 more (\(model.remainingRecordHistoryCount) remaining)") { model.showMoreRecordHistory() }+ .frame(minHeight: AsterismLayout.minHitTarget)+ .accessibilityIdentifier("record-history-more")+ }+ }+ private func chapterRow(_ row: RecordHistoryRow, generation: String) -> some View {+ let title = SourceTitleDateRow.chapterTitle(row.displayTitle, designation: row.chapterKey?.label)+ let toggle = {+ model.setRecordHistoryExpanded(row.id,+ expanded: !model.expandedRecordHistoryPairs.contains(row.id), expectedGeneration: generation)+ }+ return VStack(alignment: .leading, spacing: 6) {+ platformRecordHistoryPreview(+ identifier: "record-history-row-\(row.id.entryID.uuidString)",+ title: title,+ value: row.sourcePreview ++ (row.hasConflictingAnnotations ? ", " + String(localized: "Multiple link notes") : ""),+ action: toggle+ ) {+ SourceTitleDateRow(title: title, date: row.notedAt,+ identifier: "record-history-\(row.id.entryID.uuidString)")+ } preview: {+ Text(verbatim: row.sourcePreview).font(.caption).lineLimit(2)+ if row.hasConflictingAnnotations { Text("Multiple link notes").font(.caption) }+ }+ if model.expandedRecordHistoryPairs.contains(row.id),+ let detail = model.recordHistoryDetail(for: row.id, expectedGeneration: generation) {+ Text("Saved chapter note").font(.caption.bold())+ Text(verbatim: detail.sourceText).textSelection(.enabled)+ .fixedSize(horizontal: false, vertical: true)+ .accessibilityIdentifier("record-history-source-\(row.id.entryID.uuidString)")+ Text("Your link note").font(.caption.bold())+ if detail.annotationHeads.isEmpty { Text("No link note").foregroundStyle(.secondary) }+ ForEach(detail.annotationHeads, id: \.id) { head in+ Text(verbatim: head.text.isEmpty ? "Cleared note" : head.text)+ .textSelection(.enabled).fixedSize(horizontal: false, vertical: true)+ }+ if detail.annotationMetadataNeedsReview { Text("Link note information needs review").font(.caption) }+ Button("Edit link note") { editor = model.recordHistoryNoteEditor(for: row.id) }+ .frame(minHeight: AsterismLayout.minHitTarget)+ .disabled(model.isRefreshingRecordHistory || model.recordHistoryNeedsValidation)+ .accessibilityIdentifier("record-history-edit-\(row.id.entryID.uuidString)")+ if let onSelectEntry {+ Button("Open chapter") { onSelectEntry(row.id.entryID) }+ .frame(minHeight: AsterismLayout.minHitTarget)+ .accessibilityIdentifier("record-history-open-\(row.id.entryID.uuidString)")+ }+ }+ }+ .padding(.vertical, 6)+ .accessibilityElement(children: .contain)+ }+}
diff --git a/Asterism/Asterism/Views/SettingsView.swift b/Asterism/Asterism/Views/SettingsView.swiftindex e72075b0..ae73e685 100644--- a/Asterism/Asterism/Views/SettingsView.swift+++ b/Asterism/Asterism/Views/SettingsView.swift@@ -62,6 +62,9 @@ struct SettingsView: View { /// `workTypesModel`, and for its reason: the screen it pushes owns the /// loaded state, and it builds its own per-role detail models. private let creatorRolesModel: CreatorRolesModel?+ private let detachedAssociationNotesModel: DetachedAssociationNotesModel?+ private let snapshotGeneration: Int+ private let onAssociationNoteSaved: @MainActor () async -> Void // MARK: - Preserved captures (pending-capture-queue Reqs 2.5, 6.9, 10.1–10.6) @@ -136,6 +139,9 @@ struct SettingsView: View { siteDetailModel: SiteDetailModelBuilder? = nil, workTypesModel: WorkTypesModel? = nil, creatorRolesModel: CreatorRolesModel? = nil,+ detachedAssociationNotesModel: DetachedAssociationNotesModel? = nil,+ snapshotGeneration: Int = 0,+ onAssociationNoteSaved: @escaping @MainActor () async -> Void = {}, pendingCaptureWaitingNotice: String? = nil, setAsideCaptures: [SetAsideCaptureRow] = [], drainReportNotice: DrainReportNotice? = nil,@@ -156,6 +162,9 @@ struct SettingsView: View { self.siteDetailModel = siteDetailModel self.workTypesModel = workTypesModel self.creatorRolesModel = creatorRolesModel+ self.detachedAssociationNotesModel = detachedAssociationNotesModel+ self.snapshotGeneration = snapshotGeneration+ self.onAssociationNoteSaved = onAssociationNoteSaved self.pendingCaptureWaitingNotice = pendingCaptureWaitingNotice self.setAsideCaptures = setAsideCaptures self.drainReportNotice = drainReportNotice@@ -230,6 +239,14 @@ struct SettingsView: View { workTypesSection creatorRolesSection+ if let detachedAssociationNotesModel {+ Section {+ NavigationLink {+ DetachedAssociationNotesView(model: detachedAssociationNotesModel, snapshotGeneration: snapshotGeneration, onSaved: onAssociationNoteSaved)+ } label: { Label("Detached link notes", systemImage: "note.text") }+ .accessibilityIdentifier("settings-detached-association-notes")+ }+ } aboutSection
diff --git a/Asterism/Asterism/Views/SkippedCharacterLinksView.swift b/Asterism/Asterism/Views/SkippedCharacterLinksView.swiftnew file mode 100644index 00000000..7a70acf6--- /dev/null+++ b/Asterism/Asterism/Views/SkippedCharacterLinksView.swift@@ -0,0 +1,49 @@+import ConstellationKit+import AsterismCore+import SwiftUI++struct SkippedCharacterLinksView: View {+ @State var model: SkippedCharacterLinksModel+ @Environment(\.dismiss) private var dismiss+ var body: some View {+ NavigationStack {+ Form {+ Section {+ Text(model.chapterTitle).font(.headline)+ Text("Restore only a supported character link for this saved chapter. Detached link notes remain separate.")+ .font(.footnote)+ }+ if let message = model.message {+ Section {+ Text(message).accessibilityIdentifier("skipped-links-message")+ Button("Review latest links") { Task { await model.load() } }+ .disabled(model.isSubmitting)+ }+ }+ if model.state == .loading { ProgressView("Loading skipped links…") }+ else if model.state == .ready, model.links.isEmpty {+ Text("No supported skipped character links").accessibilityIdentifier("skipped-links-empty")+ }+ ForEach(model.links) { link in+ Section(link.recordName) {+ Text("Supported spellings: \(link.spellingKeys.joined(separator: ", "))")+ .font(.caption)+ Button("Restore link") { Task { await model.restore(link) } }+ .frame(minHeight: AsterismLayout.minHitTarget)+ .disabled(model.isSubmitting || model.state != .ready)+ .accessibilityIdentifier("skipped-link-restore-\(link.pair.recordID.uuidString)")+ }+ }+ }+ .navigationTitle("Skipped character links")+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button("Done") { dismiss() }.disabled(model.isSubmitting)+ .accessibilityIdentifier("skipped-links-done")+ }+ }+ .task { await model.load() }+ }+ .frame(minWidth: 320, minHeight: 360)+ }+}
diff --git a/Asterism/Asterism/Views/SourceTitleDateRow.swift b/Asterism/Asterism/Views/SourceTitleDateRow.swiftnew file mode 100644index 00000000..e28739f8--- /dev/null+++ b/Asterism/Asterism/Views/SourceTitleDateRow.swift@@ -0,0 +1,37 @@+import ConstellationKit+import SwiftUI++/// A source's title wraps in the leading column; the compact date owns the+/// trailing edge of the same full-width row, including at accessibility sizes.+struct SourceTitleDateRow: View {+ let title: String+ let date: Date?+ let identifier: String++ var body: some View {+ HStack(alignment: .firstTextBaseline, spacing: 8) {+ Text(verbatim: title)+ .font(.footnote.weight(.semibold))+ .fixedSize(horizontal: false, vertical: true)+ .frame(maxWidth: .infinity, alignment: .leading)+ .accessibilityIdentifier(identifier + "-title")+ if let date {+ Text(Calendar.current.isDateInToday(date) ? "Today" : date.formatted(date: .abbreviated, time: .omitted))+ .font(.caption2)+ .foregroundStyle(AsterismColors.secondaryText)+ .fixedSize()+ .accessibilityIdentifier(identifier + "-date")+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .accessibilityElement(children: .contain)+ }++ static func chapterTitle(_ title: String, designation: String? = nil) -> String {+ if !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return title }+ if let designation, !designation.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ return "Chapter " + designation+ }+ return "Unnumbered chapter"+ }+}
diff --git a/Asterism/Asterism/Views/TodayView.swift b/Asterism/Asterism/Views/TodayView.swiftindex 41a96d5d..9b9ea5cf 100644--- a/Asterism/Asterism/Views/TodayView.swift+++ b/Asterism/Asterism/Views/TodayView.swift@@ -116,7 +116,7 @@ struct TodayView: View { let libraryHasBeenRead: Bool let isWide: Bool @Binding var scrollOffset: CGFloat- @State private var scrollPosition = ScrollPosition()+ @State private var scrollPosition: ScrollPosition let onSeeAllCatchingUp: (() -> Void)? @State private var paneWidth: CGFloat = 0 /// The announcement row's tap: the sheet is `ContentView`'s, through@@ -201,6 +201,7 @@ struct TodayView: View { self.libraryHasBeenRead = libraryHasBeenRead self.isWide = isWide self._scrollOffset = scrollOffset+ self._scrollPosition = State(initialValue: ScrollPosition(y: scrollOffset.wrappedValue)) self.onSeeAllCatchingUp = onSeeAllCatchingUp self.onOpenAnnouncement = onOpenAnnouncement self.onSelect = onSelect@@ -332,7 +333,7 @@ struct TodayView: View { .padding(.horizontal, 24) .padding(.top, 24) ScrollView {- LazyVStack(alignment: .leading, spacing: 24) {+ VStack(alignment: .leading, spacing: 24) { banners announcementSection(plan) if WideLayoutPolicy.todayLayout(forPaneWidth: paneWidth) == .columns {@@ -352,15 +353,13 @@ struct TodayView: View { } else { releasesSection(plan, accent: .cyan) catchingUpSection(plan)- notedSection(plan, accent: .violet)+ LazyVStack(alignment: .leading, spacing: 16) { notedSection(plan, accent: .violet) } } }.padding(24) .frame(width: paneWidth > 0 ? paneWidth : nil, alignment: .leading)- .scrollTargetLayout() } .scrollPosition($scrollPosition) .onScrollGeometryChange(for: CGFloat.self) { max(0, $0.contentOffset.y + $0.contentInsets.top) } action: { _, offset in scrollOffset = offset }- .onAppear { scrollPosition.scrollTo(y: scrollOffset) } .onChange(of: selectedDay) { _, _ in scrollPosition.scrollTo(y: 0) } .accessibilityElement(children: .contain).accessibilityIdentifier("recent-list") }
diff --git a/Asterism/Asterism/Views/WorkDetailView.swift b/Asterism/Asterism/Views/WorkDetailView.swiftindex 0879be41..7a9fb447 100644--- a/Asterism/Asterism/Views/WorkDetailView.swift+++ b/Asterism/Asterism/Views/WorkDetailView.swift@@ -73,6 +73,7 @@ struct WorkDetailView: View { let calendar: Calendar let lastSavedLatestWorkID: UUID? let latestSaveGeneration: Int+ let snapshotGeneration: Int /// Where a committed merge leaves the reader (Req 4.6): the Work that /// survived it. Nil where the host has no route — the Merge sheet's own /// embedded copy of this screen — and the screen dismisses instead, which is@@ -157,6 +158,7 @@ struct WorkDetailView: View { calendar: Calendar, lastSavedLatestWorkID: UUID? = nil, latestSaveGeneration: Int = 0,+ snapshotGeneration: Int = 0, onResolveDuplicate: (() -> Void)? = nil, onCheckLibrary: (() -> Void)? = nil, onSelectEntry: ((UUID) -> Void)? = nil,@@ -176,6 +178,7 @@ struct WorkDetailView: View { self.calendar = calendar self.lastSavedLatestWorkID = lastSavedLatestWorkID self.latestSaveGeneration = latestSaveGeneration+ self.snapshotGeneration = snapshotGeneration _exportModel = State(initialValue: exportModel) self.onResolveDuplicate = onResolveDuplicate self.onCheckLibrary = onCheckLibrary@@ -242,7 +245,23 @@ struct WorkDetailView: View { .intentEditSession(active: model.isEditing || presentsSheet) .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { detailWidth = $0 } .screenSky(showsSky)+ #if DEBUG+ .safeAreaInset(edge: .bottom) {+ if model.historyRefreshTestPublish != nil {+ HStack {+ Text(model.historyRefreshTestMetrics).font(.caption2).lineLimit(1)+ .accessibilityIdentifier("record-history-test-metrics")+ Button("Publish ×3") { Task { await model.publishHistoryRefreshTestInvalidations() } }+ .accessibilityIdentifier("record-history-test-publish")+ }+ .frame(height: 44).frame(maxWidth: .infinity).background(.regularMaterial)+ }+ }+ #endif .task { await model.load() }+ .task(id: snapshotGeneration) {+ await model.refreshRecordHistory(publicationGeneration: snapshotGeneration)+ } .onChange(of: latestSaveGeneration) { _, newGeneration in guard newGeneration > 0, lastSavedLatestWorkID == model.work?.id else { return }@@ -1939,6 +1958,7 @@ struct WorkDetailView: View { Circle().fill(AsterismColors.cyan).frame(width: 8, height: 8).shadow(color: AsterismColors.cyan, radius: 6) if let rating = row.rating { Text(rating == .up ? "▲" : "▼").foregroundStyle(AsterismColors.cyan) } Button("Edit") { onSelectEntry?(row.id) }+ .macAccessibilityIdentifier("work-detail-edit-focused-entry-" + row.id.uuidString) if let url = model.work?.entries.first(where: { $0.id == row.id })?.rawURLString, let url = URL(string: url) { Button("Open chapter ↗") { openURL(url) } }@@ -2417,6 +2437,12 @@ struct WorkDetailView: View { withAnimation(.snappy) { expanded.wrappedValue = isExpanded ? nil : record.id }+ if !isExpanded {+ Task { await model.selectRecordHistory(kind: record.kind, recordID: record.id) }+ } else if model.selectedRecordHistory?.recordID == record.id,+ model.selectedRecordHistory?.kind == record.kind {+ model.clearRecordHistorySelection()+ } } label: { HStack(spacing: 5) { Text(record.name)@@ -2426,8 +2452,6 @@ struct WorkDetailView: View { Image(systemName: "exclamationmark.circle") .foregroundStyle(AsterismColors.amberText) }- Text("\(record.facts.count)")- .foregroundStyle(AsterismColors.secondaryText) Image(systemName: "chevron.down") .font(.caption2) .rotationEffect(.degrees(isExpanded ? 180 : 0))@@ -2438,12 +2462,11 @@ struct WorkDetailView: View { } .buttonStyle(.plain) .accessibilityIdentifier(RecordKindPresentation.workDetailIdentifier(record.kind))- .accessibilityLabel("\(record.name), \(record.facts.count) facts")+ .accessibilityLabel("\(record.name), \(RecordKindPresentation.noun(record.kind))") } - /// The one expanded record: the name and its aliases, the note, then the- /// facts on the same gutter the spine uses — everything the old always-open- /// row showed, on request and laid out to be read.+ /// The expanded record keeps aliases and the reader's note beside its+ /// chapter history. Legacy facts remain in the model and Save payload. private func recordDetailCard(_ record: WorkRecordPresentation) -> some View { let kind = record.kind return VStack(alignment: .leading, spacing: 10) {@@ -2471,6 +2494,7 @@ struct WorkDetailView: View { .frame(maxWidth: .infinity, alignment: .leading) if !record.note.isEmpty {+ Text("Record note").font(.caption).foregroundStyle(.secondary) Text(record.note) .font(.subheadline) .foregroundStyle(AsterismColors.noteText)@@ -2479,19 +2503,15 @@ struct WorkDetailView: View { .frame(maxWidth: .infinity, alignment: .leading) } - if !record.facts.isEmpty {- Rectangle()- .fill(AsterismColors.cardBorder)- .frame(height: 1)- ForEach(record.facts) { fact in- recordFactRow(fact, kind: kind)- }- }+ RecordHistoryView(model: model, kind: record.kind, recordID: record.id, onSelectEntry: onSelectEntry)++ } .frame(maxWidth: .infinity, alignment: .leading) .padding(12) .constellationCard() .constellationListRow()+ .macAccessibilityContainer(identifier: "work-detail-record-card-\(kind.rawValue)-\(record.id.uuidString)") } /// Req 5.2: each citation opens the note it came from, where that note still@@ -2762,22 +2782,15 @@ struct WorkDetailView: View { ([name, counts].compactMap { $0 } + (line.isTorn ? ["differing copies"] : [])) .joined(separator: ", ")) .accessibilityHint(- "Opens this \(RecordKindPresentation.noun(kind))'s name, aliases and facts")+ "Opens this \(RecordKindPresentation.noun(kind))'s name, aliases and note") } - /// "2 aliases · 3 facts" — the two things a draft holds that the line can- /// count, and nothing at all for a record that holds neither.- ///- /// New presentation of data the editor already carried: `RecordDraft` has- /// always had both, and the pill showed only the name.+ /// Hidden facts remain in the draft; only aliases contribute a visible count. private static func recordCounts(_ draft: RecordDraft) -> String? { var parts: [String] = [] if !draft.aliases.isEmpty { parts.append(Pluralisation.count(draft.aliases.count, "alias", "aliases")) }- if !draft.facts.isEmpty {- parts.append(Pluralisation.count(draft.facts.count, "fact", "facts"))- } return parts.isEmpty ? nil : parts.joined(separator: " · ") } @@ -2825,7 +2838,7 @@ struct WorkDetailView: View { refresh: { await extraction.reconcile() return extraction.held(for: workID)- })+ }, currentHeld: { extraction.held(for: workID) }) } private func runManualPass(workID: UUID) async {
diff --git a/Asterism/Asterism/Views/WorksGroupView.swift b/Asterism/Asterism/Views/WorksGroupView.swiftindex ffa5b815..a12b39eb 100644--- a/Asterism/Asterism/Views/WorksGroupView.swift+++ b/Asterism/Asterism/Views/WorksGroupView.swift@@ -38,6 +38,10 @@ struct WorksSearchContent<Hub: View>: View { @State private var query = "" @State private var tokens: [WorksSearchToken] = [] @AppStorage private var storedSort: String+ // `library` is configuration and may never be installed as a View.+ @Environment(\.publicationDay) private var publishedDay+ @Environment(\.calendar) private var calendar+ private var currentDay: CivilDay { publishedDay ?? CivilDay(Date(), calendar: calendar) } @Environment(\.siteNames) private var siteNames @Environment(\.columnHeadingProvided) private var columnHeadingProvided @@ -52,13 +56,13 @@ struct WorksSearchContent<Hub: View>: View { private var filter: WorksFilter { WorksSearchToken.filter(from: tokens) } private var active: Bool { !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || filter.isActive }- private var members: [WorkSnapshot] { group?.members(of: library.snapshot.works, on: library.currentDay) ?? library.snapshot.works }+ private var members: [WorkSnapshot] { group?.members(of: library.snapshot.works, on: currentDay) ?? library.snapshot.works } private var values: [WorksSearchToken] { WorksSearchToken.values(options: library.filterOptions, siteNames: siteNames) } private var suggestions: [WorksSearchToken] { WorksSearchToken.suggestions(query: query, values: values, group: group) } private var rows: [WorkSnapshot] { // A dimension prefix is navigation through suggestions, not a title query. let searchingDimension = query.contains(":") && !suggestions.isEmpty- let narrowed = filter.apply(to: WorksSearchFilter(query: searchingDimension ? "" : query).apply(to: members), on: library.currentDay)+ let narrowed = filter.apply(to: WorksSearchFilter(query: searchingDimension ? "" : query).apply(to: members), on: currentDay) if let group { return group.sorted(narrowed, by: WorksGroupSort(rawValue: storedSort) ?? .groupDefault) } return WorksSort(storedValue: storedSort).apply(to: narrowed) }@@ -70,7 +74,7 @@ struct WorksSearchContent<Hub: View>: View { private var subtitle: String { let base = "\(members.count) works · \(sortPhrase)" guard let group else { return base }- let stat = library.tileStat(group, members: members)+ let stat = library.tileStat(group, members: members, currentDay: currentDay, calendar: calendar) return stat.isEmpty || stat == "\(members.count) works" ? base : base + " · " + stat } @@ -150,7 +154,7 @@ struct WorksSearchContent<Hub: View>: View { .constellationListRow() } if group == .catchingUp {- ForEach(rows.filter { CatchUpProgress.build(work: $0, day: library.currentDay, calendar: library.calendar).state == .caughtUp }, id: \.id) { work in+ ForEach(rows.filter { CatchUpProgress.build(work: $0, day: currentDay, calendar: calendar).state == .caughtUp }, id: \.id) { work in VStack(alignment: .leading, spacing: 8) { Text("You're caught up with " + work.displayTitle).font(AsterismTypography.serif(.subheadline)) HStack {@@ -169,7 +173,7 @@ struct WorksSearchContent<Hub: View>: View { Section { ForEach(rows, id: \.id) { work in library.workButton(work, titles: library.titlesByWorkID, showsSeries: true,- siteNames: siteNames, group: group)+ siteNames: siteNames, group: group, currentDay: currentDay, calendar: calendar) .listRowBackground(AsterismColors.cardFill) .listRowSeparatorTint(AsterismColors.cardBorder) .listRowInsets(EdgeInsets())
diff --git a/Asterism/Asterism/Views/WorksView.swift b/Asterism/Asterism/Views/WorksView.swiftindex e06bb2ae..73072f3e 100644--- a/Asterism/Asterism/Views/WorksView.swift+++ b/Asterism/Asterism/Views/WorksView.swift@@ -6,8 +6,8 @@ import SwiftUI /// Library home and the shared row affordances used by its destinations. struct WorksView: View { @Environment(\.publicationDay) private var publishedDay- @Environment(\.calendar) var calendar- var currentDay: CivilDay { publishedDay ?? CivilDay(Date(), calendar: calendar) }+ @Environment(\.calendar) private var calendar+ private var currentDay: CivilDay { publishedDay ?? CivilDay(Date(), calendar: calendar) } let snapshot: WorksSnapshot let onSelectWork: (UUID) -> Void let onSelectEntry: (UUID) -> Void@@ -176,7 +176,7 @@ struct WorksView: View { ForEach([WorksGroup.catchingUp, .reading, .toRead], id: \.self) { group in let members = group.sorted(group.members(of: snapshot.works, on: currentDay)) tile(group.title, count: members.count, covers: Array(members.prefix(3)),- stat: tileStat(group, members: members), accent: group == .catchingUp,+ stat: tileStat(group, members: members, currentDay: currentDay, calendar: calendar), accent: group == .catchingUp, identifier: "library-tile-\(group.rawValue)") { select(.group(group)) } } let allSeries = seriesProgress@@ -228,7 +228,7 @@ struct WorksView: View { .accessibilityIdentifier("library-hub") } - func tileStat(_ group: WorksGroup, members: [WorkSnapshot]) -> String {+ func tileStat(_ group: WorksGroup, members: [WorkSnapshot], currentDay: CivilDay, calendar: Calendar) -> String { switch group { case .catchingUp: let behind = members.compactMap { CatchUpProgress.build(work: $0, day: currentDay, calendar: calendar).behind }.reduce(0, +)@@ -308,7 +308,7 @@ struct WorksView: View { func workButton( _ work: WorkSnapshot, titles: [UUID: String], showsSeries: Bool, siteNames: SiteNames,- group: WorksGroup? = nil+ group: WorksGroup? = nil, currentDay: CivilDay, calendar: Calendar ) -> some View { let item = duplicateWorkload.item(for: work.id, type: .work) let toReadMatch = duplicateWorkload.toReadMatch(for: work.id)
diff --git a/Asterism/AsterismTests/AppNavigationTests.swift b/Asterism/AsterismTests/AppNavigationTests.swiftindex 8d47ec6f..05659eb2 100644--- a/Asterism/AsterismTests/AppNavigationTests.swift+++ b/Asterism/AsterismTests/AppNavigationTests.swift@@ -31,6 +31,32 @@ struct AppNavigationTests { todayChapterEntryID: nil, workID: nil, worksEntryID: nil, workChapterEntryID: nil) == .entry(entryID)) } + @Test("Inspector Entry and Work transitions retain Today day/scroll state")+ func inspectorEntryWorkAndDashboardKeepReaderContext() {+ let navigation = AppNavigation()+ let first = UUID(), second = UUID(), work = UUID()+ navigation.todayScrollAnchor = 321+ let day = navigation.todaySelection+ navigation.todayInspectorEntryID = first+ navigation.showTodayEntry(first)+ #expect(navigation.todayInspectorEntryID == nil)+ #expect(navigation.selectedTodayEntryID == first && navigation.todayPath.isEmpty)+ #expect(!navigation.isTodayRoot)+ navigation.showWork(work, on: .today)+ #expect(navigation.selectedTodayEntryID == nil && navigation.todayPath == [.work(work)])+ // One synchronous Work→Entry operation ends nonroot even though it+ // clears the typed path before assigning its final selected Entry.+ navigation.showTodayEntry(second)+ #expect(navigation.todayPath.isEmpty && navigation.selectedTodayEntryID == second)+ #expect(!navigation.isTodayRoot)+ #expect(navigation.todaySelection == day && navigation.todayScrollAnchor == 321)+ navigation.back()+ #expect(navigation.isTodayRoot && navigation.selectedTodayEntryID == nil)+ #expect(navigation.todaySelection == day && navigation.todayScrollAnchor == 321)+ navigation.showTodayEntry(first)+ #expect(navigation.selectedTodayEntryID == first && !navigation.isTodayRoot)+ }+ // MARK: - Fixtures private static func workSet(_ members: [UUID]) -> DuplicateSetKey {
diff --git a/Asterism/AsterismTests/AssociationCoverageRaceTests.swift b/Asterism/AsterismTests/AssociationCoverageRaceTests.swiftnew file mode 100644index 00000000..87a3626c--- /dev/null+++ b/Asterism/AsterismTests/AssociationCoverageRaceTests.swift@@ -0,0 +1,176 @@+import AsterismCore+import AsterismIntelligence+import Foundation+import SwiftData+import Testing+@testable import Asterism++@Suite("Durable mention coverage across held settlements", .serialized)+@MainActor+struct AssociationCoverageRaceTests {+ private struct Fixture: Sendable {+ let root: URL+ let configuration: LibraryConfiguration+ let repository: LibraryRepository+ let workID: UUID+ let entryID: UUID+ init() async throws {+ root = FileManager.default.temporaryDirectory.appendingPathComponent("asterism-association-race-\(UUID().uuidString)")+ configuration = LibraryConfiguration(rootDirectory: root)+ try FileManager.default.createDirectory(at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ let container = try LibraryRepository.openContainer(at: configuration.storeURL)+ try ModelContext(container).save()+ withExtendedLifetime(container) {}+ try LibraryRepository.publishReadiness(at: configuration.readinessMarkerURL)+ let (_, repository) = try await LibraryRepository.openForApp(configuration, capabilities: .current)+ self.repository = repository+ let work = try await repository.createWork(.init(displayTitle: "Synthetic coverage race", hostname: ""))+ workID = work.id+ let projection = try await repository.projectManualEntry(workID: work.id)+ guard case .committed(let chapter) = try await repository.commitManualEntry(projection: projection,+ draft: .init(target: .init(kind: .chapter, title: "Arrival", designation: "1"),+ note: "Ada visits Bryn.", confirmedNewChapter: true)) else { throw FixtureError.refused }+ entryID = chapter.id+ // Extraction owns the links in this fixture. Save the chapter before+ // these records exist; creating records does not backfill old notes.+ guard case .committed = try await repository.commitRecordEdits(workID: work.id,+ operations: [.create(.init(kind: .place, name: "Ada")), .create(.init(kind: .place, name: "Bryn"))]) else {+ throw FixtureError.refused+ }+ try #require(try await repository.chapterAssociations(entryID: entryID).isEmpty,+ "Coverage races must begin with unaccepted mentions, not save-time links")+ }+ }+ private enum FixtureError: Error { case refused }+ private func waitUntil(_ condition: @MainActor () -> Bool) async throws {+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))+ while !condition(), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(2)) }+ }+ private func client(_ name: String) -> StubCharacterExtractionModelClient {+ .init(result: .init(places: [.init(name: name, facts: [])]))+ }+ private func source(_ fixture: Fixture, repository: LibraryRepository? = nil) async throws -> CharacterExtractionSource {+ let candidate = try #require(try await (repository ?? fixture.repository).extractionCandidates(limit: 1, workIDs: [fixture.workID]).first)+ return try #require(candidate.sources.first { $0.ref == .entry(fixture.entryID) })+ }+ private func review(_ fixture: Fixture, coordinator: CharacterExtractionCoordinator, library: any LibraryProviding) async throws -> CharacterReviewModel {+ let detail = try await fixture.repository.workDetail(id: fixture.workID)+ return CharacterReviewModel(workID: fixture.workID, proposals: coordinator.held(for: fixture.workID),+ characters: detail.characters, places: detail.places, library: library,+ extractionContext: { coordinator.context(for: fixture.workID) },+ onDecision: { key, kinds in coordinator.discard(key, for: fixture.workID, nameKeySuppressedKinds: kinds) },+ onReRoute: { key, target in coordinator.retarget(key, for: fixture.workID, to: target) },+ onReclassify: { key, kind, target in coordinator.reclassify(key, for: fixture.workID, to: kind, target: target) },+ refresh: { await coordinator.reconcile(); return coordinator.held(for: fixture.workID) },+ currentHeld: { coordinator.held(for: fixture.workID) })+ }++ @Test("B settling during A's awaited decision remains eligible after restart in either save order", arguments: [false, true])+ func lateSettlementCannotBeHiddenByACompletedSource(commitFirst: Bool) async throws {+ let fixture = try await Fixture()+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let initial = try await source(fixture)+ #expect(!initial.isCovered)+ let model = CharacterExtractionCoordinatorTests.MutableAvailabilityClient(.available, inner: client("Ada"))+ let coordinator = CharacterExtractionCoordinator(library: fixture.repository, model: model,+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ await coordinator.runManualPass(workID: fixture.workID)+ #expect(coordinator.held(for: fixture.workID).map(\.nameKey) == ["ada"])+ let allowB = SubmissionGate(), allowA = SubmissionGate()+ let recorder = StubCharacterExtractionModelClient.Recorder()+ model.inner = .init(result: .init(places: [.init(name: "Bryn", facts: [])]), recorder: recorder)+ model.onExtract = { _ in await allowB.wait() }+ let b = Task { await coordinator.runManualPass(workID: fixture.workID) }+ defer { allowB.open(); allowA.open(); b.cancel() }+ try await waitUntil { recorder.callCount == 1 }+ try #require(recorder.callCount == 1)+ let proxy = MockLibraryProvider()+ proxy.commitDecisionHold = { await allowA.wait() }+ proxy.commitDecisionHandler = { try await fixture.repository.commitDecision($0) }+ let sheet = try await review(fixture, coordinator: coordinator, library: proxy)+ let row = try #require(sheet.rows.first)+ #expect(row.targetID != nil && row.aliases.isEmpty, "A accepts an existing record without changing the matching directory")+ let a = Task { await sheet.accept(row.id) }+ defer { a.cancel() }+ try await waitUntil { proxy.committedDecisions.count == 1 }+ try #require(proxy.committedDecisions.count == 1)+ #expect(proxy.committedDecisions[0].completedSources.first { $0.ref == .entry(fixture.entryID) }?.mentionEligibilityDigest != nil,+ "A prepared its completion before B was published")+ if commitFirst {+ allowA.open(); await a.value+ allowB.open(); await b.value+ } else {+ allowB.open(); await b.value+ allowA.open(); await a.value+ }+ #expect(sheet.rows.isEmpty)+ #expect(coordinator.held(for: fixture.workID).map(\.nameKey) == ["bryn"])+ #expect(try await fixture.repository.chapterAssociations(entryID: fixture.entryID).count == 1)+ let current = try await source(fixture)+ #expect(current.fingerprint == initial.fingerprint)+ #expect(!current.isCovered, "Undecided B must remain durably eligible even though A saved after its display snapshot")+ let (_, reopened) = try await LibraryRepository.openForApp(fixture.configuration, capabilities: .current)+ #expect(try await !source(fixture, repository: reopened).isCovered, "A fresh run can derive B without the old RAM ledger")+ await reopened.shutdown(); await fixture.repository.shutdown()+ }++ @Test("A later manual pass over a covered unchanged source durably re-arms newly held B")+ func manualDiscoveryAfterCompletedCoverageRearmsTheSource() async throws {+ let fixture = try await Fixture()+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let model = CharacterExtractionCoordinatorTests.MutableAvailabilityClient(.available, inner: client("Ada"))+ let coordinator = CharacterExtractionCoordinator(library: fixture.repository, model: model,+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ await coordinator.runManualPass(workID: fixture.workID)+ let first = try await review(fixture, coordinator: coordinator, library: fixture.repository)+ await first.accept(try #require(first.rows.first).id)+ #expect(try await source(fixture).isCovered, "The control genuinely certified A's unchanged source")+ let accepted = try await fixture.repository.chapterAssociations(entryID: fixture.entryID)+ model.inner = client("Bryn")+ await coordinator.runManualPass(workID: fixture.workID)+ #expect(coordinator.held(for: fixture.workID).map(\.nameKey) == ["bryn"])+ #expect(try await fixture.repository.chapterAssociations(entryID: fixture.entryID) == accepted,+ "Pending review affects coverage, not accepted membership or notes")+ #expect(try await !source(fixture).isCovered)+ let (_, reopened) = try await LibraryRepository.openForApp(fixture.configuration, capabilities: .current)+ #expect(try await !source(fixture, repository: reopened).isCovered)+ let restartedModel = CharacterExtractionCoordinatorTests.MutableAvailabilityClient(.available,+ inner: .init(result: .init(places: [])))+ let restarted = CharacterExtractionCoordinator(library: reopened, model: restartedModel,+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ await restarted.runManualPass(workID: fixture.workID)+ #expect(restarted.held(for: fixture.workID).map(\.key) == [.init(kind: .place, nameKey: "bryn")],+ "A guarded literal pending place is reconstructed for its still-required decision")+ #expect(try await !source(fixture, repository: reopened).isCovered,+ "An empty answer after restart cannot silently decide previously observed B")+ restartedModel.inner = client("Bryn")+ await restarted.runManualPass(workID: fixture.workID)+ #expect(restarted.held(for: fixture.workID).map(\.nameKey) == ["bryn"])+ let last = try await review(fixture, coordinator: restarted, library: reopened)+ await last.accept(try #require(last.rows.first).id)+ #expect(last.rows.isEmpty)+ #expect(try await source(fixture, repository: reopened).isCovered,+ "An explicit decision on reproduced B resolves its equivalent pending markers and permits certification")+ await reopened.shutdown(); await fixture.repository.shutdown()+ }+ @Test("A failed durable pending write never publishes its proposals or advances coverage")+ func failedPendingSaveDoesNotPublishHeldResults() async throws {+ let fixture = try await Fixture()+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let proxy = MockLibraryProvider()+ proxy.extractionCandidatesResult = .success(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [fixture.workID]))+ proxy.pendingMentionReviewHandler = { _ in throw CocoaError(.fileWriteUnknown) }+ let recorder = StubCharacterExtractionModelClient.Recorder()+ let model = StubCharacterExtractionModelClient(result: .init(places: [.init(name: "Bryn", facts: [])]), recorder: recorder)+ let coordinator = CharacterExtractionCoordinator(library: proxy, model: model,+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ await coordinator.runManualPass(workID: fixture.workID)+ #expect(recorder.callCount == 1)+ #expect(coordinator.held(for: fixture.workID).isEmpty)+ #expect(coordinator.manualOutcome(for: fixture.workID) == .noProposals)+ #expect(proxy.advancedCoverage.isEmpty)+ #expect(try await !source(fixture).isCovered)+ await fixture.repository.shutdown()+ }++}
diff --git a/Asterism/AsterismTests/AssociationNoteEditorTests.swift b/Asterism/AsterismTests/AssociationNoteEditorTests.swiftnew file mode 100644index 00000000..52d78426--- /dev/null+++ b/Asterism/AsterismTests/AssociationNoteEditorTests.swift@@ -0,0 +1,142 @@+// Save-terminal note draft and detached-context contracts.+import AsterismCore+import Foundation+import Testing+@testable import Asterism++@Suite("Chapter link note draft editor")+struct AssociationNoteEditorTests {+ @MainActor private func fixture(headTexts: [String] = ["Café"]) -> (AssociationNoteEditorModel, MockLibraryProvider, AssociationNoteBasis) {+ let pair = AssociationPair(workID: UUID(), entryID: UUID(), kind: .character, recordID: UUID())+ let acceptance = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: ["alice"])))+ let current = AssociationCurrentPair(pair: pair, sourceFingerprint: "source", matchingFingerprint: "target",+ evidence: [.init(key: "alice", spelling: "Alice")])+ let ledger = AssociationLedgerInventory(events: [acceptance])+ let basis = AssociationNoteBasis(pair: pair, acceptanceIDs: [acceptance.id], validationReceipt: ledger.receipt(for: current),+ heads: headTexts.map { .init(pair: pair, attachmentAcceptanceIDs: [acceptance.id], text: $0, originalContext: "Chapter • Alice") },+ originalContext: "Chapter • Alice")+ let mock = MockLibraryProvider()+ mock.associationNoteBasisResult = .success(basis)+ mock.associationNoteWriteResult = .success(.committed)+ return (AssociationNoteEditorModel(pair: pair, library: mock), mock, basis)+ }+ @Test @MainActor func editingAndCancellingNeverWrites() async {+ let (model, mock, basis) = fixture()+ await model.load(); model.draftText = "Unsaved exact draft"+ #expect(model.hasUnsavedChanges)+ #expect(mock.associationNoteWrites.isEmpty)+ if case .success(let saved) = mock.associationNoteBasisResult { #expect(saved == basis) }+ else { Issue.record("Loading/editing must not mutate configured saved basis") }+ }+ @Test @MainActor func canonicallyEquivalentDraftIsMeaningfulAndSavePreservesExactBytes() async {+ let (model, mock, basis) = fixture()+ await model.load(); model.draftText = "Cafe\u{301}"+ #expect(model.hasUnsavedChanges && model.canSave)+ #expect(await model.save())+ #expect(mock.associationNoteWrites.count == 1)+ #expect(mock.associationNoteWrites.first?.basis == basis)+ #expect(mock.associationNoteWrites.first.map { Data($0.text.utf8) } == Data("Cafe\u{301}".utf8))+ }+ @Test("Refusal preserves exact draft and basis", arguments: [AssociationNoteWriteOutcome.reviewRequired, .inactive, .invalidMetadata])+ @MainActor func refusalKeepsDraftAndCapturedBasis(outcome: AssociationNoteWriteOutcome) async {+ let (model, mock, basis) = fixture()+ await model.load(); let draft = " Cafe\u{301}\nexact draft "; model.draftText = draft+ mock.associationNoteWriteResult = .success(outcome)+ #expect(!(await model.save()))+ #expect(Data(model.draftText.utf8) == Data(draft.utf8))+ #expect(model.basis == basis && model.message != nil)+ }+ @Test @MainActor func failureKeepsDraftAndCapturedBasis() async {+ let (model, mock, basis) = fixture()+ await model.load(); model.draftText = "Untouched failed draft"+ mock.associationNoteWriteResult = .failure(CocoaError(.fileWriteUnknown))+ #expect(!(await model.save()))+ #expect(model.draftText == "Untouched failed draft" && model.basis == basis)+ #expect(model.message != nil)+ }+ @Test @MainActor func explicitReviewReplacesBasisButKeepsDraftAndDisplaysEveryHead() async {+ let (model, mock, basis) = fixture()+ await model.load(); model.draftText = "My exact draft"+ var latest = basis+ latest.heads = [.init(pair: basis.pair, attachmentAcceptanceIDs: Array(basis.acceptanceIDs), text: "Concurrent text")]+ mock.associationNoteBasisResult = .success(latest)+ await model.load(preservingDraft: true)+ #expect(model.draftText == "My exact draft")+ #expect(model.basis == latest && model.displayedHeads == latest.heads)+ #expect(model.showsSavedHeads && model.canSave)+ #expect(mock.associationNoteWrites.isEmpty)+ }+ @Test @MainActor func differingHeadsHaveNoImplicitWinningDraft() async {+ let (model, mock, basis) = fixture(headTexts: ["First exact text", "Other exact text"])+ await model.load()+ #expect(model.displayedHeads == basis.heads && model.draftText.isEmpty)+ #expect(!model.canSave && model.canClear && mock.associationNoteWrites.isEmpty)+ }+ @Test @MainActor func stagedClearWritesOnlyAtTerminalSaveExactlyOnce() async {+ let (model, mock, basis) = fixture()+ await model.load(); model.stageClear()+ #expect(model.intendsClear && model.draftText.isEmpty && model.canSave)+ #expect(mock.associationNoteClears.isEmpty && mock.associationNoteWrites.isEmpty)+ #expect(model.displayedHeads == basis.heads)+ #expect(await model.save())+ #expect(mock.associationNoteClears == [basis] && mock.associationNoteWrites.isEmpty)+ #expect(model.isLoaded && !model.isLoading && !model.canEdit && !model.canSave)+ #expect(!(await model.save()))+ #expect(mock.associationNoteClears.count == 1)+ }+ @Test @MainActor func stagedClearThenCancelPreservesSavedHeadsAndWritesNothing() async {+ let (model, mock, basis) = fixture()+ await model.load(); model.stageClear()+ #expect(model.displayedHeads == basis.heads && model.basis == basis)+ #expect(mock.associationNoteClears.isEmpty && mock.associationNoteWrites.isEmpty && mock.associationNoteRecoveries.isEmpty)+ if case .success(let saved) = mock.associationNoteBasisResult { #expect(saved?.heads == basis.heads) }+ else { Issue.record("A field Clear/Cancel must preserve saved heads") }+ }+ @Test @MainActor func initialDelayedLoadDisablesEditingAndSaveUntilBasisArrives() async throws {+ let (model, mock, _) = fixture()+ let gate = SubmissionGate(); mock.associationNoteBasisHold = gate+ let loading = Task { await model.load() }+ defer { loading.cancel(); gate.open() }+ for _ in 0..<1000 where mock.associationNoteBasisReadCount == 0 { await Task.yield() }+ try #require(mock.associationNoteBasisReadCount == 1)+ #expect(!model.isLoaded && model.isLoading && !model.canEdit && !model.canSave && !model.canClear)+ #expect(mock.associationNoteWrites.isEmpty && mock.associationNoteClears.isEmpty)+ gate.open(); await loading.value+ #expect(model.isLoaded && !model.isLoading && model.canEdit && model.draftText == "Café")+ }+ @Test("Recovery exposes even one destination text or Clear head", arguments: [false, true])+ @MainActor func explicitRecoveryCarriesFullSelectedHeadsAndDoesNotWriteOnLoad(currentIsClear: Bool) async {+ let (_, mock, original) = fixture(headTexts: ["Newer active note"])+ var basis = original+ if currentIsClear { basis.heads = [.init(pair: basis.pair, attachmentAcceptanceIDs: Array(basis.acceptanceIDs), operation: .clear, text: "")] }+ mock.associationNoteBasisResult = .success(basis)+ let detached = AssociationNoteValue(pair: basis.pair, attachmentAcceptanceIDs: [UUID()], text: "Older exact note")+ let model = AssociationNoteEditorModel(pair: basis.pair, library: mock, selectedDetachedHeads: [detached])+ await model.load()+ #expect(model.draftText == detached.text && model.displayedHeads == basis.heads)+ #expect(model.displayedHeads.count == 1 && model.showsSavedHeads && model.canSave)+ #expect(mock.associationNoteRecoveries.isEmpty)+ #expect(await model.save())+ #expect(mock.associationNoteRecoveries.count == 1)+ #expect(mock.associationNoteRecoveries.first?.basis == basis)+ #expect(mock.associationNoteRecoveries.first?.heads == [detached])+ #expect(mock.associationNoteRecoveries.first?.text == detached.text)+ }+}++@Suite("Detached link note context")+struct DetachedAssociationNoteContextTests {+ @Test func decodesExactRawContextDespiteMalformedOtherMetadata() throws {+ let context = "Cafe\u{301} original chapter • character"+ let contextData = try JSONEncoder().encode(context)+ let malformed = Data([0xff]).base64EncodedString()+ let object: [String: Any] = ["id": UUID().uuidString, "workID": UUID().uuidString,+ "originPairData": malformed, "attachmentAcceptIDsData": malformed,+ "parentHeadIDsData": malformed, "operationRaw": "unrecognized", "text": "Recoverable exact text",+ "originalContextData": contextData.base64EncodedString(), "authoredAt": "0"]+ let raw = try JSONDecoder().decode(AssociationRawNote.self, from: JSONSerialization.data(withJSONObject: object))+ let visible = try #require(DetachedAssociationNotesModel.originalContext(raw: raw, head: nil))+ #expect(Data(visible.utf8) == Data(context.utf8))+ #expect(raw.originPairData == Data([0xff]) && raw.text == "Recoverable exact text")+ }+}
diff --git a/Asterism/AsterismTests/CharacterExtractionCoordinatorTests.swift b/Asterism/AsterismTests/CharacterExtractionCoordinatorTests.swiftindex 5e43a8ff..51918b4e 100644--- a/Asterism/AsterismTests/CharacterExtractionCoordinatorTests.swift+++ b/Asterism/AsterismTests/CharacterExtractionCoordinatorTests.swift@@ -313,7 +313,7 @@ struct CharacterExtractionCoordinatorTests { let held = coordinator.held(for: workID) #expect(held.count == 1) #expect(held.first?.name == "Ada")- #expect(held.first?.facts.count == 1)+ #expect(held.first?.facts.isEmpty == true, "New extraction is names-only even when a legacy stub supplies facts") #expect(coordinator.hasProposals(for: workID)) } @@ -434,7 +434,7 @@ struct CharacterExtractionCoordinatorTests { #expect(mock.advancedCoverage.isEmpty) } - @Test("A source whose whole output is filtered away still covers")+ @Test("A recognised non-chapter source settles without facts or an approval row") func filteredEmptyStillCovers() async { let workID = UUID() // The only fact the model offers is one the reader already accepted, so@@ -452,6 +452,7 @@ struct CharacterExtractionCoordinatorTests { ], acceptedFacts: [accepted]) ])+ mock.commitRecognisedCharacterHandler = { .committed(recordID: $0.displayedTargetID) } await coordinator.activationSweep()
diff --git a/Asterism/AsterismTests/CharacterReviewModelTests.swift b/Asterism/AsterismTests/CharacterReviewModelTests.swiftindex 52df1dc7..b1878e96 100644--- a/Asterism/AsterismTests/CharacterReviewModelTests.swift+++ b/Asterism/AsterismTests/CharacterReviewModelTests.swift@@ -718,6 +718,35 @@ struct CharacterReviewModelTests { #expect(Set(sources.map(\.ref)) == Set([.genericNotes, .entry(entryID)])) } + @Test("A held sibling arriving after the sheet opens withholds mention coverage")+ func unseenCurrentHeldSiblingWithholdsCoverageUntilItsOwnDecision() async throws {+ let work = UUID(), entry = UUID(), targetA = UUID(), targetB = UUID()+ var first = Self.candidate(facts: [], target: .existing(targetA), revisions: [.entry(entry): "raw"])+ first.mentions = [.init(entryID: entry, noteFingerprint: "raw", spellingKeys: ["ada"])]+ first.citedMentionEligibility = [.entry(entry): "whole-basis"]+ var sibling = Self.candidate(name: "Bryn", key: "bryn", facts: [], target: .existing(targetB),+ revisions: [.entry(entry): "raw"])+ sibling.mentions = [.init(entryID: entry, noteFingerprint: "raw", spellingKeys: ["bryn"])]+ sibling.citedMentionEligibility = [.entry(entry): "whole-basis"]+ var held = [first]+ let mock = MockLibraryProvider()+ let model = CharacterReviewModel(workID: work, proposals: [first],+ characters: [Self.character(id: targetA), Self.character(id: targetB, name: "Bryn")],+ library: mock, extractionContext: { nil }, onDecision: { key, _ in held.removeAll { $0.key == key } },+ onReRoute: { _, _ in }, onReclassify: { _, _, _ in }, refresh: { held }, currentHeld: { held })+ held.append(sibling) // A second window/manual pass settles after A opened.+ await model.accept(try #require(model.rows.first).id)+ #expect(mock.committedDecisions.first?.completedSources.first?.mentionEligibilityDigest == nil)+ #expect(held.map(\.nameKey) == ["bryn"])+ let next = CharacterReviewModel(workID: work, proposals: held,+ characters: [Self.character(id: targetB, name: "Bryn")], library: mock,+ extractionContext: { nil }, onDecision: { key, _ in held.removeAll { $0.key == key } },+ onReRoute: { _, _ in }, onReclassify: { _, _, _ in }, refresh: { held }, currentHeld: { held })+ await next.accept(try #require(next.rows.first).id)+ #expect(mock.committedDecisions.last?.completedSources.first?.mentionEligibilityDigest == "whole-basis")+ #expect(held.isEmpty)+ }+ // MARK: - Committing (Req 2.2, 2.5) @Test("A committed decision leaves the sheet and tells the coordinator which row it was")
diff --git a/Asterism/AsterismTests/EntryDetailAssociationPublicationTests.swift b/Asterism/AsterismTests/EntryDetailAssociationPublicationTests.swiftnew file mode 100644index 00000000..5a3a1d1a--- /dev/null+++ b/Asterism/AsterismTests/EntryDetailAssociationPublicationTests.swift@@ -0,0 +1,161 @@+import AsterismCore+import AsterismTestSupport+import Foundation+import SwiftData+import Testing+@testable import Asterism++@Suite("Entry detail association publication") @MainActor+struct EntryDetailAssociationPublicationTests {+ private func fixture() -> (EntryDetailModel, MockLibraryProvider, ChapterAssociationSnapshot) {+ let mock = MockLibraryProvider()+ let work = UUID()+ let entry = TestFixtures.makeEntry(note: "Chapter's saved note", rating: .up, workID: work)+ let pair = AssociationPair(workID: work, entryID: entry.id, kind: .character, recordID: UUID())+ let acceptance = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: ["alice"])))+ let current = AssociationCurrentPair(pair: pair, sourceFingerprint: "source", matchingFingerprint: "matching",+ evidence: [.init(key: "alice", spelling: "Alice")])+ let receipt = AssociationLedgerInventory(events: [acceptance]).receipt(for: current)+ let link = ChapterAssociationSnapshot(pair: pair, recordName: "Alice", chapterTitle: "Chapter",+ evidence: current.evidence, activeAcceptanceIDs: [acceptance.id], validationReceipt: receipt)+ mock.entryTeachingDetailResult = .success(.init(entry: entry, siteMode: .untaught,+ activePatternSummary: nil, historicalPatternSummaries: [], chapterSettlement: .manualProtected(reason: "Fixture"),+ assignmentSettlement: .manualProtected(reason: "Fixture"), availableActions: [], unresolvedCandidateTitle: nil,+ chapterAssociations: [link]))+ let model = EntryDetailModel(entryID: entry.id, library: mock, onMutation: {})+ return (model, mock, link)+ }+ @Test func successfulChapterSavePublishesBothKnownKindsThroughRealAppFactory() async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("save-known-publication-\(UUID())")+ let config = LibraryConfiguration(rootDirectory: root)+ try FileManager.default.createDirectory(at: config.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try autoreleasepool {+ let container = try LibraryRepository.openContainer(at: config.storeURL)+ try ModelContext(container).save()+ }+ try LibraryRepository.publishReadiness(at: config.readinessMarkerURL)+ let (_, repo) = try await LibraryRepository.openForApp(config, capabilities: .current)+ try await repo.seedAssociationNotesFixture()+ let workID = UUID(uuidString: "24680000-0000-4000-8000-000000000001")!+ let entryID = LibraryRepository.associationFixtureRecoveryChapterID+ let characterID = UUID(uuidString: "24680000-0000-4000-8000-000000000004")!+ let placeID = UUID(uuidString: "24680000-0000-4000-8000-000000000005")!+ let original = try await repo.workDetail(id: workID)+ let owner = AppLibraryModel(readyRepository: repo)+ let model = try #require(owner.entryDetailModel(for: entryID))+ await model.load()+ #expect(Set(model.chapterAssociations.map(\.pair.recordID)) == [characterID, placeID])+ let beforeRemoval = owner.snapshotGeneration+ model.draftNote = "Nobody visits."+ #expect(await model.update())+ #expect(owner.snapshotGeneration > beforeRemoval && model.chapterAssociations.isEmpty)+ let retired = try await repo.chapterAssociations(entryID: entryID)+ #expect(retired.allSatisfy { $0.activeAcceptanceIDs.isEmpty })++ let exact = " ALICE visits HARBOR. Cafe\u{301} remains exact. "+ model.draftNote = exact+ #expect(model.chapterAssociations.isEmpty)+ let staged = try await repo.chapterAssociations(entryID: entryID)+ #expect(staged.allSatisfy { $0.activeAcceptanceIDs.isEmpty },+ "A staged draft cannot create either kind of link")+ #expect(try await repo.entry(id: entryID).note == "Nobody visits.")+ let beforeSave = owner.snapshotGeneration+ #expect(await model.update())+ #expect(owner.snapshotGeneration > beforeSave, "The real factory publishes the successful Save")+ #expect(Data(try #require(model.entry).note.utf8) == Data(exact.utf8))+ #expect(Set(model.chapterAssociations.map(\.pair.kind)) == [.character, .place])+ #expect(Set(model.chapterAssociations.map(\.pair.recordID)) == [characterID, placeID])+ let work = try #require(owner.workDetailModel(for: workID))+ await work.load()+ for (kind, recordID) in [(RecordKind.character, characterID), (.place, placeID)] {+ await work.selectRecordHistory(kind: kind, recordID: recordID)+ let history = try #require(work.recordHistory)+ #expect(history.activeChapterCount == 2 && history.availability == .available)+ let row = try #require(history.rows.first { $0.id.entryID == entryID })+ let body = try #require(history.detail(for: row.id, expectedGeneration: history.generation))+ #expect(Data(body.sourceText.utf8) == Data(exact.utf8))+ }+ let saved = try await repo.workDetail(id: workID)+ #expect(saved.characters == original.characters && saved.places == original.places,+ "Save retains existing identities, names, aliases, legacy facts and record notes")+ }++ @Test func explicitRestorePublishesWithoutReplacingTheParentChapterDraft() async throws {+ let (model, mock, link) = fixture()+ await model.load()+ let exact = " Cafe\u{301}\nunsaved source "+ model.draftNote = exact; model.draftTitle = "Unsaved title"; model.draftRating = .down+ let captured = SkippedCharacterLinkSnapshot(pair: link.pair, recordName: "Alice", matchingName: "Alice",+ spellingKeys: ["alice"], observedRejectionIDs: [UUID()], noteFingerprint: "saved", sourceGuard: "guard", targetFingerprint: "target")+ mock.skippedCharacterLinksResult = .success([captured])+ mock.restoreCharacterLinkResult = .success(.committed(recordID: link.pair.recordID))+ mock.chapterAssociationsResult = .success([link])+ let child = model.skippedCharacterLinksModel()+ await child.load(); await child.restore(captured)+ #expect(mock.restoredCharacterLinks == [captured] && child.links.isEmpty)+ #expect(model.chapterAssociations == [link] && mock.chapterAssociationReadCount == 1)+ #expect(Data(model.draftNote.utf8) == Data(exact.utf8))+ #expect(model.draftTitle == "Unsaved title" && model.draftRating == .down)+ #expect(mock.entryTeachingDetailCallCount == 1)+ }++ @Test func initialDetailUsesItsCoherentLinkValuesWithoutASecondRead() async {+ let (model, mock, link) = fixture()+ await model.load()+ #expect(model.chapterAssociations == [link])+ #expect(mock.entryTeachingDetailCallCount == 1 && mock.chapterAssociationReadCount == 0)+ }+ @Test func narrowMetadataRefreshPreservesEveryUnsavedChapterDraft() async {+ let (model, mock, _) = fixture()+ await model.load()+ let entry = model.entry+ model.draftTitle = "Unsaved chapter title"; model.draftSourceURL = "https://draft.test/source"+ model.draftNote = " Cafe\u{301}\nunsaved chapter draft "; model.draftRating = .down+ mock.chapterAssociationsResult = .success([])+ await model.refreshAssociations()+ #expect(model.chapterAssociations.isEmpty && model.entry == entry)+ #expect(model.draftTitle == "Unsaved chapter title" && model.draftSourceURL == "https://draft.test/source")+ #expect(Data(model.draftNote.utf8) == Data(" Cafe\u{301}\nunsaved chapter draft ".utf8) && model.draftRating == .down)+ #expect(mock.entryTeachingDetailCallCount == 1 && mock.chapterAssociationReadCount == 1)+ }+ @Test func cancelledOldReadCannotOverwriteLaterPublishedAssociationValues() async throws {+ let (model, mock, link) = fixture()+ await model.load()+ let gate = SubmissionGate(); mock.chapterAssociationsHold = gate+ mock.chapterAssociationsResult = .success([link])+ let old = Task { await model.refreshAssociations() }+ defer { old.cancel(); gate.open() }+ for _ in 0..<1000 where mock.chapterAssociationReadCount == 0 { await Task.yield() }+ try #require(mock.chapterAssociationReadCount == 1)+ mock.chapterAssociationsHold = nil; mock.chapterAssociationsResult = .success([])+ await model.refreshAssociations()+ old.cancel(); gate.open(); await old.value+ #expect(model.chapterAssociations.isEmpty)+ }+ @Test func cancelledInitialLoadCannotReplaceTheLatestGeneration() async throws {+ let (model, mock, _) = fixture()+ let gate = SubmissionGate(); mock.entryTeachingDetailHold = gate+ let old = Task { await model.load() }+ defer { old.cancel(); gate.open() }+ for _ in 0..<1000 where mock.entryTeachingDetailCallCount == 0 { await Task.yield() }+ try #require(mock.entryTeachingDetailCallCount == 1)+ let original = try mock.entryTeachingDetailResult.get()+ let latest = TestFixtures.makeEntry(id: original.entry.id, note: "Latest generation chapter", workID: original.entry.workID)+ mock.entryTeachingDetailHold = nil+ mock.entryTeachingDetailResult = .success(.init(entry: latest, siteMode: .untaught,+ activePatternSummary: nil, historicalPatternSummaries: [], chapterSettlement: .unsettled(reason: "Fixture"),+ assignmentSettlement: .unsettled(reason: "Fixture"), availableActions: [], unresolvedCandidateTitle: nil,+ chapterAssociations: []))+ old.cancel(); await model.load(); gate.open(); await old.value+ #expect(model.entry == latest && model.chapterAssociations.isEmpty)+ #expect(model.draftNote == "Latest generation chapter")+ }+ @Test func zeroEffectReconciliationStillPublishesAnArrivalGeneration() async {+ let mock = MockLibraryProvider()+ let app = AppLibraryModel(readyRepository: mock)+ let before = app.snapshotGeneration+ await app.handleSyncArrivals()+ #expect(mock.reconcileAfterSyncCallCount == 1)+ #expect(app.snapshotGeneration > before)+ }+}
diff --git a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swiftindex 7894b99d..956ff320 100644--- a/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift+++ b/Asterism/AsterismTests/Helpers/MockLibraryProvider.swift@@ -386,6 +386,16 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { var sitesResult: Result<[SiteSnapshot], Error> = .success([]) var siteNamesResult: Result<[String: String], Error> = .success([:])+ var recordHistoryResult: Result<RecordHistorySnapshot, Error> = .failure(MockError.notConfigured)+ var recordHistoryHandler: (@Sendable (RecordHistorySelection) async throws -> RecordHistorySnapshot)?+ private var storedRecordHistoryCalls: [RecordHistorySelection] = []+ var recordHistoryCalls: [RecordHistorySelection] { recorderLock.withLock { storedRecordHistoryCalls } }+ func recordHistory(workID: UUID, kind: RecordKind, recordID: UUID) async throws -> RecordHistorySnapshot {+ let selection = RecordHistorySelection(workID: workID, kind: kind, recordID: recordID)+ recorderLock.withLock { storedRecordHistoryCalls.append(selection) }+ if let recordHistoryHandler { return try await recordHistoryHandler(selection) }+ return try recordHistoryResult.get()+ } var workDetailResult: Result<WorkDetailPresentation, Error> = .failure(MockError.notConfigured) var entryExportInputResult: Result<EntryExportInput, Error> = .failure(MockError.notConfigured) var workExportInputResult: Result<WorkExportInput, Error> = .failure(MockError.notConfigured)@@ -483,6 +493,23 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { return rows.filter { hostnames.contains($0.hostname) } } + var skippedCharacterLinksHandler: (@Sendable (UUID) async throws -> [SkippedCharacterLinkSnapshot])?+ private var storedSkippedLinkReads = 0+ var skippedLinkReadCount: Int { recorderLock.withLock { storedSkippedLinkReads } }+ var skippedCharacterLinksResult: Result<[SkippedCharacterLinkSnapshot], Error> = .failure(MockError.notConfigured)+ var restoreCharacterLinkResult: Result<DecisionOutcome, Error> = .failure(MockError.notConfigured)+ private var storedRestoredCharacterLinks: [SkippedCharacterLinkSnapshot] = []+ var restoredCharacterLinks: [SkippedCharacterLinkSnapshot] { recorderLock.withLock { storedRestoredCharacterLinks } }+ func skippedCharacterLinks(entryID: UUID) async throws -> [SkippedCharacterLinkSnapshot] {+ recorderLock.withLock { storedSkippedLinkReads += 1 }+ if let skippedCharacterLinksHandler { return try await skippedCharacterLinksHandler(entryID) }+ return try skippedCharacterLinksResult.get()+ }+ func restoreCharacterLink(_ captured: SkippedCharacterLinkSnapshot) async throws -> DecisionOutcome {+ recorderLock.withLock { storedRestoredCharacterLinks.append(captured) }+ return try restoreCharacterLinkResult.get()+ }+ // MARK: - Character extraction /// Recorded under `recorderLock` for the same reason the rule-suggestion@@ -490,10 +517,12 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { /// these at once. var extractionCandidatesResult: Result<[ExtractionCandidate], Error> = .success([])+ var pendingMentionReviewHandler: (@Sendable ([AssociationPendingReviewRequest]) async throws -> [AssociationPendingReviewResult])? var advanceCoverageResult: Result<Int, Error> = .success(1) /// Awaited inside `commitDecision` before it returns, so a test /// can hold one decision in flight while probing the model's gate. var commitDecisionHold: (@Sendable () async -> Void)?+ var commitDecisionHandler: (@Sendable (DecisionRequest) async throws -> DecisionOutcome)? var commitDecisionResult: Result<DecisionOutcome, Error> = .success(.committed(recordID: nil)) var commitRecordEditsResult: Result<RecordEditOutcome, Error> =@@ -552,6 +581,15 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { .prefix(limit)) } + func recordPendingMentionReviews(_ requests: [AssociationPendingReviewRequest]) async throws -> [AssociationPendingReviewResult] {+ if let handler = pendingMentionReviewHandler { return try await handler(requests) }+ return requests.map { request in+ .init(workID: request.marker.workID, entryID: request.marker.entryID,+ completionDigest: request.originalEligibilityDigest,+ references: request.marker.items.map { .init(markerID: request.markerID, key: $0.key) })+ }+ }+ @discardableResult func advanceCoverage( workID: UUID, sources: [CompletedSource]@@ -563,6 +601,24 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { return try advanceCoverageResult.get() } + var commitRecognisedCharacterHandler: (@Sendable (DecisionRequest) async throws -> DecisionOutcome)?+ var recognisedCharacterRequests: [DecisionRequest] { recorderLock.withLock { storedRecognisedCharacterRequests } }+ private var storedRecognisedCharacterRequests: [DecisionRequest] = []+ var commitReclassifiedRecognisedCharacterHandler: (@Sendable (DecisionRequest) async throws -> DecisionOutcome)?+ func commitReclassifiedRecognisedCharacter(_ request: DecisionRequest) async throws -> DecisionOutcome {+ if let handler = commitReclassifiedRecognisedCharacterHandler { return try await handler(request) }+ throw MockError.notConfigured+ }+ func commitRecognisedCharacter(_ request: DecisionRequest) async throws -> DecisionOutcome {+ recorderLock.withLock {+ storedRecognisedCharacterRequests.append(request)+ callLog.append("commitRecognisedCharacter")+ }+ if let handler = commitRecognisedCharacterHandler { return try await handler(request) }+ // A double must opt into successful persistence explicitly.+ throw MockError.notConfigured+ }+ func commitDecision( _ request: DecisionRequest ) async throws -> DecisionOutcome {@@ -571,6 +627,7 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { callLog.append("commitDecision") } if let hold = commitDecisionHold { await hold() }+ if let handler = commitDecisionHandler { return try await handler(request) } return try commitDecisionResult.get() } @@ -667,10 +724,72 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { return try commitWorkDeletionResult.get() } + // MARK: - Saved chapter association values and note writes++ struct AssociationNoteWrite: Equatable, Sendable { var basis: AssociationNoteBasis; var text: String }+ struct AssociationNoteRecovery: Equatable, Sendable { var basis: AssociationNoteBasis; var heads: [AssociationNoteValue]; var text: String }+ var chapterAssociationsResult: Result<[ChapterAssociationSnapshot], Error> = .success([])+ var chapterAssociationsHold: SubmissionGate?+ var associationNoteBasisResult: Result<AssociationNoteBasis?, Error> = .success(nil)+ var associationNoteBasisHold: SubmissionGate?+ var associationNoteWriteResult: Result<AssociationNoteWriteOutcome, Error> = .failure(MockError.notConfigured)+ var associationNoteWriteHold: SubmissionGate?+ var detachedAssociationNotesResult: Result<[DetachedAssociationNoteSnapshot], Error> = .success([])+ private var storedChapterAssociationReadCount = 0+ private var storedAssociationNoteBasisReadCount = 0+ private var storedAssociationNoteWrites: [AssociationNoteWrite] = []+ private var storedAssociationNoteClears: [AssociationNoteBasis] = []+ private var storedAssociationNoteRecoveries: [AssociationNoteRecovery] = []+ var chapterAssociationReadCount: Int { recorderLock.withLock { storedChapterAssociationReadCount } }+ var associationNoteBasisReadCount: Int { recorderLock.withLock { storedAssociationNoteBasisReadCount } }+ var associationNoteWrites: [AssociationNoteWrite] { recorderLock.withLock { storedAssociationNoteWrites } }+ var associationNoteClears: [AssociationNoteBasis] { recorderLock.withLock { storedAssociationNoteClears } }+ var associationNoteRecoveries: [AssociationNoteRecovery] { recorderLock.withLock { storedAssociationNoteRecoveries } }+ func chapterAssociations(entryID: UUID) async throws -> [ChapterAssociationSnapshot] {+ let (result, hold) = recorderLock.withLock {+ storedChapterAssociationReadCount += 1+ return (chapterAssociationsResult, chapterAssociationsHold)+ }+ await hold?.wait(); return try result.get()+ }+ func associationNoteBasis(pair: AssociationPair) async throws -> AssociationNoteBasis? {+ let (result, hold) = recorderLock.withLock {+ storedAssociationNoteBasisReadCount += 1+ return (associationNoteBasisResult, associationNoteBasisHold)+ }+ await hold?.wait(); return try result.get()+ }+ func saveAssociationNote(basis: AssociationNoteBasis, text: String) async throws -> AssociationNoteWriteOutcome {+ let (result, hold) = recorderLock.withLock {+ storedAssociationNoteWrites.append(.init(basis: basis, text: text))+ return (associationNoteWriteResult, associationNoteWriteHold)+ }+ await hold?.wait(); return try result.get()+ }+ func clearAssociationNote(basis: AssociationNoteBasis) async throws -> AssociationNoteWriteOutcome {+ let (result, hold) = recorderLock.withLock {+ storedAssociationNoteClears.append(basis)+ return (associationNoteWriteResult, associationNoteWriteHold)+ }+ await hold?.wait(); return try result.get()+ }+ func recoverAssociationNotes(basis: AssociationNoteBasis, selectedHeads: [AssociationNoteValue], text: String) async throws -> AssociationNoteWriteOutcome {+ let (result, hold) = recorderLock.withLock {+ storedAssociationNoteRecoveries.append(.init(basis: basis, heads: selectedHeads, text: text))+ return (associationNoteWriteResult, associationNoteWriteHold)+ }+ await hold?.wait(); return try result.get()+ }+ func detachedAssociationNotes() async throws -> [DetachedAssociationNoteSnapshot] {+ try detachedAssociationNotesResult.get()+ }+ // MARK: - Teaching contract stubs var entryTeachingDetailResult: Result<EntryTeachingDetail, Error> = .failure(MockError.notConfigured)- var entryTeachingDetailCallCount = 0+ private var storedEntryTeachingDetailCallCount = 0+ var entryTeachingDetailCallCount: Int { recorderLock.withLock { storedEntryTeachingDetailCallCount } }+ var entryTeachingDetailHold: SubmissionGate? var projectInitialTeachingResult: Result<TeachingContract, Error> = .failure(MockError.notConfigured) var projectInitialTeachingCallCount = 0@@ -705,8 +824,11 @@ final class MockLibraryProvider: LibraryProviding, @unchecked Sendable { var lastCommittedCaptureContract: CaptureContract? func entryTeachingDetail(id: UUID) async throws -> EntryTeachingDetail {- entryTeachingDetailCallCount += 1- return try entryTeachingDetailResult.get()+ let (result, hold) = recorderLock.withLock {+ storedEntryTeachingDetailCallCount += 1+ return (entryTeachingDetailResult, entryTeachingDetailHold)+ }+ await hold?.wait(); return try result.get() } // MARK: - Diagnoses (Req 1.5, 4.2)
diff --git a/Asterism/AsterismTests/HiddenLegacyFactsTests.swift b/Asterism/AsterismTests/HiddenLegacyFactsTests.swiftnew file mode 100644index 00000000..23601b3b--- /dev/null+++ b/Asterism/AsterismTests/HiddenLegacyFactsTests.swift@@ -0,0 +1,90 @@+import AsterismCore+import Foundation+import SwiftData+import Testing+@testable import Asterism++@Suite("Hidden legacy facts retain saved data", .serialized) @MainActor+struct HiddenLegacyFactsTests {+ @Test(arguments: [0, 1, 2])+ func unrelatedSaveCancelConversionAndCombineRetainLegacyBytes(operation: Int) async throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent("hidden-facts-\(UUID())")+ let config = LibraryConfiguration(rootDirectory: root)+ try FileManager.default.createDirectory(at: config.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try autoreleasepool { let container = try LibraryRepository.openContainer(at: config.storeURL); try ModelContext(container).save() }+ try LibraryRepository.publishReadiness(at: config.readinessMarkerURL)+ let (_, repo) = try await LibraryRepository.openForApp(config, capabilities: .current)+ let work = try await repo.createWork(.init(displayTitle: "Legacy reader", hostname: ""))+ let fact = RecordFact(statement: " Cafe\u{301}\nlegacy statement ", quote: " Cafe\u{301} exact quote ", nameKey: "ada", source: .entry(UUID()))+ let suppressed = RecordFact(statement: "Not shown", quote: "retained suppression", nameKey: "ada", source: .genericNotes)+ let accepted = try await repo.commitDecision(.init(workID: work.id, kind: .character, action: .accept,+ displayedKeys: ["ada"], proposedName: "Ada", proposedAliases: ["Nightjar"], facts: [fact], untickedFacts: [suppressed.identity]))+ guard case .committed(let acceptedID) = accepted else { Issue.record("Synthetic legacy seed refused"); return }+ let adaID = try #require(acceptedID)+ let originalSuppressions = try suppressionValues(at: config.storeURL)+ let model = makeWorkDetailModel(workID: work.id, library: repo)+ await model.load(); model.beginEditing()+ let original = try #require(model.recordDraft(for: adaID))+ #expect(original.facts == [fact])+ model.updateRecordDraft(id: adaID) { $0.note = "Discarded record note" }+ model.cancelEditing()+ model.beginEditing()+ #expect(model.recordDraft(for: adaID) == original)+ model.updateRecordDraft(id: adaID) { $0.note = "Reader note" }+ await model.commitEditing()+ #expect(!model.isEditing)+ let saved = try await repo.workDetail(id: work.id)+ let unchanged = try #require(saved.characters.first { $0.id == adaID })+ #expect(RecordFactCodec.encode(unchanged.facts.map(\.fact)) == RecordFactCodec.encode([fact]))+ // Unrelated saves cannot silently turn hidden facts into deletions or suppressions.+ let suppressionCount = try autoreleasepool {+ let container = try LibraryRepository.openContainer(at: config.storeURL)+ return try ModelContext(container).fetch(FetchDescriptor<CharacterSuppression>()).filter { $0.evidence == suppressed.quote }.count+ }+ #expect(suppressionCount == 1)+ #expect(try suppressionValues(at: config.storeURL) == originalSuppressions)+ var combinedTargetID: UUID?+ if operation == 1 {+ model.beginEditing(); model.convertRecord(id: adaID); await model.commitEditing()+ } else if operation == 2 {+ let created = try await repo.commitRecordEdits(workID: work.id, operations: [.create(.init(kind: .character, name: "Bryn"))])+ guard case .committed = created else { Issue.record("Synthetic target refused"); return }+ await model.load(); model.beginEditing()+ let target = try #require(model.characters.first { $0.name == "Bryn" })+ combinedTargetID = target.id+ model.combineRecord(source: adaID, into: target.id); await model.commitEditing()+ }+ let detail = try await repo.workDetail(id: work.id)+ #expect(!model.isEditing, "Each requested operation committed and left edit mode")+ let record: WorkRecordPresentation+ if operation == 1 {+ #expect(!detail.characters.contains { $0.id == adaID })+ record = try #require(detail.places.first { $0.name == "Ada" })+ #expect(record.id != adaID, "Conversion created the destination-kind identity")+ } else if operation == 2 {+ #expect(!detail.characters.contains { $0.id == adaID })+ let targetID = try #require(combinedTargetID)+ record = try #require(detail.characters.first { $0.id == targetID })+ #expect(record.name == "Bryn" && detail.characters.count == 1)+ } else {+ record = try #require(detail.characters.first { $0.id == adaID })+ }+ let retained = try #require(record.facts.first)+ #expect(Data(retained.fact.statement.utf8) == Data(fact.statement.utf8))+ #expect(Data(retained.fact.quote.utf8) == Data(fact.quote.utf8))+ #expect(retained.fact.source == fact.source)+ #expect(record.aliases.contains("Nightjar"))+ }+ private func suppressionValues(at url: URL) throws -> [String] {+ try autoreleasepool {+ let container = try LibraryRepository.openContainer(at: url)+ let context = ModelContext(container)+ return try context.fetch(FetchDescriptor<CharacterSuppression>()).map { row in+ [row.id.uuidString, row.kindRaw, row.nameKey, row.sourceKindRaw ?? "nil",+ row.sourceEntryID?.uuidString ?? "nil", row.evidence ?? "nil", row.statusRaw,+ String(row.actionAt.timeIntervalSince1970.bitPattern)].joined(separator: "\u{1F}")+ }.sorted()+ }+ }++}
diff --git a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift b/Asterism/AsterismTests/IntegrationSafetyNetTests.swiftindex dfff7599..03590d92 100644--- a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift+++ b/Asterism/AsterismTests/IntegrationSafetyNetTests.swift@@ -155,10 +155,10 @@ struct IntegrationSafetyNetTests { , calendar: .current) let stagingDirectory = fixture.baseDirectory.appending(path: "validated-backups")- let exporter = BackupV18Exporter(repository: repository, stagingDirectory: stagingDirectory)+ let exporter = BackupV20Exporter(repository: repository, stagingDirectory: stagingDirectory) let exportedAt = Date(timeIntervalSince1970: 1_784_246_400) let result = try await exporter.export(- metadata: BackupV18Metadata(+ metadata: BackupV20Metadata( appBuild: "integration-1", exportedAt: exportedAt )@@ -166,19 +166,19 @@ struct IntegrationSafetyNetTests { defer { exporter.cleanup(result) } let encoded = try Data(contentsOf: result.fileURL)- let decoded = try BackupV18Codec.decode(encoded)- let source = try await repository.backupV18Snapshot()+ let decoded = try BackupV20Codec.decode(encoded)+ let source = try await repository.backupV20Snapshot() #expect(decoded.payload == source)- #expect(decoded.payload.entries.count == 1)- #expect(decoded.payload.works.count == 1)- #expect(decoded.payload.entries.first?.id == entry.id)- #expect(decoded.payload.entries.first?.note == "Preserve this note exactly — including Unicode.")- #expect(decoded.payload.entries.first?.workID == work.id)- #expect(decoded.payload.works.first?.displayTitle == "Constellation Work Revised")+ #expect(decoded.payload.library.entries.count == 1)+ #expect(decoded.payload.library.works.count == 1)+ #expect(decoded.payload.library.entries.first?.id == entry.id)+ #expect(decoded.payload.library.entries.first?.note == "Preserve this note exactly — including Unicode.")+ #expect(decoded.payload.library.entries.first?.workID == work.id)+ #expect(decoded.payload.library.works.first?.displayTitle == "Constellation Work Revised") // A 7/8 Work names no Entries (Req 9.3); the Entry names it, above.- #expect(decoded.payload.memberships.map(\.workID) == [work.id])- #expect(decoded.payload.sites.map { $0.hostname } == ["backup.test"])+ #expect(decoded.payload.library.memberships.map(\.workID) == [work.id])+ #expect(decoded.payload.library.sites.map { $0.hostname } == ["backup.test"]) } @Test("Every M2 gate stays consistent across Development and Personal")@@ -241,13 +241,13 @@ struct IntegrationSafetyNetTests { Issue.record("Expected Backup export for \(environment) \(capabilities.gate.rawValue)") continue }- // Settings writes 19/20 now: the archive has to carry+ // Settings writes 20/21 now: the archive has to carry // a Work's site memberships, the reader's dismissed pairs, // version-free citations and the Work's two statuses and // verdict, so the round-trip is reachable from the surface the // reader uses. The gate the file declares is still the running // one.- let document = try BackupV19Codec.decode(Data(contentsOf: backupURL))+ let document = try BackupV20Codec.decode(Data(contentsOf: backupURL)) #expect(document.capabilityGate == AsterismCapabilities.current.gate.rawValue) backup.shareDismissed() backup.handleShareOutcome(.cancelled)@@ -310,12 +310,12 @@ struct IntegrationSafetyNetTests { #expect(captured.captureTitle == "Post-setup chapter") } - @Test("Backup V3 fill into empty library produces correct records and readiness")+ @Test("Current backup fill into empty library produces correct records and readiness") func backupV3FillEmpty() async throws { let fixture = try IntegrationFixture() defer { fixture.cleanup() } - // Create a populated source library and export V3+ // Create a populated source library and export the current lossless format let sourceConfig = fixture.developmentConfiguration let sourceRepo = try await openAppRepository(sourceConfig) let entry = try await sourceRepo.capture(@@ -333,9 +333,9 @@ struct IntegrationSafetyNetTests { try await sourceRepo.moveEntry(entry.id, to: .existing(work.id)) let stagingDir = fixture.baseDirectory.appending(path: "export-stage")- let exporter = BackupV18Exporter(repository: sourceRepo, stagingDirectory: stagingDir)+ let exporter = BackupV20Exporter(repository: sourceRepo, stagingDirectory: stagingDir) let exportResult = try await exporter.export(- metadata: BackupV18Metadata(appBuild: "fill-test", exportedAt: Date())+ metadata: BackupV20Metadata(appBuild: "fill-test", exportedAt: Date()) ) defer { exporter.cleanup(exportResult) } let backupData = try Data(contentsOf: exportResult.fileURL)
diff --git a/Asterism/AsterismTests/NoteFirstCharacterRoutingTests.swift b/Asterism/AsterismTests/NoteFirstCharacterRoutingTests.swiftnew file mode 100644index 00000000..5cfddbb2--- /dev/null+++ b/Asterism/AsterismTests/NoteFirstCharacterRoutingTests.swift@@ -0,0 +1,425 @@+@testable import AsterismCore+import AsterismIntelligence+import Foundation+import SwiftData+import Synchronization+import Testing+@testable import Asterism++@Suite("Note-first character routing", .serialized)+@MainActor+struct NoteFirstCharacterRoutingTests {+ private enum FixtureError: Error { case refused }+ private struct Fixture: Sendable {+ let root: URL, configuration: LibraryConfiguration+ let repository: LibraryRepository+ let workID: UUID, entryID: UUID+ init(records: [RecordDraft], note: String = "Ada visits Bryn at Harbour.", sourceKind: Int = 0) async throws {+ root = FileManager.default.temporaryDirectory.appendingPathComponent("asterism-note-first-\(UUID())")+ configuration = LibraryConfiguration(rootDirectory: root)+ try FileManager.default.createDirectory(at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ let storeURL = configuration.storeURL+ try autoreleasepool {+ let container = try LibraryRepository.openContainer(at: storeURL)+ try ModelContext(container).save()+ }+ try LibraryRepository.publishReadiness(at: configuration.readinessMarkerURL)+ let (_, repo) = try await LibraryRepository.openForApp(configuration, capabilities: .current)+ repository = repo+ let work = try await repo.createWork(.init(displayTitle: "Synthetic note-first story", hostname: ""))+ workID = work.id+ let projection = try await repo.projectManualEntry(workID: work.id)+ guard case .committed(let chapter) = try await repo.commitManualEntry(projection: projection,+ draft: .init(target: sourceKind == 1 ? .init(kind: .note, title: "Standalone") : .init(kind: .chapter, title: "Arrival", designation: "1"),+ note: sourceKind == 2 ? "" : note, rating: sourceKind == 2 ? .up : nil, confirmedNewChapter: sourceKind != 1)) else { throw FixtureError.refused }+ entryID = chapter.id+ if sourceKind == 2 {+ let snapshot = try await repo.workDetail(id: work.id).work+ _ = try await repo.updateWork(id: work.id, basis: .init(work: snapshot),+ draft: .init(displayTitle: snapshot.displayTitle, typeAssignment: snapshot.typeDisplay.assignment, genreTags: snapshot.genreTags,+ genericNotes: note, publicationEdit: .unchanged, readingStatus: snapshot.readingStatus, verdict: snapshot.verdict,+ releaseDays: snapshot.releaseDays, membership: snapshot.membership, thumbnail: .keep), calendar: .current)+ }+ // These tests exercise extraction after directory arrival, rather+ // than the separate save-time lane. Record creation has no backfill.+ if !records.isEmpty {+ guard case .committed = try await repo.commitRecordEdits(workID: work.id, operations: records.map(RecordEditOperation.create)) else { throw FixtureError.refused }+ }+ try #require(try await repo.chapterAssociations(entryID: entryID).isEmpty,+ "Extraction must start with no chapter links after directory arrival")+ }+ }+ private func coordinator(_ fixture: Fixture, result: ExtractionResult) -> CharacterExtractionCoordinator {+ CharacterExtractionCoordinator(library: fixture.repository, model: StubCharacterExtractionModelClient(result: result),+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ }+ private func source(_ fixture: Fixture, repository: LibraryRepository? = nil) async throws -> CharacterExtractionSource {+ let read = try #require(try await (repository ?? fixture.repository).extractionCandidates(limit: 1, workIDs: [fixture.workID]).first)+ return try #require(read.sources.first { $0.ref == .entry(fixture.entryID) })+ }+ private func eventCount(_ fixture: Fixture) throws -> Int {+ try autoreleasepool {+ let container = try LibraryRepository.openContainer(at: fixture.configuration.storeURL)+ return try ModelContext(container).fetchCount(FetchDescriptor<AssociationEvent>())+ }+ }+ /// A chapter can arrive from sync before its independent association events.+ /// Seed that supported store state under the existing repository lock: this+ /// is not a reader Save and must not invoke save-time linking or erase links.+ private func insertIncomingChapter(_ fixture: Fixture) async throws -> UUID {+ let id = UUID(), workID = fixture.workID+ let stamp = try await fixture.repository.entry(id: fixture.entryID).modifiedAt.addingTimeInterval(1)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding incoming chapter") { context in+ let work = try #require(try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { $0.id == workID })).first)+ let row = Entry(id: id, captureTitle: "", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: stamp,+ note: "Bryn reaches Harbour.")+ try row.authorTarget(.init(kind: .chapter, title: "Second", designation: "2"))+ context.insert(row); row.work = work+ LibraryRepository.applyManualAssignment(to: row, at: stamp)+ try LibraryValidator.validateEntryTuple(entry: row, works: [work])+ try context.save()+ }+ let arrived = try await fixture.repository.entry(id: id)+ try #require(arrived.note == "Bryn reaches Harbour." && arrived.authoredTarget?.kind == .chapter,+ "The incoming source retains the exact original chapter note and eligibility")+ try #require(try await fixture.repository.chapterAssociations(entryID: id).isEmpty,+ "Incoming note evidence awaits its independent association decision")+ return id+ }+ @Test("Known current names, retained keys and accepted aliases save without review on automatic and manual passes", arguments: [0, 1, 2], [false, true])+ func knownTiersSaveWithoutApproval(tier: Int, manual: Bool) async throws {+ let fixture = try await Fixture(records: [.init(kind: .character, name: tier == 2 ? "Renamed" : "Ada", note: "Authored record note", aliases: tier == 2 ? ["Ada"] : [])])+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ if tier == 1 {+ let detail = try await fixture.repository.workDetail(id: fixture.workID)+ let record = try #require(detail.characters.first)+ guard case .committed = try await fixture.repository.commitRecordEdits(workID: fixture.workID,+ operations: [.update(basis: record.editBasis, draft: .init(kind: .character, name: "Renamed", note: record.note))]) else { throw FixtureError.refused }+ }+ try #require(try await fixture.repository.chapterAssociations(entryID: fixture.entryID).isEmpty,+ "Each tier, including retained-name rename, must exercise a new extraction write")+ var publications = 0+ let owner = CharacterExtractionCoordinator(library: fixture.repository,+ model: StubCharacterExtractionModelClient(result: .init(characters: [.init(name: "Ada", facts: [.init(statement: "Must never be saved", quote: "Ada")])])),+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane(),+ onMutation: { publications += 1 })+ if manual { await owner.runManualPass(workID: fixture.workID) } else { await owner.activationSweep() }+ #expect(owner.held(for: fixture.workID).isEmpty)+ #expect(publications == 1, "Saved automatic links publish after their key settles")+ let links = try await fixture.repository.chapterAssociations(entryID: fixture.entryID)+ #expect(links.count == 1); #expect(links.first?.pair.kind == .character)+ #expect(links.first?.noteHeads.isEmpty == true)+ let detail = try await fixture.repository.workDetail(id: fixture.workID)+ #expect(detail.characters.count == 1)+ #expect(detail.characters.first?.facts.isEmpty == true)+ #expect(detail.characters.first?.note == "Authored record note")+ #expect(detail.characters.first?.aliases == (tier == 2 ? ["Ada"] : []))+ #expect(try await source(fixture).isCovered)+ let priorEventCount = try eventCount(fixture)+ await owner.runManualPass(workID: fixture.workID)+ #expect(try await fixture.repository.chapterAssociations(entryID: fixture.entryID).count == 1)+ #expect(try eventCount(fixture) == priorEventCount,+ "Already-active replay adds no acceptance, pending decision or coverage events")+ await fixture.repository.shutdown()+ }+ @Test("Ambiguous chapter keys survive restart and an empty model retry, without becoming approval rows")+ func ambiguousEmptyRetry() async throws {+ let fixture = try await Fixture(records: [.init(kind: .character, name: "First", aliases: ["Ada"]), .init(kind: .character, name: "Second", aliases: ["Ada"])])+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let owner = coordinator(fixture, result: .init(characters: [.init(name: "Ada")]))+ await owner.runManualPass(workID: fixture.workID)+ #expect(owner.held(for: fixture.workID).isEmpty)+ #expect(try await fixture.repository.chapterAssociations(entryID: fixture.entryID).isEmpty)+ #expect(try await !source(fixture).isCovered)+ await fixture.repository.shutdown()+ let (_, reopened) = try await LibraryRepository.openForApp(fixture.configuration, capabilities: .current)+ let retry = CharacterExtractionCoordinator(library: reopened, model: StubCharacterExtractionModelClient(result: .init()),+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ await retry.runManualPass(workID: fixture.workID)+ #expect(retry.held(for: fixture.workID).isEmpty)+ #expect(try await reopened.chapterAssociations(entryID: fixture.entryID).isEmpty)+ #expect(try await !source(fixture, repository: reopened).isCovered)+ await reopened.shutdown()+ }+ @Test("Known characters commit independently while new characters and known places retain decisions")+ func mixedOutcomes() async throws {+ let fixture = try await Fixture(records: [.init(kind: .character, name: "Ada"), .init(kind: .place, name: "Harbour")])+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let owner = coordinator(fixture, result: .init(characters: [.init(name: "Ada"), .init(name: "Bryn")], places: [.init(name: "Harbour")]))+ await owner.runManualPass(workID: fixture.workID)+ #expect(Set(owner.held(for: fixture.workID).map(\.key)) == [.init(kind: .character, nameKey: "bryn"), .init(kind: .place, nameKey: "harbour")])+ #expect(try await fixture.repository.chapterAssociations(entryID: fixture.entryID).count == 1)+ #expect(try await fixture.repository.workDetail(id: fixture.workID).characters.count == 1)+ #expect(try await !source(fixture).isCovered)+ let held = try #require(owner.held(for: fixture.workID).first)+ #expect(held.sourceEvidence.first?.text == "Ada visits Bryn at Harbour.")+ #expect(held.sourceEvidence.first?.isChapter == true)+ await fixture.repository.shutdown()+ }+ @Test("A formerly folded new dual-kind row splits when its character becomes recognised")+ func foldedRowBecomesKnown() async throws {+ let fixture = try await Fixture(records: [])+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let owner = coordinator(fixture, result: .init(characters: [.init(name: "Ada")], places: [.init(name: "Ada")]))+ await owner.runManualPass(workID: fixture.workID)+ #expect(owner.held(for: fixture.workID).count == 1)+ #expect(owner.held(for: fixture.workID).first?.isDualKind == true)+ guard case .committed = try await fixture.repository.commitRecordEdits(workID: fixture.workID,+ operations: [.create(.init(kind: .character, name: "Ada"))]) else { throw FixtureError.refused }+ await owner.reconcile()+ #expect(owner.held(for: fixture.workID).map(\.key) == [.init(kind: .place, nameKey: "ada")])+ #expect(try await fixture.repository.chapterAssociations(entryID: fixture.entryID).count == 1)+ #expect(try await !source(fixture).isCovered)+ await fixture.repository.shutdown()+ let (_, reopened) = try await LibraryRepository.openForApp(fixture.configuration, capabilities: .current)+ let retry = CharacterExtractionCoordinator(library: reopened, model: StubCharacterExtractionModelClient(result: .init()),+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ await retry.runManualPass(workID: fixture.workID)+ #expect(retry.held(for: fixture.workID).map(\.key) == [.init(kind: .place, nameKey: "ada")])+ #expect(try await !source(fixture, repository: reopened).isCovered)+ let detail = try await reopened.workDetail(id: fixture.workID)+ let review = CharacterReviewModel(workID: fixture.workID, proposals: retry.held(for: fixture.workID),+ characters: detail.characters, places: detail.places, library: reopened,+ extractionContext: { retry.context(for: fixture.workID) },+ onDecision: { key, kinds in retry.discard(key, for: fixture.workID, nameKeySuppressedKinds: kinds) },+ onReRoute: { key, target in retry.retarget(key, for: fixture.workID, to: target) },+ onReclassify: { key, kind, target in retry.reclassify(key, for: fixture.workID, to: kind, target: target) },+ refresh: { await retry.reconcile(); return retry.held(for: fixture.workID) })+ await review.accept(try #require(review.rows.first).id)+ #expect(review.rows.isEmpty)+ #expect(try await reopened.workDetail(id: fixture.workID).places.count == 1)+ // Creation changes the matching directory. The pending decision has+ // settled, but a fresh guarded source eligibility is still required.+ await retry.runManualPass(workID: fixture.workID)+ #expect(retry.held(for: fixture.workID).isEmpty)+ #expect(try await source(fixture, repository: reopened).isCovered)+ await reopened.shutdown()+ }+ @Test("Non-chapter known/new/place mixtures remain uncovered across restart without inventing chapter links", arguments: [1, 2])+ func nonChapterMixedRestart(sourceKind: Int) async throws {+ let fixture = try await Fixture(records: [.init(kind: .character, name: "Ada")], sourceKind: sourceKind)+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let result = ExtractionResult(characters: [.init(name: "Ada"), .init(name: "Bryn")], places: [.init(name: "Harbour")])+ let owner = coordinator(fixture, result: result)+ await owner.runManualPass(workID: fixture.workID)+ #expect(Set(owner.held(for: fixture.workID).map(\.key)) == [.init(kind: .character, nameKey: "bryn"), .init(kind: .place, nameKey: "harbour")])+ #expect(try await fixture.repository.chapterAssociations(entryID: fixture.entryID).isEmpty)+ let candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [fixture.workID]).first)+ let source = try #require(candidate.sources.first)+ #expect(!source.isCovered)+ #expect(owner.held(for: fixture.workID).allSatisfy { $0.sourceEvidence.first?.isChapter == false })+ await fixture.repository.shutdown()+ let (_, reopened) = try await LibraryRepository.openForApp(fixture.configuration, capabilities: .current)+ let fresh = try #require(try await reopened.extractionCandidates(limit: 1, workIDs: [fixture.workID]).first)+ #expect(!fresh.uncoveredSources.isEmpty)+ #expect(try await reopened.chapterAssociations(entryID: fixture.entryID).isEmpty)+ await reopened.shutdown()+ }++ @Test("An awaited known-character reconcile preserves concurrent sibling and same-key place evidence")+ func concurrentHeldSettlement() async throws {+ let fixture = try await Fixture(records: [.init(kind: .place, name: "Harbour")])+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let proxy = MockLibraryProvider()+ proxy.extractionCandidatesResult = .success(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [fixture.workID]))+ proxy.pendingMentionReviewHandler = { try await fixture.repository.recordPendingMentionReviews($0) }+ let model = CharacterExtractionCoordinatorTests.MutableAvailabilityClient(.available,+ inner: .init(result: .init(characters: [.init(name: "Ada")], places: [.init(name: "Harbour")])))+ let owner = CharacterExtractionCoordinator(library: proxy, model: model,+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ await owner.runManualPass(workID: fixture.workID)+ #expect(owner.held(for: fixture.workID).count == 2)+ let originalHarbour = try #require(owner.held(for: fixture.workID).first {+ $0.key == .init(kind: .place, nameKey: "harbour")+ })+ let harbourID = try #require(try await fixture.repository.workDetail(id: fixture.workID).places.first { $0.name == "Harbour" }?.id)+ try #require(originalHarbour.target == .existing(harbourID),+ "The older held source already targets the existing Harbour identity")+ guard case .committed = try await fixture.repository.commitRecordEdits(workID: fixture.workID,+ operations: [.create(.init(kind: .character, name: "Ada"))]) else { throw FixtureError.refused }+ // A real local Save now links known Harbour immediately. The race is+ // instead a synced chapter arriving with its association events absent;+ // Harbour's identity and matching directory remain unchanged.+ let secondID = try await insertIncomingChapter(fixture)+ proxy.extractionCandidatesResult = .success(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [fixture.workID]))+ let gate = SubmissionGate(), calls = Mutex(0)+ proxy.commitRecognisedCharacterHandler = { request in+ let number = calls.withLock { value in value += 1; return value }+ if number == 1 { await gate.wait() }+ return try await fixture.repository.commitRecognisedCharacter(request)+ }+ let reconcile = Task { await owner.reconcile() }+ defer { gate.open(); reconcile.cancel() }+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))+ while calls.withLock({ $0 }) == 0 && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(2)) }+ try #require(calls.withLock { $0 } > 0)+ model.inner = .init(result: .init(characters: [.init(name: "Bryn")], places: [.init(name: "Harbour")]))+ await owner.runManualPass(workID: fixture.workID)+ let before = owner.held(for: fixture.workID)+ let harbour = try #require(before.first { $0.key == .init(kind: .place, nameKey: "harbour") })+ #expect(harbour.citedRevisions[.entry(secondID)] != nil)+ try #require(harbour.target == .existing(harbourID) && harbour.target == originalHarbour.target,+ "The newer same-key basis still requires a decision on the same existing place")+ #expect(harbour.citedRevisions != originalHarbour.citedRevisions,+ "The newer obligation adds source evidence without changing its target")+ #expect(before.contains { $0.key == .init(kind: .character, nameKey: "bryn") })+ gate.open(); await reconcile.value+ let after = owner.held(for: fixture.workID)+ #expect(after.contains(harbour), "A newer same-key source basis survives the older awaited reconcile")+ #expect(after.contains { $0.key == .init(kind: .character, nameKey: "bryn") }, "A newly settled sibling is never replaced")+ #expect(try await !source(fixture).isCovered)+ await fixture.repository.shutdown()+ }++ @Test("Derived place recovery stays bound to the folded origin when it is skipped or changed during an awaited write", arguments: [false, true])+ func foldedOriginChanges(skip: Bool) async throws {+ let fixture = try await Fixture(records: [])+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let proxy = MockLibraryProvider()+ proxy.extractionCandidatesResult = .success(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [fixture.workID]))+ proxy.pendingMentionReviewHandler = { try await fixture.repository.recordPendingMentionReviews($0) }+ let owner = CharacterExtractionCoordinator(library: proxy,+ model: StubCharacterExtractionModelClient(result: .init(characters: [.init(name: "Ada")], places: [.init(name: "Ada")])),+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ await owner.runManualPass(workID: fixture.workID)+ let captured = try #require(owner.held(for: fixture.workID).first)+ let review = CharacterReviewModel(workID: fixture.workID, proposals: [captured], characters: [], places: [], library: fixture.repository,+ extractionContext: { owner.context(for: fixture.workID) },+ onDecision: { key, kinds in owner.discard(key, for: fixture.workID, nameKeySuppressedKinds: kinds) },+ onReRoute: { key, target in owner.retarget(key, for: fixture.workID, to: target) },+ onReclassify: { key, kind, target in owner.reclassify(key, for: fixture.workID, to: kind, target: target) },+ refresh: { await owner.reconcile(); return owner.held(for: fixture.workID) })+ guard case .committed = try await fixture.repository.commitRecordEdits(workID: fixture.workID,+ operations: [.create(.init(kind: .character, name: "Ada"))]) else { throw FixtureError.refused }+ proxy.extractionCandidatesResult = .success(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [fixture.workID]))+ let gate = SubmissionGate(), entered = Mutex(false)+ proxy.commitRecognisedCharacterHandler = { request in+ entered.withLock { $0 = true }; await gate.wait()+ return try await fixture.repository.commitRecognisedCharacter(request)+ }+ let reconcile = Task { await owner.reconcile() }+ defer { gate.open(); reconcile.cancel() }+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))+ while !entered.withLock({ $0 }) && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(2)) }+ try #require(entered.withLock { $0 })+ if skip {+ await review.skip(captured.key.rowID)+ #expect(review.rows.isEmpty)+ } else {+ owner.reclassify(captured.key, for: fixture.workID, to: .place, target: nil)+ }+ gate.open(); await reconcile.value+ if skip { #expect(owner.held(for: fixture.workID).isEmpty) }+ else {+ #expect(owner.held(for: fixture.workID).map(\.key) == [captured.key])+ #expect(owner.held(for: fixture.workID).first?.displayedKind == .place)+ }+ await fixture.repository.shutdown()+ let (_, reopened) = try await LibraryRepository.openForApp(fixture.configuration, capabilities: .current)+ let retry = CharacterExtractionCoordinator(library: reopened, model: StubCharacterExtractionModelClient(result: .init()),+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ await retry.runManualPass(workID: fixture.workID)+ if skip {+ #expect(retry.held(for: fixture.workID).isEmpty, "A committed dual-kind Skip cannot resurrect its derived place")+ #expect(try await source(fixture, repository: reopened).isCovered, "The now-irrelevant new-place marker cannot strand coverage")+ } else {+ #expect(retry.held(for: fixture.workID).map(\.key) == [.init(kind: .place, nameKey: "ada")], "The independent place decision remains reachable after RAM is lost")+ }+ await reopened.shutdown()+ }++ @Test("All recognised keys settle source coverage in the first pass without repeated pending decisions")+ func multipleKnownKeysComplete() async throws {+ let fixture = try await Fixture(records: [.init(kind: .character, name: "Ada"), .init(kind: .character, name: "Bryn")])+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let owner = coordinator(fixture, result: .init(characters: [.init(name: "Ada"), .init(name: "Bryn")]))+ await owner.runManualPass(workID: fixture.workID)+ #expect(owner.held(for: fixture.workID).isEmpty)+ #expect(try await fixture.repository.chapterAssociations(entryID: fixture.entryID).count == 2)+ #expect(try await source(fixture).isCovered)+ await fixture.repository.shutdown()+ }++ @Test("Cancelling a folded origin preserves an independently held same-name place contribution", arguments: [false, true])+ func independentPlaceCollision(change: Bool) async throws {+ let fixture = try await Fixture(records: [])+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let projection = try await fixture.repository.projectManualEntry(workID: fixture.workID)+ guard case .committed(let second) = try await fixture.repository.commitManualEntry(projection: projection,+ draft: .init(target: .init(kind: .chapter, title: "Second", designation: "2"), note: "Ada waits.", confirmedNewChapter: true)) else { throw FixtureError.refused }+ let proxy = MockLibraryProvider()+ proxy.extractionCandidatesResult = .success(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [fixture.workID]))+ proxy.pendingMentionReviewHandler = { try await fixture.repository.recordPendingMentionReviews($0) }+ let owner = CharacterExtractionCoordinator(library: proxy, model: StubCharacterExtractionModelClient(results: [+ .success(.init(characters: [.init(name: "Ada")], places: [.init(name: "Ada")])),+ .success(.init(places: [.init(name: "Ada")]))]),+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane())+ await owner.runManualPass(workID: fixture.workID)+ let originalPlace = try #require(owner.held(for: fixture.workID).first { $0.kind == .place })+ #expect(Set(originalPlace.citedRevisions.keys) == [.entry(second.id)])+ let characterKey = ProposalKey(kind: .character, nameKey: "ada")+ guard case .committed = try await fixture.repository.commitRecordEdits(workID: fixture.workID,+ operations: [.create(.init(kind: .character, name: "Ada"))]) else { throw FixtureError.refused }+ proxy.extractionCandidatesResult = .success(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [fixture.workID]))+ let gate = SubmissionGate(), entered = Mutex(false)+ proxy.commitRecognisedCharacterHandler = { request in+ entered.withLock { $0 = true }; await gate.wait()+ return try await fixture.repository.commitRecognisedCharacter(request)+ }+ let reconcile = Task { await owner.reconcile() }+ defer { gate.open(); reconcile.cancel() }+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))+ while !entered.withLock({ $0 }) && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(2)) }+ try #require(entered.withLock { $0 })+ if change { owner.reclassify(characterKey, for: fixture.workID, to: .place, target: nil) }+ else { owner.discard(characterKey, for: fixture.workID) }+ gate.open(); await reconcile.value+ let retained = try #require(owner.held(for: fixture.workID).first { $0.kind == .place })+ #expect(retained.citedRevisions == originalPlace.citedRevisions)+ #expect(retained.sourceEvidence == originalPlace.sourceEvidence)+ #expect(retained.citedRevisions[.entry(fixture.entryID)] == nil,+ "Discarded/changed folded source A cannot replace independent place source B")+ await fixture.repository.shutdown()+ }++ @Test("Cancelling after one recognised link commits starts no later key and leaves source coverage retryable")+ func cancellationBetweenKnownWrites() async throws {+ let fixture = try await Fixture(records: [.init(kind: .character, name: "Ada"), .init(kind: .character, name: "Bryn")])+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ let proxy = MockLibraryProvider()+ proxy.extractionCandidatesResult = .success(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [fixture.workID]))+ proxy.pendingMentionReviewHandler = { try await fixture.repository.recordPendingMentionReviews($0) }+ let gate = SubmissionGate(), committed = Mutex(false)+ proxy.commitRecognisedCharacterHandler = { request in+ let outcome = try await fixture.repository.commitRecognisedCharacter(request)+ committed.withLock { $0 = true }+ await gate.wait()+ return outcome+ }+ var publications = 0+ let owner = CharacterExtractionCoordinator(library: proxy,+ model: StubCharacterExtractionModelClient(result: .init(characters: [.init(name: "Ada"), .init(name: "Bryn")])),+ environment: CharacterExtractionCoordinatorTests.StubEnvironment(), lane: ModelLane(),+ onMutation: { publications += 1 })+ let sweep = Task { await owner.activationSweep() }+ defer { gate.open(); sweep.cancel() }+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))+ while !committed.withLock({ $0 }) && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(2)) }+ try #require(committed.withLock { $0 })+ owner.resignActive()+ gate.open(); await sweep.value+ #expect(proxy.recognisedCharacterRequests.count == 1)+ #expect(publications == 1)+ #expect(proxy.advancedCoverage.isEmpty)+ #expect(try await fixture.repository.chapterAssociations(entryID: fixture.entryID).count == 1)+ #expect(try await !source(fixture).isCovered)+ let retry = coordinator(fixture, result: .init(characters: [.init(name: "Ada"), .init(name: "Bryn")]))+ await retry.runManualPass(workID: fixture.workID)+ #expect(retry.held(for: fixture.workID).isEmpty)+ #expect(try await fixture.repository.chapterAssociations(entryID: fixture.entryID).count == 2)+ #expect(try await source(fixture).isCovered)+ await fixture.repository.shutdown()+ }++}
diff --git a/Asterism/AsterismTests/PublicationPresentationTests.swift b/Asterism/AsterismTests/PublicationPresentationTests.swiftindex f7a3ef2c..4dc1364a 100644--- a/Asterism/AsterismTests/PublicationPresentationTests.swift+++ b/Asterism/AsterismTests/PublicationPresentationTests.swift@@ -1,4 +1,5 @@ import AsterismPresentation+import AsterismTestSupport import AsterismCore import Foundation import Testing@@ -57,4 +58,40 @@ struct PublicationPresentationTests { #expect(model.calendar.timeZone == zone.timeZone) #expect(model.worksSnapshot.works.first?.publicationState == work.publicationState) }++ @Test("Library helpers honor an explicit published day and calendar at a hiatus return")+ func libraryHelperUsesExplicitPublishedDayAndZone() throws {+ let utc = calendar+ var losAngeles = calendar+ losAngeles.timeZone = TimeZone(identifier: "America/Los_Angeles")!+ let before = day("2026-09-29"), returned = day("2026-09-30")+ // This instant is return-day in UTC but still the paused day in LA.+ // A helper silently substituting one device calendar cannot satisfy both.+ let confirmed = returned.date(in: utc).addingTimeInterval(30 * 60)+ let note = TestFixtures.makeEntry(lastSharedAt: confirmed, firstCapturedAt: confirmed,+ chapterTitle: "Chapter 40", chapterSequence: "40")+ let publication = try work().publicationState+ let work = WorkSnapshot(id: UUID(), displayTitle: "Returns", lastParsedTitle: nil,+ memberships: [], genericNotes: "", genreTags: [], titleProvenance: .manual,+ createdAt: confirmed, modifiedAt: confirmed, entries: [note],+ authoredWorkStatus: .hiatus, releaseDays: ReleaseDay.allCases,+ catchUp: .init(confirmation: .init(latest: 42,+ confirmedAtMilliseconds: MillisecondInstant.milliseconds(confirmed),+ countsUp: true, isEstimate: false), override: nil), publicationState: publication)+ let library = WorksView(snapshot: .init(works: [work], unattachedEntries: []),+ onSelectWork: { _ in }, onSelectEntry: { _ in }, onNewWork: { _ in },+ onSelectSeries: { _ in }, onShowSeriesList: {}, onShowCreatorList: {})++ // This intentionally calls the shared helper on an unmounted configuration,+ // as WorksSearchContent does. Only explicit values may enter its calculation.+ for zone in [utc, losAngeles] {+ #expect(library.tileStat(.reading, members: [work], currentDay: before, calendar: zone) == "")+ #expect(library.tileStat(.reading, members: [work], currentDay: returned, calendar: zone) == "1 release today")+ }+ #expect(library.tileStat(.catchingUp, members: [work], currentDay: returned, calendar: utc) == "~2 chapters behind")+ #expect(library.tileStat(.catchingUp, members: [work], currentDay: returned, calendar: losAngeles) == "~3 chapters behind")+ #expect(work.authoredWorkStatus == .hiatus)+ #expect(work.publicationState == publication)+ }+ }
diff --git a/Asterism/AsterismTests/SkippedCharacterLinksTests.swift b/Asterism/AsterismTests/SkippedCharacterLinksTests.swiftnew file mode 100644index 00000000..44569ab3--- /dev/null+++ b/Asterism/AsterismTests/SkippedCharacterLinksTests.swift@@ -0,0 +1,65 @@+import AsterismCore+import Foundation+import Testing+@testable import Asterism++@Suite("Optional skipped character link restoration")+struct SkippedCharacterLinksTests {+ @MainActor private func fixture() -> (SkippedCharacterLinksModel, MockLibraryProvider, SkippedCharacterLinkSnapshot) {+ let mock = MockLibraryProvider()+ let pair = AssociationPair(workID: UUID(), entryID: UUID(), kind: .character, recordID: UUID())+ let captured = SkippedCharacterLinkSnapshot(pair: pair, recordName: "Ada", matchingName: "Ada",+ spellingKeys: ["ada"], observedRejectionIDs: [UUID()], noteFingerprint: "exact source",+ sourceGuard: "source copies", targetFingerprint: "target copies")+ mock.skippedCharacterLinksResult = .success([captured])+ return (SkippedCharacterLinksModel(entryID: pair.entryID, library: mock), mock, captured)+ }+ @Test @MainActor func olderLoadCannotResurrectAnExplicitlyRestoredLink() async throws {+ let (model, mock, captured) = fixture()+ let gate = SubmissionGate()+ mock.skippedCharacterLinksHandler = { _ in await gate.wait(); return [captured] }+ let old = Task { await model.load() }+ defer { old.cancel(); gate.open() }+ for _ in 0..<1000 where mock.skippedLinkReadCount == 0 { await Task.yield() }+ try #require(mock.skippedLinkReadCount == 1)+ mock.skippedCharacterLinksHandler = nil+ await model.load()+ mock.restoreCharacterLinkResult = .success(.committed(recordID: captured.pair.recordID))+ await model.restore(captured)+ gate.open(); await old.value+ #expect(model.state == .ready && model.links.isEmpty)+ #expect(mock.restoredCharacterLinks == [captured])+ }++ @Test @MainActor func loadingNeverRestoresAndRetainsCapturedAuthority() async {+ let (model, mock, captured) = fixture()+ await model.load()+ #expect(model.links == [captured] && model.state == .ready)+ #expect(mock.restoredCharacterLinks.isEmpty)+ }+ @Test @MainActor func refusalRetainsRowAndRequiresExplicitReload() async {+ let (model, mock, captured) = fixture()+ await model.load()+ mock.restoreCharacterLinkResult = .success(.refused(.staleSource(.entry(captured.pair.entryID))))+ await model.restore(captured)+ #expect(model.links == [captured] && model.message != nil)+ #expect(mock.restoredCharacterLinks == [captured])+ }+ @Test @MainActor func readFailureIsNotAnEmptySuccessfulList() async {+ let (model, mock, _) = fixture()+ mock.skippedCharacterLinksResult = .failure(CocoaError(.fileReadUnknown))+ await model.load()+ #expect(model.state == .error && model.message != nil)+ }+ @Test @MainActor func oneExplicitRestorePublishesAndRemovesOnlyChosenRow() async {+ let (_, mock, captured) = fixture()+ var publications = 0+ let model = SkippedCharacterLinksModel(entryID: captured.pair.entryID, library: mock) { publications += 1 }+ await model.load()+ mock.restoreCharacterLinkResult = .success(.committed(recordID: captured.pair.recordID))+ await model.restore(captured)+ #expect(model.links.isEmpty && mock.restoredCharacterLinks == [captured] && publications == 1)+ await model.restore(captured)+ #expect(mock.restoredCharacterLinks.count == 1)+ }+}
diff --git a/Asterism/AsterismTests/SourceRowPresentationTests.swift b/Asterism/AsterismTests/SourceRowPresentationTests.swiftnew file mode 100644index 00000000..e4661cef--- /dev/null+++ b/Asterism/AsterismTests/SourceRowPresentationTests.swift@@ -0,0 +1,29 @@+import AsterismCore+import AsterismIntelligence+import Foundation+import Testing+@testable import Asterism++@Suite("Source row titles preserve captured context") @MainActor+struct SourceRowPresentationTests {+ @Test func actualChapterTitleIsNotReplacedOrPrefixedByDesignation() {+ #expect(SourceTitleDateRow.chapterTitle("Shared title", designation: "6") == "Shared title")+ #expect(SourceTitleDateRow.chapterTitle(" Cafe\u{301} ", designation: "7") == " Cafe\u{301} ")+ #expect(SourceTitleDateRow.chapterTitle("Chapter 8 is the actual title", designation: "9") == "Chapter 8 is the actual title")+ }+ @Test func trulyUntitledChaptersHaveOneMeaningfulFallback() {+ #expect(SourceTitleDateRow.chapterTitle("", designation: "6") == "Chapter 6")+ #expect(SourceTitleDateRow.chapterTitle(" \n", designation: "Interlude") == "Chapter Interlude")+ #expect(SourceTitleDateRow.chapterTitle("", designation: nil) == "Unnumbered chapter")+ }+ @Test func genericStandaloneAndUntitledChapterSourcesRemainDistinct() {+ func source(_ ref: SourceRef, chapter: Bool, title: String = "") -> ProposalSourceEvidence {+ .init(source: .init(workID: UUID(), workTitle: "Story", source: ref, text: " Exact source ",+ fingerprint: "saved", displayTitle: title, isChapter: chapter), spellings: ["Ada"])+ }+ #expect(ProposalSourceEvidenceView.presentationTitle(source(.genericNotes, chapter: false)) == "Work generic notes")+ #expect(ProposalSourceEvidenceView.presentationTitle(source(.entry(UUID()), chapter: false)) == "Standalone note")+ #expect(ProposalSourceEvidenceView.presentationTitle(source(.entry(UUID()), chapter: true)) == "Unnumbered chapter")+ #expect(ProposalSourceEvidenceView.presentationTitle(source(.entry(UUID()), chapter: true, title: "Actual chapter")) == "Actual chapter")+ }+}
diff --git a/Asterism/AsterismTests/TodayStackItemBindingTests.swift b/Asterism/AsterismTests/TodayStackItemBindingTests.swiftnew file mode 100644index 00000000..9c57d547--- /dev/null+++ b/Asterism/AsterismTests/TodayStackItemBindingTests.swift@@ -0,0 +1,263 @@+import SwiftUI+#if os(macOS)+import AppKit+#else+import UIKit+#endif+import XCTest++@testable import Asterism++private struct RevisionBindingTransactionKey: TransactionKey {+ static let defaultValue = 0+}++@MainActor+private final class RevisionBindingRevision {+ var value: Int+ init(_ value: Int) { self.value = value }+}++@MainActor+private final class RevisionBindingSpy {+ var value: UUID?+ var writes: [(UUID?, Transaction)] = []+ init(_ value: UUID?) { self.value = value }+ var binding: Binding<UUID?> {+ Binding(get: { self.value }, set: { value, transaction in+ self.writes.append((value, transaction))+ self.value = value+ })+ }+}++@MainActor+private final class MountedRevisionProbe {+ struct Snapshot {+ let item: Binding<UUID?>+ let inspector: Binding<Bool>+ let revision: Binding<Int>+ let readRevision: () -> Int+ }+ let appeared = XCTestExpectation(description: "Revision probe mounted")+ let changed = XCTestExpectation(description: "Mounted revision changed")+ var snapshot: Snapshot?+}++/// Match the production capture: owner value once, State access in the reader.+/// No AppLibraryModel, persistence, delayed writes, or NavigationStack needed to+/// prove this storage/callback invariant. Rendered stack behavior is a separate gate.+@MainActor+private struct MountedRevisionProbeView: View {+ @State private var revision = 0+ @Bindable var navigation: AppNavigation+ let probe: MountedRevisionProbe+ var body: some View {+ Color.clear+ .onAppear {+ let ownerRevision = revision+ probe.snapshot = .init(+ item: TodayStackItemBinding.owned(+ $navigation.selectedTodayEntryID,+ ownerRevision: ownerRevision,+ currentRevision: { revision }),+ inspector: TodayStackItemBinding.presentation(+ TodayStackItemBinding.owned(+ $navigation.todayInspectorEntryID,+ ownerRevision: ownerRevision,+ currentRevision: { revision })),+ revision: $revision,+ readRevision: { revision })+ probe.appeared.fulfill()+ }+ .onChange(of: revision) { _, _ in probe.changed.fulfill() }+ }+}++@MainActor+final class TodayStackItemBindingTests: XCTestCase {+ func testStaleNilCannotClearNewRevisionEntryAndGetterStaysOriginal() {+ let first = UUID(), second = UUID()+ let spy = RevisionBindingSpy(first)+ let revision = RevisionBindingRevision(2)+ let old = TodayStackItemBinding.owned(spy.binding, ownerRevision: revision.value,+ currentRevision: { revision.value })+ revision.value = 3+ spy.value = second+ XCTAssertEqual(old.wrappedValue, second)+ old.wrappedValue = nil+ XCTAssertEqual(spy.value, second)+ XCTAssertEqual(spy.writes.count, 0)+ }++ func testCurrentRevisionNilForwardsExactlyOnceWithOriginalTransaction() {+ let spy = RevisionBindingSpy(UUID())+ let item = TodayStackItemBinding.owned(spy.binding, ownerRevision: 3,+ currentRevision: { 3 })+ var transaction = Transaction()+ transaction.disablesAnimations = true+ transaction[RevisionBindingTransactionKey.self] = 73+ item.transaction(transaction).wrappedValue = nil+ XCTAssertNil(spy.value)+ XCTAssertEqual(spy.writes.count, 1)+ XCTAssertTrue(spy.writes[0].1.disablesAnimations)+ XCTAssertEqual(spy.writes[0].1[RevisionBindingTransactionKey.self], 73)+ }++ func testSameRevisionOldItemNilRemainsAllowed() {+ let spy = RevisionBindingSpy(UUID())+ let item = TodayStackItemBinding.owned(spy.binding, ownerRevision: 4,+ currentRevision: { 4 })+ // No revision transition: deliberately outside the guard's protection.+ spy.value = UUID()+ item.wrappedValue = nil+ XCTAssertNil(spy.value)+ XCTAssertEqual(spy.writes.count, 1)+ }++ func testStaleNonNilWriteStillForwardsExactlyOnceWithTransaction() {+ let spy = RevisionBindingSpy(UUID()), next = UUID()+ let revision = RevisionBindingRevision(2)+ let item = TodayStackItemBinding.owned(spy.binding, ownerRevision: revision.value,+ currentRevision: { revision.value })+ revision.value = 3+ var transaction = Transaction()+ transaction[RevisionBindingTransactionKey.self] = 19+ item.transaction(transaction).wrappedValue = next+ XCTAssertEqual(spy.value, next)+ XCTAssertEqual(spy.writes.count, 1)+ XCTAssertEqual(spy.writes[0].1[RevisionBindingTransactionKey.self], 19)+ }++ func testDirectAppBackAndDirectClearBypassOldBinding() {+ let navigation = AppNavigation()+ navigation.showTodayEntry(UUID())+ let revision = RevisionBindingRevision(0)+ var bindingWrites = 0+ let original = Binding<UUID?>(get: { navigation.selectedTodayEntryID }, set: { value in+ bindingWrites += 1+ navigation.selectedTodayEntryID = value+ })+ let old = TodayStackItemBinding.owned(original, ownerRevision: revision.value,+ currentRevision: { revision.value })+ revision.value = 1+ navigation.showTodayEntry(UUID())+ old.wrappedValue = nil+ XCTAssertNotNil(navigation.selectedTodayEntryID)+ navigation.back()+ XCTAssertNil(navigation.selectedTodayEntryID)+ navigation.showTodayEntry(UUID())+ navigation.selectedTodayEntryID = nil+ XCTAssertNil(navigation.selectedTodayEntryID)+ XCTAssertEqual(bindingWrites, 0)+ }++ func testInspectorStaleDismissalCannotClearNewRevisionSelection() {+ let spy = RevisionBindingSpy(UUID())+ let revision = RevisionBindingRevision(0)+ let old = TodayStackItemBinding.presentation(+ TodayStackItemBinding.owned(spy.binding, ownerRevision: revision.value,+ currentRevision: { revision.value }))+ revision.value = 1+ let fresh = UUID()+ spy.value = fresh+ XCTAssertTrue(old.wrappedValue)+ old.wrappedValue = false+ XCTAssertEqual(spy.value, fresh)+ XCTAssertTrue(spy.writes.isEmpty)+ }++ func testInspectorCurrentDismissalForwardsOriginalTransactionOnce() {+ let spy = RevisionBindingSpy(UUID())+ let presentation = TodayStackItemBinding.presentation(+ TodayStackItemBinding.owned(spy.binding, ownerRevision: 3,+ currentRevision: { 3 }))+ var transaction = Transaction()+ transaction.disablesAnimations = true+ transaction[RevisionBindingTransactionKey.self] = 91+ presentation.transaction(transaction).wrappedValue = false+ XCTAssertNil(spy.value)+ XCTAssertEqual(spy.writes.count, 1)+ XCTAssertTrue(spy.writes[0].1.disablesAnimations)+ XCTAssertEqual(spy.writes[0].1[RevisionBindingTransactionKey.self], 91)+ }++ func testInspectorTrueWritesDoNotInventOrReplaceSelectionAndGetterStaysLive() {+ let spy = RevisionBindingSpy(nil)+ let presentation = TodayStackItemBinding.presentation(+ TodayStackItemBinding.owned(spy.binding, ownerRevision: 0,+ currentRevision: { 0 }))+ XCTAssertFalse(presentation.wrappedValue)+ presentation.wrappedValue = true+ XCTAssertNil(spy.value)+ let selected = UUID()+ spy.value = selected+ XCTAssertTrue(presentation.wrappedValue)+ presentation.wrappedValue = true+ XCTAssertEqual(spy.value, selected)+ spy.value = nil+ XCTAssertFalse(presentation.wrappedValue)+ XCTAssertTrue(spy.writes.isEmpty)+ }++ func testInspectorDirectBackAndCloseBypassRetiredPresentation() {+ let navigation = AppNavigation()+ let revision = RevisionBindingRevision(0)+ let original = Binding<UUID?>(get: { navigation.todayInspectorEntryID },+ set: { navigation.todayInspectorEntryID = $0 })+ let old = TodayStackItemBinding.presentation(+ TodayStackItemBinding.owned(original, ownerRevision: revision.value,+ currentRevision: { revision.value }))+ revision.value = 1+ let fresh = UUID()+ navigation.todayInspectorEntryID = fresh+ old.wrappedValue = false+ XCTAssertEqual(navigation.todayInspectorEntryID, fresh)+ navigation.back()+ XCTAssertNil(navigation.todayInspectorEntryID)+ navigation.todayInspectorEntryID = UUID()+ navigation.todayInspectorEntryID = nil+ XCTAssertNil(navigation.todayInspectorEntryID)+ }++ func testMountedStateReaderSeesLiveRevisionAfterBodyUpdate() async throws {+ let navigation = AppNavigation(), probe = MountedRevisionProbe()+ navigation.todayInspectorEntryID = UUID()+ navigation.showTodayEntry(UUID())+ let content = MountedRevisionProbeView(navigation: navigation, probe: probe)+ #if os(macOS)+ let window = NSWindow(contentRect: CGRect(x: 0, y: 0, width: 600, height: 600),+ styleMask: [.titled], backing: .buffered, defer: false)+ window.isReleasedWhenClosed = false+ window.contentView = NSHostingView(rootView: content)+ window.orderFront(nil)+ defer { window.orderOut(nil); window.contentView = nil; window.close() }+ #else+ let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)+ let window = UIWindow(windowScene: scene)+ window.frame = CGRect(x: 0, y: 0, width: 600, height: 600)+ window.rootViewController = UIHostingController(rootView: content)+ window.isHidden = false+ defer { window.isHidden = true; window.rootViewController = nil }+ #endif+ let appeared = await XCTWaiter.fulfillment(of: [probe.appeared], timeout: 3)+ XCTAssertEqual(appeared, .completed)+ let original = try XCTUnwrap(probe.snapshot)+ XCTAssertEqual(original.readRevision(), 0)+ original.revision.wrappedValue = 1+ let second = UUID()+ navigation.showTodayEntry(second)+ let secondInspector = UUID()+ navigation.todayInspectorEntryID = secondInspector+ let changed = await XCTWaiter.fulfillment(of: [probe.changed], timeout: 3)+ XCTAssertEqual(changed, .completed)+ // This is the OLD installed View's closure, not a replacement closure+ // constructed with a new revision value after the update.+ XCTAssertEqual(original.readRevision(), 1)+ XCTAssertEqual(original.revision.wrappedValue, 1)+ original.item.wrappedValue = nil+ XCTAssertEqual(navigation.selectedTodayEntryID, second)+ original.inspector.wrappedValue = false+ XCTAssertEqual(navigation.todayInspectorEntryID, secondInspector)+ }+}
diff --git a/Asterism/AsterismTests/UITestLaunchSupportTests.swift b/Asterism/AsterismTests/UITestLaunchSupportTests.swiftindex 234ff5f7..97dd3780 100644--- a/Asterism/AsterismTests/UITestLaunchSupportTests.swift+++ b/Asterism/AsterismTests/UITestLaunchSupportTests.swift@@ -7,6 +7,21 @@ import AsterismIntelligence @MainActor @Suite("UI test launch validation") struct UITestLaunchSupportTests {+ @Test("Chapter link journeys resolve their UUID temporary root before bootstrap")+ func validAssociationNotesSeedRequest() {+ let runID = UUID()+ let request = UITestLaunchSupport.request(environmentProvider: StubProcessEnvironment(values: [+ UITestLaunchSupport.scenarioKey: "seeded-association-notes",+ UITestLaunchSupport.runIDKey: runID.uuidString+ ]), temporaryDirectory: URL(filePath: "/tmp/asterism-launch-tests"))+ guard case .seeded(let configuration, let fixture) = request else {+ Issue.record("Expected the isolated chapter link fixture"); return+ }+ #expect(fixture == .associationNotes)+ #expect(configuration.rootDirectory.path == "/tmp/asterism-launch-tests/AsterismUITests/\(runID.uuidString)")+ #expect(configuration.cloudKitContainerID == nil)+ }+ @Test("Manual cast seeds use a UUID-contained temporary library without CloudKit") func validManualNoteCastSeedRequest() { let request = UITestLaunchSupport.request(environmentProvider: StubProcessEnvironment(values: [
diff --git a/Asterism/AsterismTests/WorkDetailModelTests.swift b/Asterism/AsterismTests/WorkDetailModelTests.swiftindex 564a81a0..bda183a0 100644--- a/Asterism/AsterismTests/WorkDetailModelTests.swift+++ b/Asterism/AsterismTests/WorkDetailModelTests.swift@@ -2831,3 +2831,362 @@ struct ReleaseDaysTextTests { ]) } }++@Suite("Selected record history model", .serialized)+@MainActor+struct WorkRecordHistoryModelTests {+ private func snapshot(_ selection: RecordHistorySelection, count: Int = 600, generation: String = "first") -> RecordHistorySnapshot {+ let details = (0..<count).map { _ in+ RecordHistoryDetail(pair: .init(workID: selection.workID, entryID: UUID(), kind: selection.kind, recordID: selection.recordID),+ sourceText: "Exact saved source", annotationHeads: [])+ }+ let rows = details.map { detail in+ RecordHistoryRow(id: detail.pair, displayTitle: "Chapter", chapterKey: nil, notedAt: .distantPast,+ sourcePreview: "Exact saved source", sourceFingerprint: "source", hasAnnotation: false, hasConflictingAnnotations: false)+ }+ return .init(selection: selection, generation: generation, availability: .available, activeChapterCount: count, rows: rows, details: details)+ }++ @Test func disclosureRetainsLocalWindowAndRowsAcrossRefreshButResetsForTypedSelection() async throws {+ let selection = RecordHistorySelection(workID: UUID(), kind: .character, recordID: UUID())+ let mock = MockLibraryProvider(), first = snapshot(selection, count: 60)+ mock.recordHistoryResult = .success(first)+ let model = makeWorkDetailModel(workID: selection.workID, library: mock)+ await model.selectRecordHistory(kind: selection.kind, recordID: selection.recordID)+ #expect(!model.isRecordHistorySectionExpanded)+ model.isRecordHistorySectionExpanded = true; model.showMoreRecordHistory()+ let pair = try #require(first.rows.first?.id)+ model.setRecordHistoryExpanded(pair, expanded: true, expectedGeneration: first.generation)+ model.isRecordHistorySectionExpanded = false+ await model.refreshRecordHistory(publicationGeneration: 3)+ #expect(!model.isRecordHistorySectionExpanded && model.visibleRecordHistoryRows.count == 40)+ model.isRecordHistorySectionExpanded = true+ await model.recordHistoryNoteSaved()+ #expect(model.isRecordHistorySectionExpanded && model.expandedRecordHistoryPairs == [pair])+ #expect(model.visibleRecordHistoryRows.count == 40)+ let place = RecordHistorySelection(workID: selection.workID, kind: .place, recordID: selection.recordID)+ mock.recordHistoryResult = .success(snapshot(place, count: 1))+ await model.selectRecordHistory(kind: place.kind, recordID: place.recordID)+ #expect(!model.isRecordHistorySectionExpanded && model.visibleRecordHistoryRows.count == 1)+ #expect(model.expandedRecordHistoryPairs.isEmpty && model.recordHistory?.selection == place)+ }++ @Test func sixHundredRowsUseThirtyLocalWindowsAndNoExtraReads() async throws {+ let selection = RecordHistorySelection(workID: UUID(), kind: .character, recordID: UUID())+ let mock = MockLibraryProvider(), saved = snapshot(selection)+ mock.recordHistoryResult = .success(saved)+ let model = makeWorkDetailModel(workID: selection.workID, library: mock)+ await model.selectRecordHistory(kind: selection.kind, recordID: selection.recordID)+ #expect(model.recordHistoryState == .ready && model.visibleRecordHistoryRows.count == 20)+ #expect(model.remainingRecordHistoryCount == 580)+ let first = try #require(saved.rows.first)+ model.setRecordHistoryExpanded(first.id, expanded: true, expectedGeneration: saved.generation)+ for _ in 1..<30 { model.showMoreRecordHistory() }+ #expect(model.visibleRecordHistoryRows.count == 600 && model.remainingRecordHistoryCount == 0)+ #expect(mock.recordHistoryCalls.count == 1 && model.expandedRecordHistoryPairs == [first.id])+ #expect(model.recordHistoryDetail(for: first.id, expectedGeneration: "old") == nil)+ }++ @Test func laterSelectionCannotBeOverwrittenByAnOlderRead() async {+ let work = UUID(), first = RecordHistorySelection(workID: work, kind: .character, recordID: UUID())+ let second = RecordHistorySelection(workID: work, kind: .place, recordID: UUID())+ let a = snapshot(first, count: 1), b = snapshot(second, count: 2), gate = SubmissionGate(), entered = SubmissionGate()+ let mock = MockLibraryProvider()+ mock.recordHistoryHandler = { selected in+ if selected == first { entered.open(); await gate.wait(); return a }+ return b+ }+ let model = makeWorkDetailModel(workID: work, library: mock)+ let older = Task { await model.selectRecordHistory(kind: first.kind, recordID: first.recordID) }+ await entered.wait()+ await model.selectRecordHistory(kind: second.kind, recordID: second.recordID)+ gate.open(); await older.value+ #expect(model.selectedRecordHistory == second && model.recordHistory == b)+ #expect(model.visibleRecordHistoryRows.count == 2)+ }++ @Test func publicationRefreshPreservesWindowAndRejectsOldBodies() async throws {+ let selection = RecordHistorySelection(workID: UUID(), kind: .character, recordID: UUID())+ let mock = MockLibraryProvider(), first = snapshot(selection)+ let model = makeWorkDetailModel(workID: selection.workID, library: mock)+ mock.recordHistoryResult = .success(first)+ await model.selectRecordHistory(kind: selection.kind, recordID: selection.recordID)+ model.showMoreRecordHistory()+ let pair = try #require(first.rows.first?.id)+ model.setRecordHistoryExpanded(pair, expanded: true, expectedGeneration: first.generation)+ let changed = RecordHistorySnapshot(selection: selection, generation: "second", availability: .available,+ activeChapterCount: first.activeChapterCount, rows: first.rows, details: first.rows.compactMap { first.detail(for: $0.id, expectedGeneration: first.generation) })+ mock.recordHistoryResult = .success(changed)+ await model.refreshRecordHistory(publicationGeneration: 2)+ #expect(model.visibleRecordHistoryRows.count == 40 && model.expandedRecordHistoryPairs == [pair])+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: first.generation) == nil)+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: changed.generation)?.sourceText == "Exact saved source")+ await model.refreshRecordHistory(publicationGeneration: 2)+ #expect(mock.recordHistoryCalls.count == 2)+ }++ @Test func suspendedRefreshKeepsCapturedRowsMountedUntilFreshAnnotationArrives() async throws {+ let selection = RecordHistorySelection(workID: UUID(), kind: .character, recordID: UUID())+ let mock = MockLibraryProvider(), first = snapshot(selection, count: 24)+ mock.recordHistoryResult = .success(first)+ let model = makeWorkDetailModel(workID: selection.workID, library: mock)+ await model.selectRecordHistory(kind: selection.kind, recordID: selection.recordID)+ model.showMoreRecordHistory()+ let pair = try #require(first.rows.first?.id)+ model.setRecordHistoryExpanded(pair, expanded: true, expectedGeneration: first.generation)+ let updatedDetails = first.rows.map { row in+ RecordHistoryDetail(pair: row.id, sourceText: "Exact saved source", annotationHeads:+ row.id == pair ? [.init(pair: pair, attachmentAcceptanceIDs: [UUID()], text: "Reader history annotation")] : [])+ }+ let updated = RecordHistorySnapshot(selection: selection, generation: "saved", availability: .available,+ activeChapterCount: 24, rows: first.rows, details: updatedDetails)+ let entered = SubmissionGate(), release = SubmissionGate()+ mock.recordHistoryHandler = { _ in entered.open(); await release.wait(); return updated }+ let refresh = Task { await model.refreshRecordHistory(publicationGeneration: 2) }+ await entered.wait()+ #expect(model.isRefreshingRecordHistory && model.recordHistoryState == .ready)+ #expect(model.recordHistory == first && model.visibleRecordHistoryRows.count == 24)+ #expect(model.expandedRecordHistoryPairs == [pair])+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: first.generation)?.sourceText == "Exact saved source")+ #expect(model.recordHistoryNoteEditor(for: pair) == nil, "A pending refresh cannot start an editor from the old capture")+ release.open(); await refresh.value+ #expect(!model.isRefreshingRecordHistory && model.recordHistory == updated)+ #expect(model.visibleRecordHistoryRows.count == 24 && model.expandedRecordHistoryPairs == [pair])+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: first.generation) == nil)+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: updated.generation)?.annotationHeads.first?.text == "Reader history annotation")+ #expect(model.recordHistoryNoteEditor(for: pair) != nil)+ }++ @Test func cancelledRefreshCannotDeduplicateOrClearItsSameGenerationReplacement() async throws {+ let selection = RecordHistorySelection(workID: UUID(), kind: .character, recordID: UUID())+ let mock = MockLibraryProvider(), first = snapshot(selection, count: 60)+ mock.recordHistoryResult = .success(first)+ let model = makeWorkDetailModel(workID: selection.workID, library: mock)+ await model.selectRecordHistory(kind: selection.kind, recordID: selection.recordID)+ model.showMoreRecordHistory()+ let pair = try #require(first.rows.first?.id)+ model.setRecordHistoryExpanded(pair, expanded: true, expectedGeneration: first.generation)+ let replacement = RecordHistorySnapshot(selection: selection, generation: "replacement", availability: .available,+ activeChapterCount: 60, rows: first.rows, details: first.rows.map {+ RecordHistoryDetail(pair: $0.id, sourceText: "Fresh saved source from replacement", annotationHeads: [])+ })+ let entered = SubmissionGate(), release = SubmissionGate()+ mock.recordHistoryHandler = { _ in+ if mock.recordHistoryCalls.count == 2 {+ entered.open(); await release.wait(); return first+ }+ return replacement+ }+ let cancelled = Task { await model.refreshRecordHistory(publicationGeneration: 2) }+ await entered.wait()+ cancelled.cancel()+ // The replacement completes before the cancelled repository read is+ // released. A generation already in flight is not a completed cache hit.+ await model.refreshRecordHistory(publicationGeneration: 2)+ #expect(mock.recordHistoryCalls.count == 3)+ #expect(model.recordHistory == replacement && !model.isRefreshingRecordHistory)+ release.open(); await cancelled.value+ #expect(model.recordHistoryState == .ready && model.recordHistory == replacement)+ #expect(model.recordHistory?.activeChapterCount == 60 && model.visibleRecordHistoryRows.count == 40)+ #expect(model.expandedRecordHistoryPairs == [pair])+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: first.generation) == nil)+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: replacement.generation)?.sourceText == "Fresh saved source from replacement")+ #expect(model.recordHistoryNoteEditor(for: pair) != nil)+ await model.refreshRecordHistory(publicationGeneration: 2)+ #expect(mock.recordHistoryCalls.count == 3, "Completed current-generation reads still deduplicate")+ }++ @Test(arguments: [RecordKind.character, .place], [false, true])+ func cancelledCurrentRefreshRetainsReadyCaptureUntilRetry(kind: RecordKind, throwsCancellation: Bool) async throws {+ let selection = RecordHistorySelection(workID: UUID(), kind: kind, recordID: UUID())+ let mock = MockLibraryProvider(), first = snapshot(selection, count: 60)+ mock.recordHistoryResult = .success(first)+ let model = makeWorkDetailModel(workID: selection.workID, library: mock)+ await model.selectRecordHistory(kind: kind, recordID: selection.recordID)+ model.isRecordHistorySectionExpanded = true; model.showMoreRecordHistory()+ let pair = try #require(first.rows.first?.id)+ model.setRecordHistoryExpanded(pair, expanded: true, expectedGeneration: first.generation)+ let entered = SubmissionGate(), release = SubmissionGate()+ mock.recordHistoryHandler = { _ in+ entered.open(); await release.wait()+ if throwsCancellation { throw CancellationError() }+ return first+ }+ let cancelled = Task { await model.refreshRecordHistory(publicationGeneration: 2) }+ await entered.wait(); cancelled.cancel(); release.open(); await cancelled.value+ // Cancellation before any replacement must not unmount the reader's+ // ready history or certify the unfinished generation as current.+ #expect(model.recordHistoryState == .ready && model.recordHistory == first)+ #expect(!model.isRefreshingRecordHistory && model.isRecordHistorySectionExpanded)+ #expect(model.visibleRecordHistoryRows.count == 40 && model.expandedRecordHistoryPairs == [pair])+ #expect(model.recordHistoryNoteEditor(for: pair) == nil, "An interrupted validation does not authorize editing the old capture")+ let fresh = RecordHistorySnapshot(selection: selection, generation: "fresh", availability: .available,+ activeChapterCount: 60, rows: first.rows, details: first.rows.map {+ RecordHistoryDetail(pair: $0.id, sourceText: "Fresh source after cancelled validation", annotationHeads: [])+ })+ mock.recordHistoryHandler = nil; mock.recordHistoryResult = .success(fresh)+ await model.refreshRecordHistory(publicationGeneration: 2)+ #expect(mock.recordHistoryCalls.count == 3 && model.recordHistory == fresh)+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: first.generation) == nil)+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: fresh.generation)?.sourceText == "Fresh source after cancelled validation")+ #expect(model.recordHistoryNoteEditor(for: pair) != nil)+ }++ @Test(arguments: [RecordKind.character, .place])+ func repeatedPublicationRequestsCoalesceWithoutDiscardingRealUpdates(kind: RecordKind) async throws {+ let selection = RecordHistorySelection(workID: UUID(), kind: kind, recordID: UUID())+ let mock = MockLibraryProvider(), first = snapshot(selection, count: 60)+ mock.recordHistoryResult = .success(first)+ let model = makeWorkDetailModel(workID: selection.workID, library: mock)+ await model.selectRecordHistory(kind: kind, recordID: selection.recordID)+ model.isRecordHistorySectionExpanded = true; model.showMoreRecordHistory()+ let pair = try #require(first.rows.first?.id)+ model.setRecordHistoryExpanded(pair, expanded: true, expectedGeneration: first.generation)+ let entered = SubmissionGate(), release = SubmissionGate(), duplicateEntered = SubmissionGate()+ mock.recordHistoryHandler = { _ in entered.open(); await release.wait(); return first }+ let refresh = Task { await model.refreshRecordHistory(publicationGeneration: 2) }+ await entered.wait()+ let duplicate = Task {+ duplicateEntered.open()+ await model.refreshRecordHistory(publicationGeneration: 2)+ }+ await duplicateEntered.wait()+ #expect(mock.recordHistoryCalls.count == 2, "The same in-flight publication has one repository read")+ #expect(model.recordHistory == first && model.recordHistoryState == .ready)+ #expect(model.visibleRecordHistoryRows.count == 40 && model.expandedRecordHistoryPairs == [pair])+ release.open(); await refresh.value; await duplicate.value+ for _ in 0..<6 { await model.refreshRecordHistory(publicationGeneration: 2) }+ #expect(mock.recordHistoryCalls.count == 2, "Completed publication invalidations do not poll")+ await model.selectRecordHistory(kind: kind, recordID: selection.recordID)+ await model.refreshRecordHistory(publicationGeneration: 2)+ #expect(mock.recordHistoryCalls.count == 2, "Selecting the same target preserves its completed publication stamp")+ let changed = RecordHistorySnapshot(selection: selection, generation: "changed-ledger", availability: .available,+ activeChapterCount: 60, rows: first.rows, details: first.rows.map {+ RecordHistoryDetail(pair: $0.id, sourceText: "Actual new publication source", annotationHeads: [])+ })+ mock.recordHistoryHandler = nil; mock.recordHistoryResult = .success(changed)+ await model.refreshRecordHistory(publicationGeneration: 3)+ #expect(mock.recordHistoryCalls.count == 3 && model.recordHistory == changed)+ #expect(model.isRecordHistorySectionExpanded && model.visibleRecordHistoryRows.count == 40)+ #expect(model.expandedRecordHistoryPairs == [pair])+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: first.generation) == nil)+ #expect(model.recordHistoryNoteEditor(for: pair) != nil)+ model.clearRecordHistorySelection()+ #expect(model.recordHistory == nil && model.selectedRecordHistory == nil)+ await model.selectRecordHistory(kind: kind, recordID: selection.recordID)+ #expect(mock.recordHistoryCalls.count == 4 && model.recordHistory == changed)+ #expect(!model.isRecordHistorySectionExpanded && model.visibleRecordHistoryRows.count == 20)+ }++ @Test(arguments: [RecordKind.character, .place], [false, true])+ func newerOwedPublicationSurvivesCancelledCreatorAndOlderReentry(kind: RecordKind, throwsCancellation: Bool) async throws {+ let selection = RecordHistorySelection(workID: UUID(), kind: kind, recordID: UUID())+ let mock = MockLibraryProvider(), first = snapshot(selection, count: 60)+ let fresh = RecordHistorySnapshot(selection: selection, generation: "owed-six", availability: .available,+ activeChapterCount: 60, rows: first.rows, details: first.rows.map {+ RecordHistoryDetail(pair: $0.id, sourceText: "Actual generation six body", annotationHeads: [])+ })+ mock.recordHistoryResult = .success(first)+ let model = makeWorkDetailModel(workID: selection.workID, library: mock)+ await model.selectRecordHistory(kind: kind, recordID: selection.recordID)+ let entered = SubmissionGate(), release = SubmissionGate(), newerStarted = SubmissionGate(), freshEntered = SubmissionGate()+ mock.recordHistoryHandler = { _ in+ if mock.recordHistoryCalls.count == 2 {+ entered.open()+ // Deliberately ignore caller cancellation until the test releases+ // the old physical read, so a late return/throw remains observable.+ await Task.detached { await release.wait() }.value+ if throwsCancellation { throw CancellationError() }+ return first+ }+ freshEntered.open(); return fresh+ }+ let creator = Task { await model.refreshRecordHistory(publicationGeneration: 5) }+ await entered.wait()+ let owed = Task { newerStarted.open(); await model.refreshRecordHistory(publicationGeneration: 6) }+ await newerStarted.wait(); creator.cancel()+ await freshEntered.wait()+ #expect(mock.recordHistoryCalls.count == 3, "The newer read starts without waiting for the cancelled creator or an older re-entry")+ await model.refreshRecordHistory(publicationGeneration: 5)+ #expect(model.recordHistory == fresh, "An older re-entry services the newer obligation instead of overwriting it")+ release.open(); await creator.value; await owed.value+ #expect(mock.recordHistoryCalls.count == 3 && model.recordHistory == fresh)+ await model.refreshRecordHistory(publicationGeneration: 6)+ #expect(mock.recordHistoryCalls.count == 3, "The completed stamp belongs to owed generation six, never older re-entry five")+ let pair = try #require(first.rows.first?.id)+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: first.generation) == nil)+ #expect(model.recordHistoryNoteEditor(for: pair) != nil)+ }++ @Test(arguments: [RecordKind.character, .place])+ func cancellingJoinedWaiterDoesNotCancelSharedHistoryRead(kind: RecordKind) async throws {+ let selection = RecordHistorySelection(workID: UUID(), kind: kind, recordID: UUID())+ let mock = MockLibraryProvider(), first = snapshot(selection, count: 24)+ mock.recordHistoryResult = .success(first)+ let model = makeWorkDetailModel(workID: selection.workID, library: mock)+ await model.selectRecordHistory(kind: kind, recordID: selection.recordID)+ let entered = SubmissionGate(), release = SubmissionGate(), joinedStarted = SubmissionGate()+ mock.recordHistoryHandler = { _ in entered.open(); await release.wait(); return first }+ let creator = Task { await model.refreshRecordHistory(publicationGeneration: 2) }+ await entered.wait()+ let joined = Task { joinedStarted.open(); await model.refreshRecordHistory(publicationGeneration: 2) }+ await joinedStarted.wait(); joined.cancel()+ #expect(mock.recordHistoryCalls.count == 2)+ #expect(model.recordHistory == first && model.recordHistoryState == .ready)+ release.open(); await creator.value; await joined.value+ #expect(model.recordHistoryState == .ready && model.recordHistory == first)+ #expect(mock.recordHistoryCalls.count == 2 && !model.isRefreshingRecordHistory)+ let pair = try #require(first.rows.first?.id)+ #expect(model.recordHistoryNoteEditor(for: pair) != nil)+ await model.refreshRecordHistory(publicationGeneration: 2)+ #expect(mock.recordHistoryCalls.count == 2)+ }++ @Test(arguments: [RecordKind.character, .place])+ func noteSavedDuringReadQueuesPostMutationCaptureAndKeepsNewerPublication(kind: RecordKind) async throws {+ let selection = RecordHistorySelection(workID: UUID(), kind: kind, recordID: UUID())+ let mock = MockLibraryProvider(), first = snapshot(selection, count: 60)+ let fresh = RecordHistorySnapshot(selection: selection, generation: "post-save-six", availability: .available,+ activeChapterCount: 60, rows: first.rows, details: first.rows.map {+ RecordHistoryDetail(pair: $0.id, sourceText: "Post-mutation source and ledger", annotationHeads: [+ .init(pair: $0.id, attachmentAcceptanceIDs: [UUID()], text: "Actual saved annotation")])+ })+ mock.recordHistoryResult = .success(first)+ let mutation = SubmissionGate()+ let model = makeWorkDetailModel(workID: selection.workID, library: mock, onMutation: {+ await MainActor.run { mock.recordHistoryResult = .success(fresh); mutation.open() }+ })+ await model.selectRecordHistory(kind: kind, recordID: selection.recordID)+ let entered = SubmissionGate(), release = SubmissionGate(), newerStarted = SubmissionGate()+ mock.recordHistoryHandler = { _ in+ if mock.recordHistoryCalls.count == 2 {+ entered.open(); await release.wait(); return first+ }+ return try await MainActor.run { try mock.recordHistoryResult.get() }+ }+ let old = Task { await model.refreshRecordHistory(publicationGeneration: 5) }+ await entered.wait()+ let owed = Task { newerStarted.open(); await model.refreshRecordHistory(publicationGeneration: 6) }+ await newerStarted.wait()+ let saved = Task { await model.recordHistoryNoteSaved() }+ await mutation.wait()+ let pair = try #require(first.rows.first?.id)+ #expect(model.recordHistoryNoteEditor(for: pair) == nil, "A pre-mutation read cannot authorize the post-Save editor")+ release.open(); await old.value; await owed.value; await saved.value+ #expect(mock.recordHistoryCalls.count == 3 && model.recordHistory == fresh)+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: first.generation) == nil)+ #expect(model.recordHistoryDetail(for: pair, expectedGeneration: fresh.generation)?.annotationHeads.first?.text == "Actual saved annotation")+ #expect(model.recordHistoryNoteEditor(for: pair) != nil)+ await model.refreshRecordHistory(publicationGeneration: 6)+ #expect(mock.recordHistoryCalls.count == 3, "Forced post-mutation work does not erase the newer completed publication")+ }++ @Test func failedReadsAndClearedSelectionAreNotLoadedEmptyHistory() async {+ let selection = RecordHistorySelection(workID: UUID(), kind: .character, recordID: UUID())+ let mock = MockLibraryProvider(), model = makeWorkDetailModel(workID: selection.workID, library: mock)+ await model.selectRecordHistory(kind: selection.kind, recordID: selection.recordID)+ #expect(model.recordHistoryState == .error && model.recordHistory == nil)+ model.clearRecordHistorySelection()+ #expect(model.recordHistoryState == .idle && model.selectedRecordHistory == nil)+ }+}
diff --git a/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift b/Asterism/AsterismUITests/AccessibilityJourneyUITests.swiftindex 3b09d847..12e7303e 100644--- a/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift+++ b/Asterism/AsterismUITests/AccessibilityJourneyUITests.swift@@ -1072,9 +1072,7 @@ final class AccessibilityJourneyUITests: XCTestCase { "character-review-kind-place:kestrel head-character", "character-review-kind-place:kestrel head-place", ] {- let segment = app.buttons[identifier]- scrollUntilPresent(segment, in: app, "The review list offers \(identifier)")- scrollToElement(segment, attempts: 8)+ let segment = revealReviewControl(identifier, "The review list offers \(identifier)") assertContentControl(segment, named: "\(identifier) at largest Dynamic Type") } @@ -1416,8 +1414,27 @@ final class AccessibilityJourneyUITests: XCTestCase { /// `CharacterExtractionUITests` makes, and at `accessibility5` there is even /// less of the list on screen at once. private func tapReviewControl(_ identifier: String, _ message: String) {- for _ in 0..<6 where !app.anyElement(identifier).isHittable { app.swipeDown() }- scrollUntilTappableAndTap(app.anyElement(identifier), in: app, message)+ revealReviewControl(identifier, message).tap()+ }++ /// Saved-source rows make the largest-text review longer than eight+ /// screenfuls. Walk its own list in either direction; stop at the banner+ /// when returning upwards so the gesture cannot dismiss the sheet.+ private func revealReviewControl(+ _ identifier: String, _ message: String,+ file: StaticString = #filePath, line: UInt = #line+ ) -> XCUIElement {+ let list = app.anyElement("character-review-list")+ XCTAssertTrue(list.waitForExistence(timeout: 15), file: file, line: line)+ let control = app.anyElement(identifier)+ let banner = app.anyElement("character-review-banner")+ for _ in 0..<16 where !control.isHittable && !banner.isHittable { list.swipeDown() }+ for _ in 0..<16 {+ if control.exists && control.isHittable { return control }+ list.swipeUp()+ }+ XCTFail(message, file: file, line: line)+ return control } private func launchSeeded(scenario: String = "seeded-m1", extraArguments: [String] = []) {
diff --git a/Asterism/AsterismUITests/AssociationNotesUITests.swift b/Asterism/AsterismUITests/AssociationNotesUITests.swiftnew file mode 100644index 00000000..60f3b134--- /dev/null+++ b/Asterism/AsterismUITests/AssociationNotesUITests.swift@@ -0,0 +1,1263 @@+import XCTest++/// Same bounded saved-note/recovery journeys on phone, iPad and native Mac.+/// No UIKit dependency; every app and test-host launch selects a synthetic root.+final class AssociationNotesUITests: XCTestCase {+ private let app = XCUIApplication()+ private let chapterID = "24680000-0000-4000-8000-000000000002"+ private let characterID = "24680000-0000-4000-8000-000000000004"+ private let placeID = "24680000-0000-4000-8000-000000000005"+ private var runID = UUID().uuidString++ override func setUp() {+ continueAfterFailure = false+ terminateAndWaitForExit(app)+ launch()+ }+ override func tearDown() { terminateAndWaitForExit(app) }+ private func launch() {+ app.configureSyntheticLaunch(scenario: "seeded-association-notes", runID: runID)+ app.launch()+ XCTAssertTrue(element("recent-list").waitForExistence(timeout: 60), "UUID-contained synthetic library opens")+ }+ private func element(_ id: String) -> XCUIElement {+ app.descendants(matching: .any).matching(identifier: id).firstMatch+ }+ private func staticTextString(_ text: XCUIElement) -> String {+ #if os(macOS)+ XCTAssertEqual(text.elementType, .staticText, "Read the actual native text control")+ guard let displayed = text.value as? String else {+ retainFailure("Native static text has no string value")+ XCTFail("Native static text exposes its exact displayed string as AXValue")+ return ""+ }+ return displayed+ #else+ return text.label+ #endif+ }+ #if os(macOS)+ private func nativeMacViewport(in scroll: XCUIElement) -> CGRect {+ let window = app.windows["main"]+ XCTAssertTrue(window.exists, "The actual native main window owns this pane")+ let bounds = scroll.frame.intersection(window.frame)+ XCTAssertTrue(!bounds.isNull && !bounds.isInfinite && !bounds.isEmpty+ && bounds.origin.x.isFinite && bounds.origin.y.isFinite+ && bounds.width.isFinite && bounds.height.isFinite,+ "The native pane has a finite visible rectangle inside its window")+ return bounds+ }+ private func nativeMacScroll(_ scroll: XCUIElement, deltaY: CGFloat) {+ XCTAssertTrue(deltaY.isFinite, "Native wheel movement remains finite")+ scroll.scroll(byDeltaX: 0, deltaY: deltaY)+ }+ private func nativeMacReveal(_ control: XCUIElement, in scroll: XCUIElement) {+ XCTAssertTrue(control.waitForExistence(timeout: 15))+ for _ in 0..<10 {+ let bounds = nativeMacViewport(in: scroll)+ let frame = control.frame+ XCTAssertFalse(frame.isEmpty || frame.isInfinite || frame.isNull,+ "The real native control has measurable geometry before scrolling")+ if bounds.contains(frame) { return }+ let delta = max(-bounds.height * 0.3,+ min(bounds.height * 0.3, bounds.midY - frame.midY))+ nativeMacScroll(scroll, deltaY: delta)+ }+ XCTAssertTrue(nativeMacViewport(in: scroll).contains(control.frame),+ "Bounded native scrolling reveals the actual control")+ }+ #endif+ private func retainFailure(_ name: String) {+ let tree = XCTAttachment(string: app.debugDescription)+ tree.name = name + " accessibility tree"+ tree.lifetime = .keepAlways+ add(tree)+ #if os(macOS)+ // A Mac application has no screen rectangle of its own. Preserve the+ // hierarchy first, then capture its actual native window.+ let screenshot = XCTAttachment(screenshot: app.windows["main"].screenshot())+ #else+ let screenshot = XCTAttachment(screenshot: app.screenshot())+ #endif+ screenshot.name = name+ screenshot.lifetime = .keepAlways+ add(screenshot)+ }+ private func activate(_ value: XCUIElement) {+ let exists = value.waitForExistence(timeout: 15)+ if !exists { retainFailure("Expected association control missing") }+ XCTAssertTrue(exists, "The control exists")+ let enabled = value.isEnabled+ if !enabled { retainFailure("Expected association control disabled") }+ XCTAssertTrue(enabled, "The control is enabled")+ // Use the native element action, which scrolls its containing cell.+ // On this runtime visible enabled Form controls report isHittable=false+ // despite a normal tap opening the correct editor (controlled5/6).+ #if os(macOS)+ value.click()+ #else+ value.tap()+ #endif+ }+ private func openChapter(_ selectedChapterID: String? = nil) {+ activate(app.buttons["recent-entry-\(selectedChapterID ?? chapterID)"])+ let destination = app.descendants(matching: .any).matching(+ NSPredicate(format: "identifier IN %@", ["entry-detail-work-title", "today-inspector"])).firstMatch+ let arrived = destination.waitForExistence(timeout: 20)+ if !arrived { retainFailure("Chapter selection opened neither editor nor inspector") }+ XCTAssertTrue(arrived)+ let inspector = element("today-inspector")+ if inspector.exists { activate(inspector.buttons["Edit"].firstMatch) }+ let title = element("entry-detail-work-title")+ let opened = title.waitForExistence(timeout: 20)+ if !opened { retainFailure("Inspector Edit did not open the chapter editor") }+ XCTAssertTrue(opened)+ XCTAssertTrue(element("entry-detail-note-editor").waitForExistence(timeout: 15))+ }+ private func openNote(kind: String = "character", id: String? = nil) -> XCUIElement {+ activate(app.buttons["entry-association-\(kind)-\(id ?? characterID)"])+ let field = element("association-note-text")+ let appeared = field.waitForExistence(timeout: 15)+ if !appeared { retainFailure("Expected chapter-link editor did not open") }+ XCTAssertTrue(appeared)+ #if os(macOS)+ // The stable identifier publishes completed initial read, not validity+ // of the basis or AX enabled. Mac editability is proved by native input+ // and Save eligibility below; unchanged content must keep Save disabled.+ XCTAssertTrue(app.buttons["association-note-cancel"].isEnabled)+ XCTAssertFalse(app.buttons["association-note-save"].isEnabled)+ #else+ let loaded = XCTNSPredicateExpectation(predicate: NSPredicate(format: "enabled == true"), object: field)+ let loadedResult = XCTWaiter.wait(for: [loaded], timeout: 15)+ if loadedResult != .completed { retainFailure("Chapter-link editor did not load") }+ XCTAssertEqual(loadedResult, .completed)+ #endif+ return field+ }+ #if os(macOS)+ private func nativeMacFieldInput(_ field: XCUIElement, edit: () -> Void) {+ XCTAssertTrue(field.waitForExistence(timeout: 15))+ XCTAssertTrue(app.buttons["association-note-cancel"].isEnabled)+ // This runtime reports false AX enabled for an actually editable native+ // TextView. Normal click/keyboard input must succeed; never force values.+ field.click()+ edit()+ }+ private func requireNativeMacDirtySave() {+ let save = app.buttons["association-note-save"]+ let dirty = XCTNSPredicateExpectation(predicate: NSPredicate(format: "enabled == true"), object: save)+ XCTAssertEqual(XCTWaiter.wait(for: [dirty], timeout: 15), .completed,+ "The real exact draft enables Save")+ }+ #endif+ private func replace(_ field: XCUIElement, with text: String) {+ #if os(macOS)+ if field.identifier == "entry-detail-note-editor" {+ XCTAssertTrue(field.waitForExistence(timeout: 15))+ field.click()+ field.typeKey("a", modifierFlags: .command)+ field.typeText(text)+ } else {+ nativeMacFieldInput(field) {+ field.typeKey("a", modifierFlags: .command)+ field.typeText(text)+ }+ }+ #else+ activate(field)+ // Established ChapterNotes replacement driver: explicitly position the+ // caret at the end of these one-line fixture values before backspace.+ field.coordinate(withNormalizedOffset: CGVector(dx: 0.98, dy: 0.5)).tap()+ let old = field.value as? String ?? ""+ field.typeText(String(repeating: XCUIKeyboardKey.delete.rawValue, count: old.count + 2) + text)+ #endif+ XCTAssertEqual(Array((field.value as? String ?? "").utf8), Array(text.utf8),+ "The exact replacement draft landed before Save")+ #if os(macOS)+ if field.identifier == "entry-detail-note-editor" {+ XCTAssertTrue(app.buttons["entry-detail-update-button"].isEnabled,+ "The actual Entry update action remains available for the exact draft")+ } else {+ requireNativeMacDirtySave()+ }+ #endif+ }+ private func close(_ id: String) {+ activate(app.buttons[id])+ let gone = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: element("association-note-text"))+ let closed = XCTWaiter.wait(for: [gone], timeout: 20)+ if closed != .completed { retainFailure("Chapter-link editor did not close") }+ XCTAssertEqual(closed, .completed)+ }+ private func openHistoryWork() {+ #if os(macOS)+ activate(app.buttons["recent-entry-24680000-0000-4000-8000-000000000028"])+ XCTAssertTrue(element("today-inspector").waitForExistence(timeout: 15))+ activate(app.buttons["today-inspector-open-work"])+ #else+ openAllWorks(in: app)+ activate(element("work-row-24680000-0000-4000-8000-000000000001"))+ #endif+ XCTAssertTrue(element("work-detail-title").waitForExistence(timeout: 20))+ }++ private func openHistoryFixture() {+ terminateAndWaitForExit(app)+ runID = UUID().uuidString+ app.configureSyntheticLaunch(scenario: "seeded-record-history", runID: runID)+ #if !os(macOS)+ app.launchArguments += ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityM"]+ #endif+ app.launch()+ XCTAssertTrue(element("recent-list").waitForExistence(timeout: 60))+ openHistoryWork()+ XCTAssertTrue(element("work-detail-title").waitForExistence(timeout: 20))+ }++ private func toggleHistoryDisclosure() {+ // The identifier belongs to the semantic label, not the whole group:+ // descendants retain their own row and action identities.+ #if os(macOS)+ let disclosure = app.disclosureTriangles["record-history-count"]+ XCTAssertTrue(disclosure.waitForExistence(timeout: 15))+ let before = (disclosure.value as? NSNumber)?.stringValue ?? disclosure.value as? String+ XCTAssertTrue(before == "0" || before == "1", "The native disclosure reports its expansion state")+ nativeMacReveal(disclosure, in: element("work-detail-scroll"))+ let windowFrame = app.windows["main"].frame+ let controlFrame = disclosure.frame+ XCTAssertFalse(windowFrame.isEmpty || windowFrame.isInfinite || windowFrame.isNull)+ XCTAssertFalse(controlFrame.isEmpty || controlFrame.isInfinite || controlFrame.isNull)+ XCTAssertTrue(windowFrame.contains(controlFrame), "The native disclosure is inside its actual window")+ // Retained native screenshots place the chevron about 25 points into+ // this AX rectangle; its left edge includes blank leading padding.+ // Click the visible chevron, not that padding or the label's centre.+ disclosure.coordinate(withNormalizedOffset: CGVector(dx: 0, dy: 0.5))+ .withOffset(CGVector(dx: 25, dy: 0)).click()+ let expected = before == "0" ? "1" : "0"+ let changed = XCTNSPredicateExpectation(+ predicate: NSPredicate(format: "value == %@ OR value == %@", expected,+ NSNumber(value: expected == "1" ? 1 : 0)), object: disclosure)+ let result = XCTWaiter.wait(for: [changed], timeout: 15)+ if result != .completed { retainFailure("Native chapter disclosure did not change state") }+ XCTAssertEqual(result, .completed,+ "Native disclosure activation changes its actual expanded state")+ #else+ activate(element("record-history-count"))+ #endif+ }++ private func assertHistoryTitleDate(_ target: String, title expected: String) {+ let row = app.buttons["record-history-row-\(target)"]+ let title = element("record-history-\(target)-title"), date = element("record-history-\(target)-date")+ XCTAssertTrue(title.waitForExistence(timeout: 15) && date.exists)+ XCTAssertEqual(staticTextString(title), expected)+ XCTAssertEqual(staticTextString(date), "Today")+ XCTAssertLessThan(title.frame.minX, date.frame.minX)+ XCTAssertGreaterThanOrEqual(date.frame.maxX, row.frame.maxX - 4,+ "History dates align with the trailing edge, not the title's intrinsic width")+ XCTAssertGreaterThanOrEqual(date.frame.midY, title.frame.minY)+ XCTAssertLessThanOrEqual(date.frame.midY, title.frame.maxY)+ }++ func testExpandedHistoryStaysStableThroughRealPublicationsAndReentry() {+ app.launchEnvironment["ASTERISM_UI_TEST_HISTORY_REFRESH"] = "1"+ openHistoryFixture()+ var observations: [String] = []+ defer {+ let trace = XCTAttachment(string: observations.joined(separator: "\n"))+ trace.name = "Sustained history real-publication temporal trace"; trace.lifetime = .keepAlways; add(trace)+ }+ var stable = true, boundedReads = true, noPolling = true+ func expose(_ control: XCUIElement) {+ let detail = element("work-detail-scroll")+ func viewport() -> CGRect {+ #if os(macOS)+ let bounds = nativeMacViewport(in: detail)+ #else+ let bounds = detail.frame.intersection(app.frame)+ #endif+ #if os(macOS)+ let navigation = app.navigationBars.firstMatch+ let top = navigation.exists ? max(bounds.minY, navigation.frame.maxY + 4) : bounds.minY+ #else+ let top = max(bounds.minY, app.navigationBars.firstMatch.frame.maxY + 4)+ #endif+ let bottom = min(bounds.maxY, element("record-history-test-publish").frame.minY - 4)+ return CGRect(x: bounds.minX, y: top, width: bounds.width, height: max(0, bottom - top))+ }+ for _ in 0..<8 {+ if control.exists && viewport().contains(control.frame) { return }+ if !control.exists {+ #if os(macOS)+ nativeMacScroll(detail, deltaY: -nativeMacViewport(in: detail).height * 0.25)+ #else+ detail.swipeUp()+ #endif+ continue+ }+ let distance = max(-0.25, min(0.25, (viewport().midY - control.frame.midY) / detail.frame.height))+ #if os(macOS)+ nativeMacScroll(detail, deltaY: distance * nativeMacViewport(in: detail).height)+ #else+ detail.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))+ .press(forDuration: 0.1, thenDragTo: detail.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5 + distance)))+ #endif+ }+ XCTAssertTrue(control.exists && viewport().contains(control.frame), "The actual control is fully clear of navigation and the fixed fixture footer")+ }+ func tapRecordPill(_ kind: String, movingDown: Bool) {+ let pill = app.buttons.matching(identifier: "work-detail-" + kind).firstMatch+ let detail = element("work-detail-scroll")+ func isClear() -> Bool {+ guard pill.exists else { return false }+ #if os(macOS)+ var viewport = nativeMacViewport(in: detail)+ #else+ var viewport = detail.frame.intersection(app.frame)+ #endif+ viewport.size.height = max(0, min(viewport.maxY, element("record-history-test-publish").frame.minY) - viewport.minY)+ let navigation = app.navigationBars.firstMatch+ return viewport.contains(pill.frame) && (!navigation.exists || pill.frame.minY >= navigation.frame.maxY)+ }+ for _ in 0..<8 where !isClear() {+ #if os(macOS)+ nativeMacScroll(detail, deltaY: nativeMacViewport(in: detail).height * (movingDown ? -0.25 : 0.25))+ #else+ if movingDown { detail.swipeUp() } else { detail.swipeDown() }+ #endif+ }+ XCTAssertTrue(isClear(), "The record capsule is clear of navigation and the fixed fixture footer")+ #if os(macOS)+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).click()+ #else+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).tap()+ #endif+ }+ for kind in ["character", "place"] {+ tapRecordPill(kind, movingDown: true)+ let count = element("record-history-count")+ XCTAssertTrue(count.waitForExistence(timeout: 15))+ expose(count); toggleHistoryDisclosure()+ let row = app.buttons["record-history-row-\(chapterID)"]+ expose(row); activate(row)+ let source = element("record-history-source-\(chapterID)")+ XCTAssertTrue(source.waitForExistence(timeout: 15)); expose(source)+ let bytes = Array(staticTextString(source).utf8), initialY = source.frame.minY, expectedCount = count.label+ let metrics = element("record-history-test-metrics")+ func value(_ key: String) -> String {+ staticTextString(metrics).split(separator: ";").first(where: { $0.hasPrefix(key + "=") })+ .map { String($0.dropFirst(key.count + 1)) } ?? "missing"+ }+ let startReads = Int(value("starts")) ?? -100+ let startPublications = Int(value("publications")) ?? -100+ let capture = value("capture")+ for pulse in 0..<3 {+ activate(app.buttons["record-history-test-publish"])+ let until = Date().addingTimeInterval(5)+ repeat {+ let present = source.exists && count.exists+ let same = present && Array(staticTextString(source).utf8) == bytes && count.label == expectedCount+ && abs(source.frame.minY - initialY) < 2 && value("capture") == capture+ stable = stable && same && !element("record-history-refreshing").exists+ observations.append("\(Date().timeIntervalSince1970) kind=\(kind) pulse=\(pulse) sourceY=\(source.exists ? source.frame.minY : -1) stable=\(same) \(staticTextString(metrics))")+ } while Date() < until+ retainFailure("\(kind) expanded history publication \(pulse)")+ let partialTrace = XCTAttachment(string: observations.joined(separator: "\n"))+ partialTrace.name = "\(kind) temporal trace through publication \(pulse)"; partialTrace.lifetime = .keepAlways; add(partialTrace)+ }+ let endReads = Int(value("starts")) ?? -100+ let publicationCount = (Int(value("publications")) ?? -100) - startPublications+ boundedReads = boundedReads && publicationCount == 3 && endReads - startReads == publicationCount+ let idleUntil = Date().addingTimeInterval(5)+ repeat {+ observations.append("\(Date().timeIntervalSince1970) idle kind=\(kind) \(staticTextString(metrics))")+ noPolling = noPolling && Int(value("starts")) == endReads+ } while Date() < idleUntil+ // Fold only this record; the other kind is a separate typed selection.+ tapRecordPill(kind, movingDown: false)+ }+ XCTAssertTrue(stable, "Expanded source/count/capture/viewport stay stable throughout actual publications")+ XCTAssertTrue(boundedReads, "Each real new publication revalidates once; same-generation requests share it")+ XCTAssertTrue(noPolling, "No history reads occur during separate idle intervals")+ // Re-enter after another typed selection, then exercise the actual note+ // editor. A Save is a real forced revalidation, not a display hash hit.+ tapRecordPill("character", movingDown: false)+ XCTAssertTrue(element("record-history-count").waitForExistence(timeout: 15))+ toggleHistoryDisclosure(); activate(app.buttons["record-history-row-\(chapterID)"])+ activate(app.buttons["record-history-edit-\(chapterID)"])+ let field = element("association-note-text")+ XCTAssertTrue(field.waitForExistence(timeout: 15))+ #if os(macOS)+ nativeMacFieldInput(field) { field.typeText("Stable history publication note") }+ requireNativeMacDirtySave()+ #else+ activate(field)+ field.typeText("Stable history publication note")+ #endif+ let savedAnnotation = field.value as? String ?? ""+ XCTAssertTrue(savedAnnotation.contains("Stable history publication note"))+ close("association-note-save")+ XCTAssertTrue(app.staticTexts[savedAnnotation].waitForExistence(timeout: 15))+ activate(app.buttons["record-history-open-\(chapterID)"])+ XCTAssertTrue(element("entry-detail-note-editor").waitForExistence(timeout: 20))+ #if os(macOS)+ // This chapter was pushed from the retained Work. Native Back uses+ // that existing parent; Open Work's separate failed action is tracked.+ activate(app.buttons["Back"].firstMatch)+ #else+ activate(app.buttons["entry-detail-work-title"])+ #endif+ XCTAssertTrue(element("work-detail-title").waitForExistence(timeout: 20))+ let restoredCount = element("record-history-count")+ if !restoredCount.waitForExistence(timeout: 10) { tapRecordPill("character", movingDown: true) }+ XCTAssertTrue(restoredCount.waitForExistence(timeout: 15))+ XCTAssertEqual(restoredCount.label, "Chapters (24)")+ expose(restoredCount)+ let restoredRow = app.buttons["record-history-row-\(chapterID)"]+ if !restoredRow.exists { toggleHistoryDisclosure() }+ expose(restoredRow)+ let restoredSource = element("record-history-source-\(chapterID)")+ if !restoredSource.exists { activate(restoredRow) }+ XCTAssertTrue(restoredSource.waitForExistence(timeout: 15)); expose(restoredSource)+ XCTAssertEqual(Array(staticTextString(restoredSource).utf8), Array("Alice visits Harbor.".utf8))+ XCTAssertTrue(app.staticTexts[savedAnnotation].waitForExistence(timeout: 15))+ let restoredEdit = app.buttons["record-history-edit-\(chapterID)"]+ expose(restoredEdit)+ XCTAssertTrue(restoredEdit.isEnabled, "Re-entry uses a fresh captured basis for the existing editor")+ retainFailure("Expanded character history after actual Save and chapter re-entry")+ }++ func testSavingChapterNoteImmediatelyPublishesKnownCharacterAndPlaceLinks() {+ let target = "24680000-0000-4000-8000-000000000003"+ let exact = "ALICE visits HARBOR. Saved together."+ func expose(_ control: XCUIElement) {+ let scroll = element("work-detail-scroll")+ for _ in 0..<10 {+ #if os(macOS)+ let bounds = nativeMacViewport(in: scroll)+ #else+ let bounds = scroll.frame.intersection(app.frame)+ #endif+ let navigation = app.navigationBars.firstMatch+ let top = navigation.exists ? max(bounds.minY, navigation.frame.maxY + 4) : bounds.minY+ let viewport = CGRect(x: bounds.minX, y: top, width: bounds.width, height: max(0, bounds.maxY - top))+ if control.exists && viewport.contains(control.frame) { return }+ if !control.exists {+ #if os(macOS)+ nativeMacScroll(scroll, deltaY: -nativeMacViewport(in: scroll).height * 0.25)+ #else+ scroll.swipeUp()+ #endif+ continue+ }+ let distance = max(-0.25, min(0.25, (viewport.midY - control.frame.midY) / max(1, bounds.height)))+ #if os(macOS)+ nativeMacScroll(scroll, deltaY: distance * nativeMacViewport(in: scroll).height)+ #else+ scroll.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))+ .press(forDuration: 0.1, thenDragTo: scroll.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5 + distance)))+ #endif+ }+ XCTAssertTrue(control.exists && control.isHittable, "The saved-note control is reachable in the actual Work viewport")+ }+ @discardableResult+ func showHistory(_ kind: String, recordID: String, count: Int) -> XCUIElement {+ let name = kind == "character" ? "Alice" : "Harbor"+ let pill = app.buttons.matching(identifier: "work-detail-" + kind).firstMatch+ expose(pill)+ // Center the actual capsule before inspecting its immediately+ // following card. Offscreen lazy cells cannot decide whether this+ // record needs expanding or its existing Show chapters action.+ let scroll = element("work-detail-scroll")+ #if os(macOS)+ let bounds = nativeMacViewport(in: scroll)+ #else+ let bounds = scroll.frame.intersection(app.frame)+ #endif+ let distance = max(-0.25, min(0.25, (bounds.midY - pill.frame.midY) / max(1, bounds.height)))+ if abs(distance) > 0.02 {+ #if os(macOS)+ nativeMacScroll(scroll, deltaY: distance * nativeMacViewport(in: scroll).height)+ #else+ scroll.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))+ .press(forDuration: 0.1, thenDragTo: scroll.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5 + distance)))+ #endif+ }+ // Bind the exact visible name and selected history to this typed card.+ // Phone retains its Form cell; Mac exposes the real card group.+ #if os(macOS)+ let card = element("work-detail-record-card-\(kind)-\(recordID)")+ let selectedHistory = card.disclosureTriangles["record-history-count"]+ let alreadySelected = card.exists && selectedHistory.exists+ #else+ let card = app.cells.containing(.staticText, identifier: name)+ .containing(.button, identifier: "record-history-count").firstMatch+ let alreadySelected = card.exists+ #endif+ if !alreadySelected {+ let select = app.buttons["record-history-select-\(kind)-\(recordID)"]+ if select.exists {+ expose(select); activate(select)+ } else {+ #if os(macOS)+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).click()+ #else+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).tap()+ #endif+ }+ }+ let selected = card.waitForExistence(timeout: 15)+ if !selected { retainFailure("Intended typed record history was not selected") }+ XCTAssertTrue(selected, "The \(name) card itself owns the selected Chapters control")+ #if os(macOS)+ XCTAssertTrue(card.staticTexts[name].exists, "The typed record card owns its real visible name")+ let label = card.disclosureTriangles["record-history-count"]+ XCTAssertTrue(label.waitForExistence(timeout: 15), "The typed record card owns the actual Chapters disclosure")+ #else+ let label = card.descendants(matching: .any).matching(identifier: "record-history-count").firstMatch+ #endif+ let updated = XCTNSPredicateExpectation(predicate: NSPredicate(format: "label == %@", "Chapters (\(count))"), object: label)+ XCTAssertEqual(XCTWaiter.wait(for: [updated], timeout: 15), .completed)+ expose(label)+ return card+ }+ func entryForm(containing field: XCUIElement) -> XCUIElement {+ #if os(macOS)+ // Native Form exports a flattened pane marker. The TextEditor's+ // internal ScrollView owns only note text, not its sibling links.+ let pane = element("entry-detail-\(target)")+ XCTAssertTrue(pane.waitForExistence(timeout: 15))+ XCTAssertTrue(nativeMacViewport(in: pane).contains(field.frame),+ "The selected Entry's actual pane contains its note editor")+ return pane+ #else+ // Resolve the actual Entry pane while its editor is visible, then+ // retain the index query as Form lazily removes offscreen rows.+ // A descendant-filter query would stop matching the same Form as+ // soon as the note editor scrolled out of its realized window.+ for collection in [app.collectionViews, app.scrollViews] {+ for index in 0..<collection.count {+ let candidate = collection.element(boundBy: index)+ if candidate.descendants(matching: .any).matching(identifier: "entry-detail-note-editor").firstMatch.exists {+ return candidate+ }+ }+ }+ retainFailure("Entry editor has no containing native Form")+ XCTFail("The Entry pane owns a native scroll container containing its note editor")+ return field+ #endif+ }+ func revealEntry(_ control: XCUIElement, in form: XCUIElement, towardTop: Bool = false, assertingNoLinks: Bool = false) {+ func viewport() -> CGRect {+ #if os(macOS)+ var bounds = nativeMacViewport(in: form)+ #else+ var bounds = form.frame.intersection(app.frame)+ #endif+ for navigation in app.navigationBars.allElementsBoundByIndex where navigation.frame.intersects(bounds) {+ let top = max(bounds.minY, navigation.frame.maxY + 4)+ bounds = CGRect(x: bounds.minX, y: top, width: bounds.width, height: max(0, bounds.maxY - top))+ }+ for tab in app.tabBars.allElementsBoundByIndex where tab.frame.intersects(bounds) {+ bounds.size.height = max(0, min(bounds.maxY, tab.frame.minY - 4) - bounds.minY)+ }+ for keyboard in app.keyboards.allElementsBoundByIndex where keyboard.frame.intersects(bounds) {+ bounds.size.height = max(0, min(bounds.maxY, keyboard.frame.minY - 4) - bounds.minY)+ }+ #if os(macOS)+ // Full-width native controls legitimately share the pane edges.+ return bounds+ #else+ return bounds.insetBy(dx: 6, dy: 6)+ #endif+ }+ for _ in 0..<10 {+ let bounds = viewport()+ if assertingNoLinks {+ let character = app.buttons["entry-association-character-\(characterID)"]+ let place = app.buttons["entry-association-place-\(placeID)"]+ if character.exists || place.exists { retainFailure("Unexpected saved link while scanning the Entry Form") }+ XCTAssertFalse(character.exists, "No saved character link anywhere along the realized Chapter links section")+ XCTAssertFalse(place.exists, "No saved place link anywhere along the realized Chapter links section")+ }+ if control.exists && bounds.contains(control.frame) { return }+ guard bounds.width > 0 && bounds.height > 0 else { break }+ #if os(macOS)+ // The flattened native Form has no outer scroll container.+ // Do not scroll the note's internal TextView to reveal siblings.+ break+ #else+ let delta = control.exists+ ? max(-bounds.height * 0.3, min(bounds.height * 0.3, bounds.midY - control.frame.midY))+ : bounds.height * (towardTop ? 0.3 : -0.3)+ let origin = form.coordinate(withNormalizedOffset: .zero)+ let from = origin.withOffset(CGVector(dx: bounds.midX - form.frame.minX, dy: bounds.midY - form.frame.minY))+ let to = origin.withOffset(CGVector(dx: bounds.midX - form.frame.minX, dy: bounds.midY + delta - form.frame.minY))+ from.press(forDuration: 0.1, thenDragTo: to)+ #endif+ }+ retainFailure("Entry Form control not fully revealed")+ XCTAssertTrue(control.exists && viewport().contains(control.frame),+ "Bounded scrolling inside this Entry pane reveals the entire control clear of navigation and tabs")+ }+ func scanEntryHasNoLinks(_ form: XCUIElement, field: XCUIElement, expectedDraft: String) {+ revealEntry(field, in: form, towardTop: true)+ // The existing footer follows every link in this same Form section.+ // Scan from the note to that visible footer, checking both types at+ // every small scroll step, so lazy offscreen rows cannot prove absence.+ let footer = app.buttons["entry-skipped-character-links"]+ revealEntry(footer, in: form, assertingNoLinks: true)+ XCTAssertTrue(footer.exists)+ revealEntry(field, in: form, towardTop: true)+ XCTAssertEqual(Array((field.value as? String ?? "").utf8), Array(expectedDraft.utf8),+ "Revealing the saved metadata never changes the actual unsaved note draft")+ }+ func saveAndReturnToWork() {+ activate(app.buttons["entry-detail-update-button"])+ let work = element("work-detail-title")+ if !work.waitForExistence(timeout: 20) {+ #if os(macOS)+ activate(app.buttons["Back"].firstMatch)+ #else+ activate(app.buttons["entry-detail-work-title"])+ #endif+ }+ XCTAssertTrue(work.waitForExistence(timeout: 20), "Actual Save returns to the chapter's existing Work route")+ }+ // Enter through the real Work/history reader so terminal Save returns+ // to the same published Work model instead of relaunching the fixture.+ #if os(macOS)+ // This journey uses the two-chapter association-notes fixture, not the+ // separate record-history fixture whose recent chapter is 28.+ activate(app.buttons["recent-entry-\(target)"])+ XCTAssertTrue(element("today-inspector").waitForExistence(timeout: 15))+ activate(app.buttons["today-inspector-open-work"])+ XCTAssertTrue(element("work-detail-title").waitForExistence(timeout: 20))+ #else+ openHistoryWork()+ #endif+ showHistory("character", recordID: characterID, count: 2)+ toggleHistoryDisclosure()+ let row = app.buttons["record-history-row-\(target)"]+ expose(row); activate(row)+ let open = app.buttons["record-history-open-\(target)"]+ expose(open); activate(open)+ let field = element("entry-detail-note-editor")+ XCTAssertTrue(field.waitForExistence(timeout: 20))+ var form = entryForm(containing: field)+ let characterReference = app.buttons["entry-association-character-\(characterID)"]+ let placeReference = app.buttons["entry-association-place-\(placeID)"]+ revealEntry(characterReference, in: form); XCTAssertTrue(characterReference.exists)+ revealEntry(placeReference, in: form); XCTAssertTrue(placeReference.exists)+ revealEntry(field, in: form, towardTop: true)+ replace(field, with: "Nobody visits.")+ saveAndReturnToWork()+ let count = element("record-history-count")+ XCTAssertTrue(count.waitForExistence(timeout: 15))+ let removed = XCTNSPredicateExpectation(predicate: NSPredicate(format: "label == %@", "Chapters (1)"), object: count)+ XCTAssertEqual(XCTWaiter.wait(for: [removed], timeout: 15), .completed)+ XCTAssertFalse(row.exists, "The old character membership was retired by the first actual Save")+ showHistory("place", recordID: placeID, count: 1)+ // Return has no accepted links now, so reopen its ordinary spine row.+ let spine = app.buttons.matching(NSPredicate(format: "identifier == %@ AND label CONTAINS %@", "work-detail-entry", "Return")).firstMatch+ expose(spine)+ #if os(macOS)+ XCTAssertTrue(element("work-detail-focused-entry-\(target)").exists,+ "The requested saved chapter owns the focused-row Edit action")+ let editChapter = app.buttons["work-detail-edit-focused-entry-\(target)"]+ expose(editChapter)+ activate(editChapter)+ #else+ activate(spine)+ #endif+ let reopened = field.waitForExistence(timeout: 20)+ if !reopened { retainFailure("Save-time chapter re-entry and Today path trace") }+ XCTAssertTrue(reopened)+ form = entryForm(containing: field)+ XCTAssertEqual(field.value as? String, "Nobody visits.")+ scanEntryHasNoLinks(form, field: field, expectedDraft: "Nobody visits.")+ XCTAssertFalse(app.buttons["entry-association-character-\(characterID)"].exists)+ XCTAssertFalse(app.buttons["entry-association-place-\(placeID)"].exists)+ revealEntry(field, in: form, towardTop: true)+ replace(field, with: exact)+ scanEntryHasNoLinks(form, field: field, expectedDraft: exact)+ XCTAssertFalse(app.buttons["entry-association-character-\(characterID)"].exists,+ "Typing a draft cannot publish a character link")+ XCTAssertFalse(app.buttons["entry-association-place-\(placeID)"].exists,+ "Typing a draft cannot publish a place link")+ saveAndReturnToWork()+ // Both records retain their original identities; no review or AI is+ // involved. Each captured history must show the final saved bytes.+ for (kind, recordID) in [("character", characterID), ("place", placeID)] {+ let card = showHistory(kind, recordID: recordID, count: 2)+ let selectedRow = card.buttons["record-history-row-\(target)"]+ if !selectedRow.exists { toggleHistoryDisclosure() }+ expose(selectedRow)+ let source = card.descendants(matching: .any).matching(identifier: "record-history-source-\(target)").firstMatch+ if !source.exists { activate(selectedRow) }+ XCTAssertTrue(source.waitForExistence(timeout: 15)); expose(source)+ XCTAssertEqual(Array(staticTextString(source).utf8), Array(exact.utf8))+ assertHistoryTitleDate(target, title: "Return")+ retainFailure("Save-time known \(kind) chapter link and exact source")+ }+ expose(open); activate(open)+ XCTAssertTrue(field.waitForExistence(timeout: 20))+ XCTAssertEqual(Array((field.value as? String ?? "").utf8), Array(exact.utf8))+ form = entryForm(containing: field)+ revealEntry(characterReference, in: form)+ XCTAssertTrue(characterReference.exists)+ revealEntry(placeReference, in: form)+ XCTAssertTrue(placeReference.exists,+ "The coherent Entry detail reload exposes both saved typed links")+ retainFailure("Saved chapter exposes both known record references")+ }++ func testPlaceHistoryUsesActualChapterTitleAndTrailingDate() {+ openHistoryFixture()+ let pill = app.buttons.matching(identifier: "work-detail-place").firstMatch+ XCTAssertTrue(pill.waitForExistence(timeout: 15) && pill.isEnabled)+ #if os(macOS)+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).click()+ #else+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).tap()+ #endif+ XCTAssertTrue(element("record-history-count").waitForExistence(timeout: 15))+ XCTAssertEqual(element("record-history-count").label, "Chapters (2)")+ XCTAssertFalse(app.buttons["record-history-row-\(chapterID)"].exists)+ toggleHistoryDisclosure()+ assertHistoryTitleDate(chapterID, title: "Arrival")+ XCTAssertFalse(app.staticTexts["Chapter 1"].exists)+ activate(app.buttons["record-history-row-\(chapterID)"])+ XCTAssertEqual(Array(staticTextString(element("record-history-source-\(chapterID)")).utf8), Array("Alice visits Harbor.".utf8))+ retainFailure("Place history actual title and trailing date")+ }++ func testRecordHistoryWindowsCapturedBodiesAndExistingEditorRoute() {+ openHistoryFixture()+ let pill = app.buttons.matching(identifier: "work-detail-character").firstMatch+ XCTAssertTrue(pill.waitForExistence(timeout: 15) && pill.isEnabled)+ // The existing capsule's AX frame spans the row; its visible hit shape+ // is at the leading edge (same driver as CharacterExtractionUITests).+ #if os(macOS)+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).click()+ #else+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).tap()+ #endif+ XCTAssertTrue(element("record-history-count").waitForExistence(timeout: 15))+ XCTAssertEqual(element("record-history-count").label, "Chapters (24)")+ let rows = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "record-history-row-"))+ XCTAssertEqual(rows.count, 0, "A newly selected record starts collapsed")+ XCTAssertFalse(app.buttons["record-history-more"].exists)+ toggleHistoryDisclosure()+ if rows.count != 20 { retainFailure("Expanded history did not expose 20 native row buttons") }+ XCTAssertEqual(rows.count, 20, "Only the first local window is rendered")+ activate(app.buttons["record-history-more"])+ if rows.count != 24 { retainFailure("Paginated history did not expose 24 native row buttons") }+ XCTAssertEqual(rows.count, 24, "Show more uses the captured local window")+ assertHistoryTitleDate("24680000-0000-4000-8000-000000000006", title: "Shared title")+ assertHistoryTitleDate("24680000-0000-4000-8000-000000000007", title: "Shared title")+ XCTAssertFalse(app.staticTexts["Chapter 6"].exists || app.staticTexts["Chapter 7"].exists,+ "Titled chapters have no redundant designation heading")+ let target = "24680000-0000-4000-8000-000000000006"+ activate(app.buttons["record-history-row-\(target)"])+ let source = element("record-history-source-\(target)")+ XCTAssertTrue(source.waitForExistence(timeout: 15))+ XCTAssertEqual(Array(staticTextString(source).utf8), Array(" Alice reads Cafe\u{301}.\nExact saved chapter 6. ".utf8))+ #if os(macOS)+ // The real title/date sibling retains the old title-click expansion+ // route, independently of the genuine native preview Button above.+ let title = element("record-history-\(target)-title")+ nativeMacReveal(title, in: element("work-detail-scroll"))+ title.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).click()+ let folded = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: source)+ XCTAssertEqual(XCTWaiter.wait(for: [folded], timeout: 15), .completed,+ "One title click folds the saved source exactly once")+ nativeMacReveal(title, in: element("work-detail-scroll"))+ title.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).click()+ XCTAssertTrue(source.waitForExistence(timeout: 15), "One more title click reopens the same saved source")+ XCTAssertEqual(Array(staticTextString(source).utf8), Array(" Alice reads Cafe\u{301}.\nExact saved chapter 6. ".utf8))+ #endif+ XCTAssertTrue(app.staticTexts["Saved chapter note"].exists)+ XCTAssertTrue(app.staticTexts["Your link note"].exists)+ XCTAssertFalse(app.staticTexts.matching(NSPredicate(format: "label BEGINSWITH %@", "Saved note ")).firstMatch.exists)+ toggleHistoryDisclosure()+ XCTAssertEqual(rows.count, 0)+ XCTAssertFalse(source.exists)+ XCTAssertFalse(app.buttons["record-history-more"].exists)+ toggleHistoryDisclosure()+ XCTAssertEqual(rows.count, 24, "Reopening preserves the local window")+ XCTAssertTrue(source.exists, "Reopening preserves the expanded source row")+ retainFailure("Rendered history at accessibility size")+ activate(app.buttons["record-history-edit-\(target)"])+ let field = element("association-note-text")+ XCTAssertTrue(field.waitForExistence(timeout: 15))+ replace(field, with: "Reader history annotation")+ close("association-note-cancel")+ toggleHistoryDisclosure(); XCTAssertEqual(rows.count, 0); toggleHistoryDisclosure()+ XCTAssertEqual(rows.count, 24)+ activate(app.buttons["record-history-edit-\(target)"])+ XCTAssertEqual(element("association-note-text").value as? String, "", "Cancel never writes")+ replace(element("association-note-text"), with: "Reader history annotation")+ close("association-note-save")+ XCTAssertTrue(app.staticTexts["Reader history annotation"].waitForExistence(timeout: 15))+ XCTAssertEqual(rows.count, 24, "Saving preserves the expanded section and local window")+ toggleHistoryDisclosure(); XCTAssertFalse(source.exists); toggleHistoryDisclosure()+ XCTAssertTrue(app.staticTexts["Reader history annotation"].exists)+ activate(app.buttons["record-history-open-\(target)"])+ XCTAssertTrue(element("entry-detail-note-editor").waitForExistence(timeout: 20))+ }++ func testLongSavedChapterNoteRemainsFullyReadableAndActionsReachable() {+ openHistoryFixture()+ let target = "24680000-0000-4000-8000-000000000006"+ let pill = app.buttons.matching(identifier: "work-detail-character").firstMatch+ XCTAssertTrue(pill.waitForExistence(timeout: 15) && pill.isEnabled)+ #if os(macOS)+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).click()+ #else+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).tap()+ #endif+ XCTAssertTrue(element("record-history-count").waitForExistence(timeout: 15))+ XCTAssertEqual(element("record-history-count").label, "Chapters (24)")+ toggleHistoryDisclosure()+ activate(app.buttons["record-history-row-\(target)"])+ let source = element("record-history-source-\(target)")+ XCTAssertTrue(source.waitForExistence(timeout: 15))+ activate(app.buttons["record-history-open-\(target)"])+ let note = element("entry-detail-note-editor")+ XCTAssertTrue(note.waitForExistence(timeout: 20))+ let original = note.value as? String ?? ""+ XCTAssertEqual(Array(original.utf8), Array(" Alice reads Cafe\u{301}.\nExact saved chapter 6. ".utf8))+ let paragraphs = (1...12).map {+ "Long source paragraph \($0). Alice keeps the whole saved chapter note readable, including every line beyond the initial preview."+ }.joined(separator: "\n\n")+ let suffix = "\n\n" + paragraphs + "\n\nEnding long source marker."+ #if os(macOS)+ // Native TextView AX enabled is false on this runtime even when normal+ // keyboard editing works; prove the actual draft rather than force it.+ note.click()+ note.typeKey(XCUIKeyboardKey.downArrow.rawValue, modifierFlags: .command)+ #else+ activate(note)+ // The saved two-line fixture leaves empty space below its final line;+ // the native trailing-bottom tap positions the insertion point at end.+ note.coordinate(withNormalizedOffset: CGVector(dx: 0.98, dy: 0.95)).tap()+ #endif+ note.typeText(suffix)+ let exact = note.value as? String ?? ""+ XCTAssertEqual(Array(exact.utf8), Array((original + suffix).utf8),+ "Native append preserves every original NFD/whitespace byte and the whole multiline suffix")+ XCTAssertNotEqual(exact, original)+ XCTAssertTrue(exact.contains(suffix), "The full multiline draft landed through native input")+ XCTAssertGreaterThan(exact.utf8.count, 1_400)+ activate(app.buttons["entry-detail-update-button"])+ let workTitle = element("work-detail-title")+ // Phone Save is terminal and its navigation is asynchronous. Let the+ // destination settle before considering the wide column's own route.+ if !workTitle.waitForExistence(timeout: 20) {+ // A wide entry column intentionally stays open after Update. Its+ // existing Open Work action is the reader's route back to history.+ #if os(macOS)+ activate(app.buttons["Back"].firstMatch)+ #else+ activate(app.buttons["entry-detail-work-title"])+ #endif+ }+ XCTAssertTrue(workTitle.waitForExistence(timeout: 20), "The saved chapter's Work is reachable through its existing route")+ if !element("record-history-count").exists {+ XCTAssertTrue(pill.waitForExistence(timeout: 15) && pill.isEnabled)+ #if os(macOS)+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).click()+ #else+ pill.coordinate(withNormalizedOffset: CGVector(dx: 0.08, dy: 0.5)).tap()+ #endif+ }+ XCTAssertTrue(element("record-history-count").waitForExistence(timeout: 15),+ "The literal character remains supported after saving the longer note")+ XCTAssertEqual(element("record-history-count").label, "Chapters (24)")+ if !app.buttons["record-history-row-\(target)"].exists { toggleHistoryDisclosure() }+ if !source.exists { activate(app.buttons["record-history-row-\(target)"]) }+ XCTAssertTrue(source.waitForExistence(timeout: 15), "Saved source expansion is reachable after Update")+ let refreshed = XCTNSPredicateExpectation(predicate: NSPredicate { value, _ in+ #if os(macOS)+ (value as? XCUIElement)?.value as? String == exact+ #else+ (value as? XCUIElement)?.label == exact+ #endif+ }, object: source)+ XCTAssertEqual(XCTWaiter.wait(for: [refreshed], timeout: 15), .completed,+ "The selected captured history refreshes to the explicitly saved note")+ XCTAssertEqual(Array(staticTextString(source).utf8), Array(exact.utf8), "History exposes the entire saved source without truncation or normalization")+ retainFailure("Long saved chapter source at accessibility size")+ activate(app.buttons["record-history-edit-\(target)"])+ XCTAssertTrue(element("association-note-text").waitForExistence(timeout: 15),+ "The annotation action remains reachable after a long expanded source")+ close("association-note-cancel")+ }++ func testExplicitSkippedRestoreIsSeparateFromUnsavedChapterFields() {+ openHistoryFixture()+ // Open a stable saved chapter through the shared Work chapter route.+ let chapter = app.buttons.matching(NSPredicate(format: "identifier == %@ AND label CONTAINS %@", "work-detail-entry", "28")).firstMatch+ func openSavedChapter(_ chapter: XCUIElement) {+ #if os(macOS)+ XCTAssertTrue(chapter.waitForExistence(timeout: 15))+ XCTAssertTrue(chapter.isEnabled)+ XCTAssertTrue(element("work-detail-focused-entry-24680000-0000-4000-8000-000000000028").exists,+ "The actual Work chapter row retains the requested saved chapter marker")+ XCTAssertTrue(nativeMacViewport(in: element("work-detail-scroll")).contains(chapter.frame),+ "The requested real chapter row is fully inside the native Work viewport")+ chapter.coordinate(withNormalizedOffset: CGVector(dx: 0.12, dy: 0.5)).click()+ #else+ activate(chapter)+ #endif+ }+ openSavedChapter(chapter)+ let note = element("entry-detail-note-editor")+ XCTAssertTrue(note.waitForExistence(timeout: 20))+ let original = note.value as? String+ #if os(macOS)+ // Native AX marks this editable TextView disabled; the long-note+ // journey proves ordinary keyboard editing. Verify the exact draft.+ note.click()+ note.typeKey(XCUIKeyboardKey.downArrow.rawValue, modifierFlags: .command)+ #else+ activate(note)+ #endif+ note.typeText(" unsaved parent draft")+ let draft = note.value as? String+ XCTAssertNotEqual(draft, original, "The parent has an actual unsaved edit")+ #if os(macOS)+ XCTAssertEqual(draft, (original ?? "") + " unsaved parent draft",+ "Native editing preserves the original note and appends the entire unsaved draft")+ #endif+ activate(app.buttons["entry-skipped-character-links"])+ activate(app.buttons["skipped-link-restore-\(characterID)"])+ XCTAssertTrue(element("skipped-links-empty").waitForExistence(timeout: 15))+ activate(app.buttons["skipped-links-done"])+ XCTAssertEqual(Array((note.value as? String ?? "").utf8), Array((draft ?? "").utf8), "Restore preserves the exact unsaved parent draft")+ XCTAssertTrue(app.buttons["entry-association-character-\(characterID)"].waitForExistence(timeout: 15))+ let detached = " Cafe\u{301} skipped chapter annotation "+ XCTAssertFalse(app.staticTexts[detached].exists, "Restore does not attach this pair's detached prose")+ retainFailure("Restored link alongside unsaved chapter draft")+ // Relaunch cancels this unsaved parent, while the explicit child action remains saved.+ terminateAndWaitForExit(app); app.launch()+ XCTAssertTrue(element("recent-list").waitForExistence(timeout: 60))+ openHistoryWork()+ openSavedChapter(app.buttons.matching(NSPredicate(format: "identifier == %@ AND label CONTAINS %@", "work-detail-entry", "28")).firstMatch)+ XCTAssertTrue(element("entry-detail-note-editor").waitForExistence(timeout: 20))+ XCTAssertEqual(Array((element("entry-detail-note-editor").value as? String ?? "").utf8), Array((original ?? "").utf8), "The parent draft was never saved")+ XCTAssertTrue(app.buttons["entry-association-character-\(characterID)"].exists, "Only the explicit Restore survives relaunch")+ terminateAndWaitForExit(app); app.launch()+ XCTAssertTrue(element("recent-list").waitForExistence(timeout: 60))+ openDetachedNotes()+ #if os(macOS)+ // The native selectable Text exports a same-text child. Bind the one+ // identified wrapper so the exact byte read cannot match both nodes.+ let detachedTexts = app.staticTexts.matching(identifier: "detached-association-note-text")+ .matching(NSPredicate(format: "value == %@", detached))+ let savedDetached = detachedTexts.element(boundBy: 0)+ #else+ let detachedTexts = app.staticTexts.matching(identifier: "detached-association-note-text")+ .matching(NSPredicate(format: "label == %@", detached))+ let savedDetached = detachedTexts.element(boundBy: 0)+ // UUID-ordered sections are lazy: this note can follow the malformed+ // and missing-endpoint notes. Scroll the recovery list, never the+ // Recent list that remains behind Settings, before reading exact bytes.+ let recoveryLists = app.collectionViews.containing(.staticText, identifier: "detached-association-note-text")+ XCTAssertTrue(recoveryLists.firstMatch.waitForExistence(timeout: 15))+ XCTAssertEqual(recoveryLists.count, 1, "Only the recovery list owns detached note text")+ for _ in 0..<8 where !savedDetached.exists { recoveryLists.firstMatch.swipeUp() }+ #endif+ XCTAssertTrue(savedDetached.waitForExistence(timeout: 15), "This same pair's detached note remains available for explicit recovery")+ XCTAssertEqual(detachedTexts.count, 1, "Exactly one identified detached note preserves this text")+ XCTAssertEqual(Array(staticTextString(savedDetached).utf8), Array(detached.utf8))++++ }++ #if os(macOS)+ /// Candidate regression: normal inspector routes and final dashboard Back.+ /// The existing saved-note behavioral journey stays intact.+ func testWideInspectorEntrySwitchAndWorkBackRetainCorrectModelAndDay() {+ let secondID = "24680000-0000-4000-8000-000000000003"+ let date = element("today-header-date")+ XCTAssertTrue(date.waitForExistence(timeout: 15))+ let originalDayLabel = date.label+ func openWorkFromCurrentEntry() {+ let field = element("entry-detail-note-editor")+ XCTAssertTrue(field.waitForExistence(timeout: 15))+ activate(app.buttons["entry-detail-work-title"])+ XCTAssertTrue(element("work-detail-title").waitForExistence(timeout: 20),+ "The Entry's genuine Open Work action displays its Work")+ XCTAssertTrue(element("work-detail-pulse").waitForExistence(timeout: 15),+ "Open Work presents the complete Work screen")+ XCTAssertEqual(staticTextString(app.staticTexts["work-detail-title"]), "The Link Book")+ let gone = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: field)+ XCTAssertEqual(XCTWaiter.wait(for: [gone], timeout: 20), .completed,+ "Open Work leaves the Entry rather than retaining its editor")+ }+ func backToDashboard() {+ activate(app.buttons["Back"].firstMatch)+ XCTAssertTrue(element("recent-list").waitForExistence(timeout: 20))+ XCTAssertEqual(element("today-header-date").label, originalDayLabel)+ for id in ["entry-detail-\(chapterID)", "entry-detail-\(secondID)", "work-detail-title"] {+ let gone = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: element(id))+ XCTAssertEqual(XCTWaiter.wait(for: [gone], timeout: 20), .completed,+ "Back reaches the final dashboard without a retained pushed controller")+ }+ XCTAssertFalse(element("entry-detail-\(chapterID)").exists)+ XCTAssertFalse(element("entry-detail-\(secondID)").exists)+ XCTAssertFalse(element("work-detail-title").exists, "The pushed Work controller must not remain")+ }+ openChapter() // Existing row → inspector Edit, existing title/editor assertions.+ XCTAssertTrue(element("entry-detail-\(chapterID)").waitForExistence(timeout: 15))+ backToDashboard()+ activate(app.buttons["recent-entry-\(secondID)"])+ let inspector = element("today-inspector")+ XCTAssertTrue(inspector.waitForExistence(timeout: 15))+ activate(inspector.buttons["Edit"].firstMatch)+ XCTAssertTrue(element("entry-detail-\(secondID)").waitForExistence(timeout: 20))+ XCTAssertTrue(element("entry-detail-note-editor").waitForExistence(timeout: 15))+ XCTAssertFalse(element("entry-detail-\(chapterID)").exists, "The second Entry owns the actual model")+ backToDashboard()+ activate(app.buttons["recent-entry-\(chapterID)"])+ XCTAssertTrue(inspector.waitForExistence(timeout: 15))+ activate(app.buttons["today-inspector-open-work"])+ XCTAssertTrue(element("work-detail-title").waitForExistence(timeout: 20))+ XCTAssertTrue(element("work-detail-focused-entry-\(chapterID)").waitForExistence(timeout: 15))+ XCTAssertFalse(inspector.exists)+ backToDashboard()+ openChapter()+ XCTAssertTrue(element("entry-detail-\(chapterID)").waitForExistence(timeout: 15))+ openWorkFromCurrentEntry() // Standalone Today entry → its actual Work.+ backToDashboard()+ activate(app.buttons["recent-entry-\(chapterID)"])+ XCTAssertTrue(inspector.waitForExistence(timeout: 15))+ activate(app.buttons["today-inspector-open-work"])+ let edit = app.buttons["work-detail-edit-focused-entry-\(chapterID)"]+ let scroll = element("work-detail-scroll")+ for _ in 0..<8 {+ let bounds = nativeMacViewport(in: scroll)+ if edit.exists && bounds.contains(edit.frame) { break }+ let distance = edit.exists+ ? max(-0.25, min(0.25, (bounds.midY - edit.frame.midY) / max(1, bounds.height))) : -0.25+ nativeMacScroll(scroll, deltaY: distance * bounds.height)+ }+ XCTAssertTrue(edit.exists && nativeMacViewport(in: scroll).contains(edit.frame),+ "The genuine focused chapter Edit action is inside the Work viewport")+ activate(edit)+ XCTAssertTrue(element("entry-detail-\(chapterID)").waitForExistence(timeout: 20))+ openWorkFromCurrentEntry() // Work-origin chapter → its existing Work.+ backToDashboard()+ }+ func testMacInspectorCloseKeyboardAndDayChangePreserveDashboard() throws {+ let inspector = element("today-inspector")+ let date = element("today-header-date")+ XCTAssertTrue(date.waitForExistence(timeout: 15))+ let originalDate = date.label+ XCTAssertFalse(originalDate.isEmpty)+ let arrivalRow = app.buttons["recent-entry-\(chapterID)"]+ let returnRow = app.buttons["recent-entry-24680000-0000-4000-8000-000000000003"]+ XCTAssertTrue(arrivalRow.waitForExistence(timeout: 15) && returnRow.waitForExistence(timeout: 15))+ XCTAssertGreaterThan(arrivalRow.frame.height, 0)+ XCTAssertGreaterThan(returnRow.frame.height, 0)+ XCTAssertNotEqual(arrivalRow.frame.minY, returnRow.frame.minY)+ let expectedBottom = arrivalRow.frame.minY > returnRow.frame.minY ? "Arrival" : "Return"+ let expectedTop = expectedBottom == "Arrival" ? "Return" : "Arrival"+ func openInspector() {+ activate(app.buttons["recent-entry-\(chapterID)"])+ XCTAssertTrue(inspector.waitForExistence(timeout: 15))+ }+ func expectClosed() {+ let gone = XCTNSPredicateExpectation(predicate: NSPredicate(format: "exists == false"), object: inspector)+ XCTAssertEqual(XCTWaiter.wait(for: [gone], timeout: 20), .completed)+ XCTAssertTrue(element("recent-list").exists)+ XCTAssertFalse(element("entry-detail-note-editor").exists)+ }+ openInspector()+ activate(app.buttons["today-inspector-close"])+ expectClosed()+ XCTAssertEqual(date.label, originalDate)+ openInspector()+ let titles = ["Arrival", "Return"]+ let heading = inspector.staticTexts.matching(NSPredicate(format: "value IN %@", titles)).firstMatch+ XCTAssertTrue(heading.waitForExistence(timeout: 15))+ app.typeKey(XCUIKeyboardKey.downArrow.rawValue, modifierFlags: [])+ let reachedBottom = XCTNSPredicateExpectation(+ predicate: NSPredicate(format: "value == %@", expectedBottom), object: heading)+ XCTAssertEqual(XCTWaiter.wait(for: [reachedBottom], timeout: 20), .completed)+ let bottom = staticTextString(heading)+ XCTAssertEqual(bottom, expectedBottom)+ app.typeKey(XCUIKeyboardKey.upArrow.rawValue, modifierFlags: [])+ let movedUp = XCTNSPredicateExpectation(+ predicate: NSPredicate(format: "value == %@", expectedTop), object: heading)+ XCTAssertEqual(XCTWaiter.wait(for: [movedUp], timeout: 20), .completed,+ "Inspector focus handles Up rather than moving the dashboard")+ let top = staticTextString(heading)+ XCTAssertEqual(Set([top, bottom]), Set(titles))+ app.typeKey(XCUIKeyboardKey.downArrow.rawValue, modifierFlags: [])+ let movedDown = XCTNSPredicateExpectation(predicate: NSPredicate(format: "value == %@", bottom), object: heading)+ XCTAssertEqual(XCTWaiter.wait(for: [movedDown], timeout: 20), .completed,+ "Down returns to the same actual inspector row")+ app.typeKey(XCUIKeyboardKey.escape.rawValue, modifierFlags: [])+ expectClosed()+ XCTAssertEqual(date.label, originalDate)+ openInspector()+ let days = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "today-strip-"))+ XCTAssertTrue(days.firstMatch.waitForExistence(timeout: 15))+ let otherDay = try XCTUnwrap(days.allElementsBoundByIndex.first { $0.isEnabled && !$0.label.hasPrefix(originalDate) })+ activate(otherDay)+ expectClosed()+ let changedDay = XCTNSPredicateExpectation(+ predicate: NSPredicate(format: "label != %@ AND label != ''", originalDate), object: date)+ XCTAssertEqual(XCTWaiter.wait(for: [changedDay], timeout: 20), .completed,+ "Selecting another visible day closes the inspector")+ activate(date)+ let returnedDay = XCTNSPredicateExpectation(predicate: NSPredicate(format: "label == %@", originalDate), object: date)+ XCTAssertEqual(XCTWaiter.wait(for: [returnedDay], timeout: 20), .completed,+ "The header returns to the original current day")+ openInspector()+ activate(app.buttons["today-inspector-close"])+ expectClosed()+ }++ func testMacSidebarRestoreDoesNotRestoreInspector() {+ activate(app.buttons["recent-entry-\(chapterID)"])+ XCTAssertTrue(element("today-inspector").waitForExistence(timeout: 15))+ let library = app.buttons["sidebar-library-allWorks"]+ activate(library)+ XCTAssertTrue(element("works-group-allWorks").waitForExistence(timeout: 20))+ XCTAssertTrue(library.isSelected)+ XCTAssertFalse(element("today-inspector").exists)+ terminateAndWaitForExit(app)+ runID = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_RESTORE_NAVIGATION"] = "1"+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = runID+ app.launch()+ XCTAssertTrue(element("works-group-allWorks").waitForExistence(timeout: 60),+ "Explicit restore retains the selected sidebar destination")+ XCTAssertTrue(library.isSelected)+ XCTAssertFalse(element("today-inspector").exists, "Inspector selection is not restored")+ activate(app.buttons["sidebar-today"])+ XCTAssertTrue(element("recent-list").waitForExistence(timeout: 20))+ XCTAssertFalse(element("today-inspector").exists)+ XCTAssertFalse(element("entry-detail-note-editor").exists)+ }+ #endif++ func testSaveCancelStagedClearAndRelaunchPreserveExactTextAndBothKinds() {+ openChapter()+ var field = openNote()+ XCTAssertEqual(field.value as? String, "Saved arrival note")+ replace(field, with: "Discard this draft")+ close("association-note-cancel")+ field = openNote()+ XCTAssertEqual(field.value as? String, "Saved arrival note", "Cancel writes nothing")+ #if os(macOS)+ // XCTest native keystrokes compose accented input on this runtime.+ // The separate seeded-NFD append journey pins exact Unicode persistence.+ let exact = "Reader note saved on Mac"+ #else+ let exact = "Cafe\u{301} reader note"+ #endif+ replace(field, with: exact)+ close("association-note-save")+ field = openNote()+ XCTAssertEqual(Array((field.value as? String ?? "").utf8), Array(exact.utf8))+ activate(app.buttons["association-note-clear"])+ XCTAssertEqual(field.value as? String, "")+ close("association-note-cancel")+ field = openNote()+ XCTAssertEqual(Array((field.value as? String ?? "").utf8), Array(exact.utf8), "Staged Clear plus Cancel preserves saved text")+ close("association-note-cancel")+ terminateAndWaitForExit(app)+ launch() // Same UUID; a completed fixture must preserve the reader's edit.+ openChapter()+ field = openNote()+ XCTAssertEqual(Array((field.value as? String ?? "").utf8), Array(exact.utf8))+ activate(app.buttons["association-note-clear"])+ close("association-note-save")+ field = openNote()+ XCTAssertEqual(field.value as? String, "", "Terminal Save persists Clear")+ close("association-note-cancel")+ let place = openNote(kind: "place", id: placeID)+ XCTAssertTrue(app.staticTexts["Harbor note from device A"].exists)+ XCTAssertTrue(app.staticTexts["Harbor note from device B"].exists)+ replace(place, with: "Resolved Harbor note")+ close("association-note-save")+ let reopened = openNote(kind: "place", id: placeID)+ XCTAssertEqual(reopened.value as? String, "Resolved Harbor note")+ close("association-note-cancel")+ }+ #if os(macOS)+ func testSeededNFDNoteSurvivesNativeASCIIAppendSaveReopenAndRepositoryReadback() {+ let secondID = "24680000-0000-4000-8000-000000000003"+ let seeded = "Cafe\u{301} seeded link note"+ let suffix = " ASCII appended"+ openChapter(secondID)+ let field = openNote(kind: "place", id: placeID)+ XCTAssertEqual(Array((field.value as? String ?? "").utf8), Array(seeded.utf8),+ "Repository-seeded NFD bytes load without normalization")+ nativeMacFieldInput(field) {+ // This fixture is one line; standard Command-Right moves to its end.+ field.typeKey(XCUIKeyboardKey.rightArrow.rawValue, modifierFlags: .command)+ field.typeText(suffix)+ }+ let expected = seeded + suffix+ XCTAssertEqual(Array((field.value as? String ?? "").utf8), Array(expected.utf8))+ requireNativeMacDirtySave()+ close("association-note-save")+ let reopened = openNote(kind: "place", id: placeID)+ XCTAssertEqual(Array((reopened.value as? String ?? "").utf8), Array(expected.utf8))+ close("association-note-cancel")+ terminateAndWaitForExit(app)+ app.launchEnvironment["ASTERISM_UI_TEST_ASSOCIATION_VERIFY_UNICODE_APPEND"] = "1"+ launch() // Same UUID; completed fixture READS repository bytes, never reseeds.+ openChapter(secondID)+ let durable = openNote(kind: "place", id: placeID)+ XCTAssertEqual(Array((durable.value as? String ?? "").utf8), Array(expected.utf8))+ close("association-note-cancel")+ }+ #endif++ private func openDetachedNotes() {+ #if os(macOS)+ app.typeKey(",", modifierFlags: .command)+ #else+ activate(app.buttons["settings-button"])+ #endif+ activate(element("settings-detached-association-notes"))+ }+ func testRecoveryExposesTheSingleDestinationHeadBeforeExplicitSave() {+ openDetachedNotes()+ activate(app.buttons["detached-association-note-recover"])+ XCTAssertTrue(app.staticTexts["Current destination note"].waitForExistence(timeout: 15), "Existing destination text is visible before a consuming Save")+ let field = element("association-note-text")+ XCTAssertEqual(field.value as? String, "Earlier chapter link note")+ close("association-note-cancel")+ XCTAssertTrue(app.staticTexts["Earlier chapter link note"].exists, "Cancel leaves detached text untouched")+ activate(app.buttons["detached-association-note-recover"])+ XCTAssertTrue(app.staticTexts["Current destination note"].exists)+ close("association-note-save")+ XCTAssertFalse(app.staticTexts["Earlier chapter link note"].exists, "Explicit recovery consumes only the selected detached head")+ }+ func testMalformedAndMissingEndpointNotesKeepCopyableTextAndOriginalContext() {+ openDetachedNotes()+ let raw = app.staticTexts["Cafe\u{301} raw text remains copyable"]+ XCTAssertTrue(raw.waitForExistence(timeout: 15))+ XCTAssertTrue(app.staticTexts["Missing chapter: preserved original context"].exists)+ XCTAssertTrue(app.staticTexts["Missing endpoint note"].exists)+ XCTAssertTrue(app.staticTexts["Removed chapter: original context"].exists)+ let copies = app.buttons.matching(identifier: "detached-association-note-copy")+ XCTAssertEqual(copies.count, 3)+ XCTAssertEqual(app.buttons.matching(identifier: "detached-association-note-recover").count, 1, "Only the coherent same-pair note offers recovery")+ activate(copies.element(boundBy: 0))+ XCTAssertTrue(raw.exists, "Copy leaves preserved raw variants intact")+ let attachment = XCTAttachment(screenshot: app.screenshot())+ attachment.name = "association-raw-context-copy-recovery"; attachment.lifetime = .keepAlways+ add(attachment)+ }+}
diff --git a/Asterism/AsterismUITests/AsterismUITests.swift b/Asterism/AsterismUITests/AsterismUITests.swiftindex 5493b7e5..b536add6 100644--- a/Asterism/AsterismUITests/AsterismUITests.swift+++ b/Asterism/AsterismUITests/AsterismUITests.swift@@ -26,6 +26,7 @@ final class AsterismUITests: XCTestCase { func testExample() throws { // UI tests must launch the application that they test. let app = XCUIApplication()+ app.configureSyntheticLaunch() app.launch() // Use XCTAssert and related functions to verify your tests produce the correct results.@@ -37,7 +38,9 @@ final class AsterismUITests: XCTestCase { func testLaunchPerformance() throws { // This measures how long it takes to launch your application. measure(metrics: [XCTApplicationLaunchMetric()]) {- XCUIApplication().launch()+ let app = XCUIApplication()+ app.configureSyntheticLaunch()+ app.launch() } } }
diff --git a/Asterism/AsterismUITests/AsterismUITestsLaunchTests.swift b/Asterism/AsterismUITests/AsterismUITestsLaunchTests.swiftindex bc26ed6e..75238c89 100644--- a/Asterism/AsterismUITests/AsterismUITestsLaunchTests.swift+++ b/Asterism/AsterismUITests/AsterismUITestsLaunchTests.swift@@ -20,6 +20,7 @@ final class AsterismUITestsLaunchTests: XCTestCase { @MainActor func testLaunch() throws { let app = XCUIApplication()+ app.configureSyntheticLaunch() app.launch() // Insert steps here to perform after app launch but before taking a screenshot,
diff --git a/Asterism/AsterismUITests/ChapterNotesUITests.swift b/Asterism/AsterismUITests/ChapterNotesUITests.swiftindex c8315587..6ef19bc8 100644--- a/Asterism/AsterismUITests/ChapterNotesUITests.swift+++ b/Asterism/AsterismUITests/ChapterNotesUITests.swift@@ -140,12 +140,10 @@ final class ChapterNotesUITests: XCTestCase { private func revealManualCastSpine(expectedCount: Int = 1) { let rows = app.buttons.matching(identifier: "work-detail-entry")- if UIDevice.current.userInterfaceIdiom == .pad {- let pane = waitFor(app.anyElement("work-detail-scroll"), "The work owns its detail pane")- for _ in 0..<8 where rows.count != expectedCount { pane.swipeUp() }- } else {- scrollUntilPresent(rows.firstMatch, in: app, "The saved spine is reachable below the long cast")- }+ // Compact Work uses a lazy List too. One realized row does not prove+ // that all saved rows have been brought past the long character cast.+ let pane = waitFor(app.anyElement("work-detail-scroll"), "The work owns its detail pane")+ for _ in 0..<8 where rows.count != expectedCount { pane.swipeUp() } waitFor(rows.firstMatch, "Saved reactions are drawn before counting") }
diff --git a/Asterism/AsterismUITests/CharacterExtractionUITests.swift b/Asterism/AsterismUITests/CharacterExtractionUITests.swiftindex eac09001..b7063418 100644--- a/Asterism/AsterismUITests/CharacterExtractionUITests.swift+++ b/Asterism/AsterismUITests/CharacterExtractionUITests.swift@@ -51,6 +51,137 @@ final class CharacterExtractionUITests: XCTestCase { terminateAndWaitForExit(app) } + private func relaunchWithLegacyFacts() {+ terminateAndWaitForExit(app)+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_LEGACY_FACTS"] = "1"+ app.launchEnvironment["ASTERISM_UI_TEST_EXTRACTION"] = "unavailable"+ app.launch()+ }++ private func openSourceRowReview() {+ terminateAndWaitForExit(app)+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_SOURCE_ROWS"] = "1"+ app.launchArguments += ["-UIPreferredContentSizeCategoryName", "UICTContentSizeCategoryAccessibilityM"]+ app.launch(); openWorkDetail(); openReview()+ }++ private func assertChapterSourceTitleDate(_ rowID: String, kind: String) {+ let block = app.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "review-source-\(rowID)-1")).firstMatch+ scrollUntilTappableAndTap(block, in: app, "The \(kind) chapter source expands",+ scroll: { $0.anyElement("character-review-list").swipeUp() })+ let title = app.staticTexts.matching(NSPredicate(format: "identifier BEGINSWITH %@ AND identifier ENDSWITH %@",+ "review-source-\(rowID)-1", "-title")).firstMatch+ XCTAssertTrue(title.waitForExistence(timeout: 15))+ // A native DisclosureGroup combines its label's identifiers. The leaf+ // owns the raw source identity; predicate queries also avoid XCTest's+ // 128-character limit on identifier string subscripts.+ let base = String(title.identifier.dropLast("-title".count))+ let date = app.staticTexts.matching(NSPredicate(format: "identifier == %@", base + "-date")).firstMatch+ XCTAssertTrue(date.exists)+ XCTAssertEqual(title.label, "The Lamp Room — arrival at the old harbour")+ XCTAssertEqual(date.label, "Today")+ XCTAssertLessThan(title.frame.minX, date.frame.minX)+ XCTAssertGreaterThan(date.frame.maxX, block.frame.maxX - 44,+ "The compact date occupies the full-width source row's trailing edge")+ XCTAssertGreaterThanOrEqual(date.frame.midY, title.frame.minY)+ XCTAssertLessThanOrEqual(date.frame.midY, title.frame.maxY,+ "The date remains beside the wrapping title, never a separate line")+ let suffix = String(base.dropFirst("review-source-".count))+ let full = app.staticTexts.matching(NSPredicate(format: "identifier == %@", "review-source-text-" + suffix)).firstMatch+ XCTAssertTrue(full.waitForExistence(timeout: 15))+ XCTAssertEqual(Array(full.label.utf8), Array("Brede rows the tender out at dusk, past Kestrel Head.".utf8))+ XCTAssertFalse(app.staticTexts.matching(NSPredicate(format: "label MATCHES %@", "Saved source [0-9]+")).firstMatch.exists)+ XCTAssertFalse(app.staticTexts["Chapter note"].exists)+ XCTAssertFalse(app.staticTexts["Chapter 1"].exists)+ let image = XCTAttachment(screenshot: app.screenshot())+ image.name = "\(kind) suggestion chapter title and trailing date"; image.lifetime = .keepAlways; add(image)+ let tree = XCTAttachment(string: app.debugDescription)+ tree.name = "\(kind) suggestion chapter title and date AX tree"; tree.lifetime = .keepAlways; add(tree)+ let list = app.anyElement("character-review-list")+ func visibleSourceViewport() -> CGRect {+ var viewport = list.frame.intersection(app.windows.firstMatch.frame).insetBy(dx: 0, dy: 4)+ let navigation = app.navigationBars.firstMatch+ if navigation.exists {+ let top = max(viewport.minY, navigation.frame.maxY + 4)+ viewport = CGRect(x: viewport.minX, y: top, width: viewport.width, height: max(0, viewport.maxY - top))+ }+ return viewport+ }+ func sourceFitsViewport() -> Bool {+ let viewport = visibleSourceViewport()+ return viewport.contains(title.frame) && viewport.contains(date.frame)+ && viewport.contains(full.frame) && title.isHittable && date.isHittable && full.isHittable+ }+ for _ in 0..<6 where !sourceFitsViewport() {+ let viewport = visibleSourceViewport()+ let correction = title.frame.minY < viewport.minY+ ? viewport.minY - title.frame.minY + 16 : viewport.maxY - full.frame.maxY - 16+ let distance = max(-0.25, min(0.25, correction / list.frame.height))+ list.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))+ .press(forDuration: 0.1, thenDragTo: list.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5 + distance)))+ }+ XCTAssertTrue(sourceFitsViewport(), "The actual chapter title, trailing date and full exact source are all visible together")+ let sourceImage = XCTAttachment(screenshot: app.screenshot())+ sourceImage.name = "\(kind) suggestion full chapter source viewport"; sourceImage.lifetime = .keepAlways; add(sourceImage)+ let sourceTree = XCTAttachment(string: app.debugDescription)+ sourceTree.name = "\(kind) suggestion full chapter source viewport AX tree"; sourceTree.lifetime = .keepAlways; add(sourceTree)+ }++ func testCharacterSuggestionSourceShowsActualTitleAndTrailingDate() {+ openSourceRowReview()+ assertChapterSourceTitleDate(Row.brede, kind: "Character")+ XCTAssertTrue(reviewListShows("character-review-keep-\(Row.kestrelHead)"), "Reading evidence does not decide the place")+ }++ func testPlaceSuggestionSourceShowsActualTitleAndTrailingDate() {+ openSourceRowReview()+ assertChapterSourceTitleDate(Row.kestrelHead, kind: "Place")+ XCTAssertTrue(reviewListShows("character-review-keep-\(Row.brede)"), "Reading evidence does not decide the character")+ }++ func testReviewShowsExactSavedSourceWithoutGeneratedFacts() {+ openWorkDetail(); openReview()+ let block = app.descendants(matching: .any).matching(NSPredicate(+ format: "identifier BEGINSWITH %@", "review-source-character:ada-0")).firstMatch+ scrollUntilTappableAndTap(block, in: app, "Ada's captured source can be read fully")+ let text = app.descendants(matching: .any).matching(NSPredicate(+ format: "identifier BEGINSWITH %@", "review-source-text-character:ada-0")).firstMatch+ XCTAssertTrue(text.waitForExistence(timeout: 15))+ XCTAssertEqual(text.label, "Ada keeps the lighthouse at Kestrel Head, and the crew call her Nightjar. Brede rows the tender out at dusk. Selkie is moored below the light.")+ XCTAssertFalse(app.descendants(matching: .any).matching(NSPredicate(+ format: "identifier BEGINSWITH %@", "character-review-fact-")).firstMatch.exists)+ XCTAssertTrue(reviewListShows("character-review-keep-\(Row.brede)"), "Reading a source does not settle a sibling")+ let image = XCTAttachment(screenshot: app.screenshot())+ image.name = "Captured source evidence"; image.lifetime = .keepAlways; add(image)+ tapReviewControl("character-review-keep-\(Row.ada)", "Fresh character creation keeps its selected alias")+ waitUntilGone(+ app.anyElement("character-review-keep-\(Row.ada)"),+ "Keeping Ada settles her decision before closing review")+ closeReview()+ openPill(pill(named: "Ada"))+ waitFor(aliasChip(named: "Nightjar"), "An accepted alias is retained on a newly created character")+ XCTAssertFalse(app.staticTexts["Ada keeps the lighthouse."].exists, "No generated fact was added")+ }++ func testRecognisedCharacterLinksWithoutEnteringReview() {+ terminateAndWaitForExit(app)+ app.launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = UUID().uuidString+ app.launchEnvironment["ASTERISM_UI_TEST_KNOWN_CHARACTER"] = "1"+ app.launch()+ openWorkDetail()+ let brede = pill(named: "Brede")+ scrollUntilPresent(brede, in: app, "The known character is present")+ openPill(brede)+ scrollUntilPresent(app.anyElement("record-history-count"), in: app, "Background recognition saved the chapter link")+ XCTAssertEqual(app.anyElement("record-history-count").label, "Chapters (1)")+ openReview()+ XCTAssertFalse(app.anyElement("character-review-keep-\(Row.brede)").exists,+ "The recognised character has no approval row")+ XCTAssertTrue(reviewListShows("character-review-keep-\(Row.kestrelHead)"), "Place decisions remain independent")+ }+ // MARK: - Navigation private func openWorkDetail() {@@ -122,15 +253,49 @@ final class CharacterExtractionUITests: XCTestCase { return seen } - /// Taps a review row's control, scrolling the list until it is reachable.+ /// The sheet's list can publish a hittable control behind its toolbar.+ /// Keep the whole control below that sheet's own navigation bar before+ /// asking XCTest to choose a native tap point.+ private var reviewControlViewport: CGRect {+ let listFrame = reviewList.frame.intersection(app.frame)+ let done = app.buttons["character-review-done"]+ guard !listFrame.isNull, !listFrame.isEmpty, done.exists else { return .null }+ let navigationBar = app.navigationBars+ .containing(.button, identifier: "character-review-done").firstMatch+ let toolbarBottom = navigationBar.exists ? navigationBar.frame.maxY : done.frame.maxY+ let top = max(listFrame.minY, toolbarBottom)+ return CGRect(+ x: listFrame.minX, y: top, width: listFrame.width,+ height: max(0, listFrame.maxY - top))+ }++ private func reviewControlIsFullyVisible(_ control: XCUIElement) -> Bool {+ guard control.exists, control.isHittable else { return false }+ let frame = control.frame+ let viewport = reviewControlViewport+ return !frame.isEmpty && !viewport.isNull && !viewport.isEmpty && viewport.contains(frame)+ }++ /// Taps a review row's control, scrolling its owning list in either direction. private func tapReviewControl(_ identifier: String, _ message: String) {+ let control = app.anyElement(identifier) // Stop at the banner: pulling down again at the top dismisses the sheet.- for _ in 0..<6 where !app.anyElement(identifier).isHittable && !reviewBanner.isHittable {+ for _ in 0..<6 where !reviewControlIsFullyVisible(control)+ && !reviewControlIsFullyVisible(reviewBanner) { reviewList.swipeDown() }- scrollUntilTappableAndTap(- app.anyElement(identifier), in: app, message,- scroll: { $0.anyElement("character-review-list").swipeUp() })+ for _ in 0..<8 {+ if reviewControlIsFullyVisible(control) {+ control.tap()+ return+ }+ if control.exists && control.frame.minY < reviewControlViewport.minY {+ reviewList.swipeDown()+ } else {+ reviewList.swipeUp()+ }+ }+ XCTFail(message) } /// The proposed-fact toggle whose statement contains `text`.@@ -318,9 +483,11 @@ final class CharacterExtractionUITests: XCTestCase { "Keeping a place writes no character") openPill(pill(named: "Kestrel Head", kind: "place"))- scrollUntilPresent(- app.staticTexts["The lighthouse stands at Kestrel Head."], in: app,- "The place's fact was written")+ scrollUntilPresent(app.anyElement("record-history-count"), in: app,+ "The accepted place has its chapter history")+ XCTAssertEqual(app.anyElement("record-history-count").label, "Chapters (1)")+ XCTAssertFalse(app.staticTexts["The lighthouse stands at Kestrel Head."].exists,+ "Keeping a place writes no generated fact") } // MARK: - Req 2.2: reclassification, then keeping under the new kind@@ -492,10 +659,8 @@ final class CharacterExtractionUITests: XCTestCase { // MARK: - Req 4.4: the entry a place's fact cites says so func testAKeptPlaceIsNamedOnTheEntryItCites() {+ relaunchWithLegacyFacts() openWorkDetail()- openReview()- tapReviewControl("character-review-keep-\(Row.kestrelHead)", "The place can be kept")- closeReview() scrollUntilPresent( app.anyElement("work-detail-place"), in: app, "The kept place appears")@@ -514,6 +679,8 @@ final class CharacterExtractionUITests: XCTestCase { waitFor( app.anyElement("entry-detail-citing-place"), "The entry names the place citing it", timeout: 20)+ let reference = app.anyElement("entry-detail-citing-place")+ XCTAssertFalse(reference.label.contains("fact")) } // MARK: - Req 2.2: keeping, with a fact unticked and an alias struck@@ -528,12 +695,10 @@ final class CharacterExtractionUITests: XCTestCase { waitFor(app.anyElement("character-review-alias-Nightjar"), "The alias is offered"), "The alias is struck") - // Untick one of Ada's two proposed facts. "Only what was ticked" is the- // whole claim of this journey, and it says nothing at all unless- // something is left unticked.- flip(- waitFor(factToggle(containing: "lighthouse"), "Ada's lighthouse fact is offered"),- "The lighthouse fact is unticked")+ XCTAssertFalse(app.descendants(matching: .any).matching(+ NSPredicate(format: "identifier BEGINSWITH %@", "character-review-fact-")).firstMatch.exists,+ "New extraction offers names and exact source evidence without generated facts")+ XCTAssertTrue(app.staticTexts["Saved sources (1)"].exists || app.staticTexts["Saved sources (2)"].exists) tapReviewControl("character-review-keep-\(Row.ada)", "Ada can be kept") waitUntilGone(@@ -554,12 +719,10 @@ final class CharacterExtractionUITests: XCTestCase { app.staticTexts["Ada is called Nightjar by the crew."].exists, "Quotes stay folded until the pill is tapped") openPill(app.anyElement("work-detail-character"))- scrollUntilPresent(- app.staticTexts["Ada is called Nightjar by the crew."], in: app,- "The ticked fact was written")- XCTAssertFalse(- app.staticTexts["Ada keeps the lighthouse."].exists,- "The unticked fact was not written")+ XCTAssertFalse(app.staticTexts["Ada is called Nightjar by the crew."].exists,+ "Keeping a new character does not create a generated fact")+ XCTAssertFalse(app.staticTexts["Ada keeps the lighthouse."].exists,+ "No generated lighthouse fact was written") // Q92: the struck alias was not installed either. The card lists the // aliases as chips beside the name (`work-detail-reading-redesign` // Q14), so what must not be there is a chip carrying that name.@@ -568,55 +731,26 @@ final class CharacterExtractionUITests: XCTestCase { "The struck alias did not become a match key") } - // MARK: - Req 5.2, Q10: the fact gutter's citation opens the note it cites-- /// The positive counterpart of the two negatives above: an alias the reader- /// kept *is* a chip, and a fact grounded in a live note carries a link in- /// its gutter that goes there.- ///- /// The link is the reason `characterFactRow` declares- /// `accessibilityElement(children: .contain)`: the row's own identifier- /// would otherwise be inherited by the button and no test could reach it.- func testACitationInTheFactGutterOpensTheCitedNote() {- openWorkDetail()- openReview()- // Ada carries the alias; Brede's fact is the one grounded in the- // chapter note, so both are kept and each card is asked in turn.- tapReviewControl("character-review-keep-\(Row.ada)", "Ada can be kept")- tapReviewControl("character-review-keep-\(Row.brede)", "Brede can be kept")- closeReview()-- waitFor(- app.anyElement("work-detail-character"), "The kept characters appear on the page",- timeout: 30)-+ // Q12 supersedes the visible fact-gutter route. Alias and chapter access remain.+ func testLegacyFactsStayHiddenWhileAliasesAndReferencedChapterRemainReachable() {+ relaunchWithLegacyFacts(); openWorkDetail()+ waitFor(app.anyElement("work-detail-character"), "Legacy characters remain", timeout: 30) openPill(pill(named: "Ada"))- // Keep the actual open-card tree and pixels when this journey fails:- // a missing alias must be distinguished from a tap on another pill.- let cardTree = XCTAttachment(string: app.debugDescription)- cardTree.name = "Record card before alias assertion"- cardTree.lifetime = .deleteOnSuccess- add(cardTree)- let cardScreenshot = XCTAttachment(screenshot: app.screenshot())- cardScreenshot.name = "Record card before alias assertion"- cardScreenshot.lifetime = .deleteOnSuccess- add(cardScreenshot)- waitFor(aliasChip(named: "Nightjar"), "The kept alias is a chip beside the name")-+ waitFor(aliasChip(named: "Nightjar"), "The saved alias remains visible")+ XCTAssertFalse(app.staticTexts["Ada is called Nightjar by the crew."].exists)+ XCTAssertFalse(app.staticTexts["the crew call her Nightjar"].exists)+ XCTAssertFalse(app.staticTexts["Existing facts"].exists)+ XCTAssertFalse(app.buttons["work-detail-character-citation"].exists) openPill(pill(named: "Brede"))- let citation = waitFor(- app.buttons["work-detail-character-citation"],- "The fact's gutter offers the note it cites")- citation.tap()-- // Entry detail's section sits between the actions and the capture- // details, so it needs a scroll on a short screen.- if !app.anyElement("entry-detail-citing-character").waitForExistence(timeout: 5) {- scrollEntryDetail(in: app)- }- waitFor(- app.anyElement("entry-detail-citing-character"),- "The citation opened the note it came from", timeout: 20)+ XCTAssertFalse(app.staticTexts["Brede rows the tender."].exists)+ XCTAssertFalse(app.buttons["work-detail-character-citation"].exists)+ let chapter = app.anyElement("work-detail-entry")+ scrollUntilTappableAndTap(chapter, in: app, "The saved chapter remains reachable from its Work spine")+ if !app.anyElement("entry-detail-citing-character").waitForExistence(timeout: 5) { scrollEntryDetail(in: app) }+ let reference = waitFor(app.anyElement("entry-detail-citing-character"), "Legacy reference retains the character's name", timeout: 20)+ XCTAssertTrue(reference.label.contains("Brede"))+ XCTAssertFalse(reference.label.contains("fact"), "Legacy fact counts are hidden from accessibility too")+ XCTAssertFalse(app.staticTexts["Brede rows the tender."].exists) } // MARK: - Req 5.3, Q109: the review sheet is unreachable in edit mode@@ -682,10 +816,8 @@ final class CharacterExtractionUITests: XCTestCase { // MARK: - Req 5.4: the entry the fact cites says so func testAKeptCharacterIsNamedOnTheEntryItCites() {+ relaunchWithLegacyFacts() openWorkDetail()- openReview()- tapReviewControl("character-review-keep-\(Row.brede)", "Brede can be kept")- closeReview() waitFor( app.anyElement("work-detail-character"), "The kept character appears on the page",@@ -707,6 +839,8 @@ final class CharacterExtractionUITests: XCTestCase { waitFor( app.anyElement("entry-detail-citing-character"), "The entry names the character citing it", timeout: 20)+ let reference = app.anyElement("entry-detail-citing-character")+ XCTAssertFalse(reference.label.contains("fact")) } // MARK: - Req 3.2/3.7: the edit session's combine, from tap to committed union@@ -717,12 +851,9 @@ final class CharacterExtractionUITests: XCTestCase { /// the editor opened. And the edit rows' buttons are borderless: with the /// default style a tap on a fact's statement text landed on the adjacent /// Delete and the fact silently vanished.- func testCombinePresentsItsDialogInPlaceAndQuoteTapsAreInert() {+ func testCombinePresentsItsDialogAndKeepsLegacyFactsHidden() {+ relaunchWithLegacyFacts() openWorkDetail()- openReview()- tapReviewControl("character-review-keep-\(Row.ada)", "Ada can be kept")- tapReviewControl("character-review-keep-\(Row.brede)", "Brede can be kept")- closeReview() waitFor( app.anyElement("work-detail-character"), "The kept characters appear", timeout: 30) @@ -736,13 +867,9 @@ final class CharacterExtractionUITests: XCTestCase { openEditorLine( editLine(named: "Ada"), expecting: "character-editor", in: app, "Ada's line opens her editor")- waitFor(statement, "The fact's statement is shown in the editor")-- // A tap on the statement text itself deletes nothing.- statement.tap()- XCTAssertTrue(- statement.waitForExistence(timeout: 3),- "Tapping a fact's text does not delete the fact")+ XCTAssertFalse(statement.exists, "Legacy statements stay hidden even in the record editor")+ XCTAssertFalse(app.buttons["work-detail-character-fact-delete"].exists)+ XCTAssertFalse(app.staticTexts["Existing facts"].exists) scrollUntilTappableAndTap( app.buttons.matching(identifier: "work-detail-character-combine").firstMatch, in: app,@@ -776,9 +903,12 @@ final class CharacterExtractionUITests: XCTestCase { .matching(NSPredicate(format: "identifier == %@", "work-detail-character")) XCTAssertEqual(characterNames.count, 1, "The source was absorbed into the target") openPill(app.anyElement("work-detail-character"))- scrollUntilPresent(- app.staticTexts["Ada is called Nightjar by the crew."], in: app,- "The moved fact survives the combine")+ waitFor(aliasChip(named: "Nightjar"), "The saved alias survives the combine")+ XCTAssertFalse(app.staticTexts["Ada is called Nightjar by the crew."].exists)+ XCTAssertFalse(app.buttons["work-detail-character-citation"].exists)+ // Exact legacy fact/quote/citation preservation is verified through the+ // real repository by HiddenLegacyFactsTests; this surface must hide it.+ } // MARK: - Req 1.11: the manual pass and its outcomes
diff --git a/Asterism/AsterismUITests/UIJourneySupport.swift b/Asterism/AsterismUITests/UIJourneySupport.swiftindex a64bf902..ae05fd9e 100644--- a/Asterism/AsterismUITests/UIJourneySupport.swift+++ b/Asterism/AsterismUITests/UIJourneySupport.swift@@ -323,7 +323,12 @@ extension XCTestCase { app.staticTexts[labelText], app.anyElement(headerIdentifier), ]- if let header = candidates.first(where: { $0.exists && $0.isHittable }) {+ // Native tap performs its own scrolling/hit testing. On iOS the+ // visible DisclosureGroup header can report isHittable == false;+ // preflighting that value prevented any tap at the list's end.+ // The expanded content, rather than that advisory value, remains+ // the required witness that the action actually succeeded.+ if let header = candidates.first(where: { $0.exists }) { header.tap() if witness.waitForExistence(timeout: 3) { return } }
diff --git a/Asterism/AsterismUITests/WideLayoutUITests.swift b/Asterism/AsterismUITests/WideLayoutUITests.swiftindex 1b23acd4..7548f464 100644--- a/Asterism/AsterismUITests/WideLayoutUITests.swift+++ b/Asterism/AsterismUITests/WideLayoutUITests.swift@@ -851,8 +851,23 @@ final class WideLayoutUITests: XCTestCase { launchToday() XCTAssertFalse(app.anyElement("wide-list-column").exists, "Today has a single pane") let row = recentRows.firstMatch- scrollUntilTappableAndTap(row, in: app, "A noted row is reachable", scroll: { $0.anyElement("recent-list").swipeUp() })- let entryID = String(row.identifier.dropFirst("recent-entry-".count))+ // Reach without opening the inspector: both geometry samples must be+ // the full-width dashboard, before and after the Work push.+ _ = row.waitForExistence(timeout: 15)+ for _ in 0..<8 {+ if row.exists && row.isHittable { break }+ app.anyElement("recent-list").swipeUp()+ _ = row.waitForExistence(timeout: 2)+ }+ XCTAssertTrue(row.exists && row.isHittable, "A noted row is reachable before opening its inspector")+ let rowIdentifier = row.identifier+ let fixedRow = app.anyElement(rowIdentifier)+ let entryID = String(rowIdentifier.dropFirst("recent-entry-".count))+ let dayLabel = app.anyElement("today-header-date").label+ let originalListFrame = app.anyElement("recent-list").frame+ let originalWindowFrame = app.windows.firstMatch.frame+ let selectedRowY = fixedRow.frame.minY+ fixedRow.tap() waitFor(app.anyElement("today-inspector"), "Notes open the inspector") XCTAssertTrue(app.anyElement("recent-list").exists) waitFor(app.buttons["today-inspector-open-work"], "Inspector opens the work").tap()@@ -863,6 +878,120 @@ final class WideLayoutUITests: XCTestCase { XCTAssertFalse(app.buttons["column-back"].exists, "Today uses the native stack control only") waitFor(app.navigationBars.buttons["Back"].firstMatch, "The native stack offers Back").tap() waitFor(app.anyElement("recent-list"), "Back returns to the selected day")+ XCTAssertEqual(app.anyElement("today-header-date").label, dayLabel)+ let list = app.anyElement("recent-list")+ let window = app.windows.firstMatch+ func sameGeometry(_ actual: CGRect, _ expected: CGRect) -> Bool {+ abs(actual.minX - expected.minX) <= 2 && abs(actual.minY - expected.minY) <= 2+ && abs(actual.width - expected.width) <= 2 && abs(actual.height - expected.height) <= 2+ }+ let geometry = expectation(for: NSPredicate { _, _ in+ sameGeometry(list.frame, originalListFrame) && sameGeometry(window.frame, originalWindowFrame)+ }, evaluatedWith: nil)+ XCTAssertEqual(XCTWaiter().wait(for: [geometry], timeout: 15), .completed,+ "Back restores the same full-width dashboard geometry before comparing scroll position")+ for (actual, expected) in [(list.frame, originalListFrame), (window.frame, originalWindowFrame)] {+ XCTAssertEqual(actual.minX, expected.minX, accuracy: 2)+ XCTAssertEqual(actual.minY, expected.minY, accuracy: 2)+ XCTAssertEqual(actual.width, expected.width, accuracy: 2)+ XCTAssertEqual(actual.height, expected.height, accuracy: 2)+ }+ XCTAssertEqual(fixedRow.identifier, rowIdentifier)+ XCTAssertTrue(fixedRow.exists && fixedRow.isHittable, "The same scrolled selected row remains reachable")+ XCTAssertEqual(fixedRow.frame.minY, selectedRowY, accuracy: 2, "Back preserves the reader's scroll position")+ XCTAssertFalse(app.anyElement("work-detail-title").exists, "No stale pushed Work controller remains")+ }++ func testScrolledTodayInspectorAndWorkReturnPreservePositionAndDayChangeResetsIt() {+ launchToday()+ let list = app.anyElement("recent-list")+ let window = app.windows.firstMatch+ let row = waitFor(recentRows.firstMatch, "A noted row is present before scrolling")+ let rowIdentifier = row.identifier+ let entryID = String(rowIdentifier.dropFirst("recent-entry-".count))+ let fixedRow = app.anyElement(rowIdentifier)+ let dayLabel = app.anyElement("today-header-date").label+ let initialListFrame = list.frame+ let initialWindowFrame = window.frame+ let initialRowY = fixedRow.frame.minY+ let shelf = waitFor(app.anyElement("today-releases-shelf"), "The unscrolled release shelf is present")+ let initialShelfY = shelf.frame.minY++ func sameGeometry(_ actual: CGRect, _ expected: CGRect) -> Bool {+ abs(actual.minX - expected.minX) <= 2 && abs(actual.minY - expected.minY) <= 2+ && abs(actual.width - expected.width) <= 2 && abs(actual.height - expected.height) <= 2+ }+ func dashboardGeometryRestored() -> Bool {+ sameGeometry(list.frame, initialListFrame) && sameGeometry(window.frame, initialWindowFrame)+ }+ XCTAssertTrue(list.frame.intersection(window.frame).contains(fixedRow.frame),+ "The same complete noted row starts inside the dashboard viewport")+ list.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.75))+ .press(forDuration: 0.1, thenDragTo:+ list.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.55)))+ let moved = expectation(for: NSPredicate { _, _ in+ dashboardGeometryRestored() && fixedRow.exists && fixedRow.isHittable+ && list.frame.intersection(window.frame).contains(fixedRow.frame)+ && fixedRow.frame.minY < initialRowY - 10+ }, evaluatedWith: nil)+ XCTAssertEqual(XCTWaiter().wait(for: [moved], timeout: 15), .completed,+ "The same visible row actually moves upward before its nonzero position is saved")+ let selectedRowY = fixedRow.frame.minY++ func assertRestoredPosition() {+ let restored = expectation(for: NSPredicate { _, _ in+ !self.app.anyElement("today-inspector").exists && dashboardGeometryRestored()+ && fixedRow.exists && fixedRow.isHittable+ && abs(fixedRow.frame.minY - selectedRowY) <= 2+ }, evaluatedWith: nil)+ XCTAssertEqual(XCTWaiter().wait(for: [restored], timeout: 15), .completed,+ "The full-width dashboard restores the same nonzero row position")+ XCTAssertEqual(app.anyElement("today-header-date").label, dayLabel)+ XCTAssertTrue(sameGeometry(list.frame, initialListFrame))+ XCTAssertTrue(sameGeometry(window.frame, initialWindowFrame))+ XCTAssertEqual(fixedRow.frame.minY, selectedRowY, accuracy: 2)+ XCTAssertFalse(app.anyElement("work-detail-title").exists)+ }++ fixedRow.tap()+ waitFor(app.anyElement("today-inspector"), "The scrolled note opens its inspector")+ waitFor(app.buttons["today-inspector-close"], "Close returns to the scrolled dashboard").tap()+ assertRestoredPosition()++ fixedRow.tap()+ waitFor(app.buttons["today-inspector-open-work"], "The same scrolled note opens its Work").tap()+ waitFor(app.anyElement("work-detail-title"), "The Work fills Today")+ waitFor(app.anyElement("work-detail-focused-entry-" + entryID), "The same note remains focused")+ waitFor(app.navigationBars.buttons["Back"].firstMatch, "Native Back returns from Work").tap()+ waitFor(list, "The dashboard returns after Work")+ assertRestoredPosition()++ XCUIDevice.shared.press(.home)+ app.activate()+ waitFor(list, "The scrolled dashboard returns after app switching")+ assertRestoredPosition()++ waitFor(app.buttons["sidebar-library-reading"], "Reading remains reachable from the scrolled dashboard").tap()+ waitFor(app.anyElement("works-group-reading"), "Reading opens through the real sidebar")+ waitFor(app.buttons["sidebar-today"], "Today remains reachable from Reading").tap()+ waitFor(list, "The scrolled dashboard returns from the sidebar destination")+ assertRestoredPosition()++ if !stripCell(daysFromLaunch: -1).exists { app.anyElement("today-week-previous").tap() }+ waitFor(stripCell(daysFromLaunch: -1), "The previous day remains reachable without scrolling to the top").tap()+ let changedDay = expectation(for: NSPredicate { _, _ in+ self.app.anyElement("today-header-date").label != dayLabel && !self.app.anyElement("today-inspector").exists+ }, evaluatedWith: nil)+ XCTAssertEqual(XCTWaiter().wait(for: [changedDay], timeout: 15), .completed)+ waitFor(app.buttons["today-header-date"], "The fixed date header returns to Today").tap()+ let reset = expectation(for: NSPredicate { _, _ in+ self.app.anyElement("today-header-date").label == dayLabel && dashboardGeometryRestored()+ && shelf.exists && shelf.isHittable && abs(shelf.frame.minY - initialShelfY) <= 2+ }, evaluatedWith: nil)+ XCTAssertEqual(XCTWaiter().wait(for: [reset], timeout: 15), .completed,+ "Changing days resets the content to its original top instead of restoring the scrolled position")+ XCTAssertEqual(shelf.frame.minY, initialShelfY, accuracy: 2)+ XCTAssertFalse(app.anyElement("today-inspector").exists) } func testClosingInspectorAndChangingDayClearItsSelection() {
diff --git a/Asterism/AsterismUITests/XCUIApplication+TestIsolation.swift b/Asterism/AsterismUITests/XCUIApplication+TestIsolation.swiftindex 91faffd5..e6f3f6a1 100644--- a/Asterism/AsterismUITests/XCUIApplication+TestIsolation.swift+++ b/Asterism/AsterismUITests/XCUIApplication+TestIsolation.swift@@ -14,3 +14,14 @@ extension XCTestCase { ) } }+++extension XCUIApplication {+ /// Select the disposable UUID library before app bootstrap on every launch.+ /// CloudKit is nil in the scenario resolver, including native Mac launches.+ func configureSyntheticLaunch(scenario: String = "seeded-m1", runID: String = UUID().uuidString) {+ launchEnvironment["ASTERISM_UI_TEST_SCENARIO"] = scenario+ launchEnvironment["ASTERISM_UI_TEST_RUN_ID"] = runID+ launchEnvironment["ASTERISM_UI_TEST_EXTRACTION"] = "unavailable"+ }+}
diff --git a/Makefile b/Makefileindex 5462a1fa..139646a1 100644--- a/Makefile+++ b/Makefile@@ -44,6 +44,8 @@ endif # Optional xcodebuild flags for simulator test targets; empty keeps their # existing invocation unchanged. Useful for isolating Xcode diagnostics stalls. XCODE_TEST_FLAGS ?=+# Build-only flags remain separate from test result-bundle flags.+XCODE_BUILD_FLAGS ?= .PHONY: help help:@@ -158,6 +160,7 @@ build-mac: -destination '$(MAC_DESTINATION)' \ -configuration $(CONFIG) \ -derivedDataPath $(DERIVED_DATA) \+ $(XCODE_BUILD_FLAGS) \ $(PIPE_PRETTY) @if [ ! -d "$(MAC_APPEX)" ]; then \ echo "build-mac: the Mac share extension is missing from the built app:"; \@@ -418,7 +421,7 @@ test-performance-m4: ASTERISM_PERFORMANCE_CONTROLLED="$(CONTROLLED)" \ ASTERISM_PERFORMANCE_LOG="$(PERFORMANCE_LOG)" swift test \ --package-path Packages/AsterismCore \- --no-parallel \+ --no-parallel $(SWIFT_TEST_FLAGS) \ -c release \ -Xswiftc -DASTERISM_PERFORMANCE_TESTING \ --filter '$(PERFORMANCE_FILTER)' \
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationEndpoints.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationEndpoints.swiftnew file mode 100644index 00000000..7a937556--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationEndpoints.swift@@ -0,0 +1,116 @@+import Foundation+import SwiftData++struct AssociationRecordAddress: Hashable, Sendable {+ var kind: RecordKind+ var id: UUID+}++/// Selected endpoint values, globally complete for each encountered application+/// UUID. Unrelated facts, record prose, title, URL and rating do not enter a+/// membership fingerprint or turn a coherent matching tuple into a conflict.+struct AssociationEndpointInventory {+ struct Source {+ var id: UUID+ var workID: UUID?+ var eligible: Bool+ var note: String+ var fingerprint: String+ var title: String+ }+ struct Target {+ var address: AssociationRecordAddress+ var workID: UUID?+ var names: [String]+ var fingerprint: String+ var displayName: String+ }+ var sources: [UUID: Source]+ var targets: [AssociationRecordAddress: Target]+ var sourceStates: [UUID: String]+ var targetStates: [AssociationRecordAddress: String]+ var sourceOwnerIDs: [UUID: Set<UUID>]+ var targetOwnerIDs: [AssociationRecordAddress: Set<UUID>]+ var liveWorkIDs: Set<UUID>+ var endpointFetchCount: Int++ func current(_ pair: AssociationPair) -> AssociationCurrentPair? {+ guard liveWorkIDs.contains(pair.workID), let source = sources[pair.entryID], source.eligible,+ source.workID == pair.workID,+ let target = targets[.init(kind: pair.kind, id: pair.recordID)], target.workID == pair.workID else { return nil }+ let evidence = RecordMentionGrounding.evidence(names: target.names, in: source.note)+ guard !evidence.isEmpty else { return nil }+ return .init(pair: pair, sourceFingerprint: source.fingerprint,+ matchingFingerprint: target.fingerprint, evidence: evidence)+ }+ static func read(context: ModelContext, pairs: Set<AssociationPair>,+ entryIDs explicitEntries: Set<UUID> = [],+ records explicitRecords: Set<AssociationRecordAddress> = []) throws -> Self {+ let entryIDs = Array(explicitEntries.union(pairs.map(\.entryID)))+ let records = explicitRecords.union(pairs.map { .init(kind: $0.kind, id: $0.recordID) })+ var fetches = 0+ let entries: [Entry]+ if entryIDs.isEmpty { entries = [] } else {+ fetches += 1+ entries = try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { entryIDs.contains($0.id) }))+ }+ var sources: [UUID: Source] = [:], sourceStates: [UUID: String] = [:]+ var sourceOwners: [UUID: Set<UUID>] = [:], targetOwners: [AssociationRecordAddress: Set<UUID>] = [:]+ for (id, rows) in Dictionary(grouping: entries, by: \.id) {+ sourceOwners[id] = Set(rows.compactMap { $0.work?.id })+ let states = Set(rows.map(sourceFingerprint)).sorted()+ sourceStates[id] = AssociationDigest.of("association/source-group/v1", states)+ guard states.count == 1, let row = GroupOrdering.sortedEntryRows(rows).first else { continue }+ sources[id] = .init(id: id, workID: row.work?.id, eligible: eligible(row), note: row.note,+ fingerprint: states[0], title: row.effectiveChapterTitle ?? row.captureTitle)+ }+ var targets: [AssociationRecordAddress: Target] = [:], targetStates: [AssociationRecordAddress: String] = [:]+ func add<Row: RecordRow>(_ rows: [Row]) {+ for (id, copies) in Dictionary(grouping: rows, by: \.recordID) {+ let address = AssociationRecordAddress(kind: Row.kind, id: id)+ targetOwners[address] = Set(copies.compactMap(\.ownerWorkID))+ let states = Set(copies.map(targetFingerprint)).sorted()+ targetStates[address] = AssociationDigest.of("association/target-group/v1", states)+ guard states.count == 1, let row = copies.first else { continue }+ targets[address] = .init(address: address, workID: row.ownerWorkID,+ names: Array(Set(copies.flatMap { [$0.name, $0.nameKey] + $0.aliases })).sorted(),+ fingerprint: states[0], displayName: row.name)+ }+ }+ let characterIDs = records.filter { $0.kind == .character }.map(\.id)+ if !characterIDs.isEmpty { fetches += 1; add(try CharacterRecord.rows(ids: characterIDs, context: context)) }+ let placeIDs = records.filter { $0.kind == .place }.map(\.id)+ if !placeIDs.isEmpty { fetches += 1; add(try Place.rows(ids: placeIDs, context: context)) }+ let workIDs = Array(Set(sources.values.compactMap(\.workID)).union(targets.values.compactMap(\.workID)))+ var liveWorks: Set<UUID> = []+ if !pairs.isEmpty && !workIDs.isEmpty {+ fetches += 1+ liveWorks = Set(try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { workIDs.contains($0.id) })).map(\.id))+ }+ return .init(sources: sources, targets: targets, sourceStates: sourceStates,+ targetStates: targetStates, sourceOwnerIDs: sourceOwners, targetOwnerIDs: targetOwners,+ liveWorkIDs: liveWorks, endpointFetchCount: fetches)+ }+ static func eligible(_ row: Entry) -> Bool {+ guard row.mergedIntoEntryID == nil else { return false }+ guard row.authoredTargetData != nil else { return true }+ return row.authoredTarget?.kind == .chapter+ }+ static func sourceFingerprint(_ row: Entry) -> String {+ sourceFingerprint(id: row.id, workID: row.work?.id, eligible: eligible(row), note: row.note)+ }+ static func sourceFingerprint(id: UUID, workID: UUID?, eligible: Bool, note: String) -> String {+ AssociationDigest.of("association/source/v1", [id.uuidString, workID?.uuidString ?? "",+ eligible ? "chapter" : "ineligible", note])+ }+ static func targetFingerprint<Row: RecordRow>(_ row: Row) -> String {+ targetFingerprint(kind: Row.kind, id: row.recordID, workID: row.ownerWorkID,+ name: row.name, nameKey: row.nameKey, aliases: row.aliases)+ }+ static func targetFingerprint(kind: RecordKind, id: UUID, workID: UUID?, name: String,+ nameKey: String, aliases: [String]) -> String {+ AssociationDigest.of("association/matching/v1", [kind.rawValue, id.uuidString,+ workID?.uuidString ?? "", RecordNameKey.normalize(name), nameKey]+ + Array(Set(aliases.map(RecordNameKey.normalize))).sorted())+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationImportPreparation.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationImportPreparation.swiftnew file mode 100644index 00000000..15d86dd0--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationImportPreparation.swift@@ -0,0 +1,316 @@+import Foundation+import SwiftData++/// Values captured in the import's existing transaction. Incoming roots never+/// become local before-authority merely because their raw rows were staged.+struct AssociationImportPreparation {+ let before: AssociationMutation+ let plannedScopes: Set<AssociationScope>+ let incomingEvents: [AssociationRawEvent]+ let incomingNotes: [AssociationRawNote]+ let mergedEvents: [AssociationLedgerEvent]+ let quarantinedIDs: Set<UUID>++ static func prepare(_ payload: BackupImportPayload, context: ModelContext, timestamp: Date) throws -> Self {+ let entries = Set(payload.entries.map(\.id))+ let records = Set(payload.characters.map { AssociationRecordAddress(kind: .character, id: $0.id) })+ .union(payload.places.map { .init(kind: .place, id: $0.id) })+ let works = Set(payload.works.map(\.id)).union(payload.entries.compactMap(\.workID))+ .union(payload.characters.compactMap(\.workID)).union(payload.places.map(\.workID))+ .union(payload.associationEvents.map(\.workID)).union(payload.pairNoteVersions.map(\.workID))+ // MUST precede incoming raw staging: all before-active/inactive roots+ // and mutable physical copies belong to the local selected snapshot.+ let before = try AssociationMutation.capture(context: context, workIDs: works,+ entryIDs: entries, records: records, allPairs: true)+ try insertMissing(events: payload.associationEvents, notes: payload.pairNoteVersions, context: context)+ let union = try AssociationStorageInventory.read(context: context, workIDs: before.workIDs,+ eventIDs: Set(payload.associationEvents.map(\.id)), noteIDs: Set(payload.pairNoteVersions.map(\.id)))+ let pairs = before.pairs.union(union.ledger.pairs)+ let actual = try AssociationEndpointInventory.read(context: context, pairs: pairs,+ entryIDs: entries, records: records)+ let projection = try project(payload, onto: actual, context: context)+ let projected = projection.endpoints+ let uncertainEntryIDs = Set(projection.uncertainScopes.compactMap { scope -> UUID? in+ if case .entry(_, let id) = scope { return id }; return nil+ })+ // Selected history can name an owner no physical Entry currently+ // exposes. Its old proof must be held before the same early base save.+ let uncertainScopes = projection.uncertainScopes.union(pairs.compactMap { pair -> AssociationScope? in+ uncertainEntryIDs.contains(pair.entryID) ? .entry(workID: pair.workID, entryID: pair.entryID) : nil+ })+ let scopes = changedExistingScopes(before: actual, after: projected, entries: entries, records: records, pairs: pairs)+ .union(uncertainScopes).subtracting(projection.arrivalScopes)+ let incomingIDs = Set(payload.associationEvents.map(\.id))+ var provedScopes: Set<AssociationScope> = [], ambiguousScopes: Set<AssociationScope> = []+ let localRoots = Dictionary(grouping: before.storage.rawEvents.compactMap { raw -> (AssociationPair, UUID)? in+ guard let event = raw.value, case .accept(let core) = event.payload else { return nil }+ return (core.pair, event.id)+ }, by: { $0.0 }).mapValues { Set($0.map(\.1)) }+ for pair in pairs {+ guard let current = projected.current(pair) else { continue }+ let active = union.ledger.activeAcceptanceIDs(for: current)+ guard !active.isEmpty else { continue }+ let touched = scopes.intersection([+ .entry(workID: pair.workID, entryID: pair.entryID),+ .record(workID: pair.workID, kind: pair.kind, recordID: pair.recordID), .work(pair.workID)])+ if !active.isDisjoint(with: incomingIDs) { provedScopes.formUnion(touched) }+ // Only LOCAL known roots can make this scope genuinely ambiguous.+ let known = localRoots[pair, default: []]+ if !active.intersection(known).subtracting(before.active[pair, default: []]).isEmpty {+ ambiguousScopes.formUnion(touched)+ }+ }+ // Persist genuine invalidations before the earliest base-field chunk.+ // Clean coherent bundles retain their own exact barriers and receipts.+ var merged = union.rawEvents.compactMap(\.value)+ for scope in scopes where uncertainScopes.contains(scope) || ambiguousScopes.contains(scope) || !provedScopes.contains(scope) {+ let event = AssociationLedgerEvent(payload: .invalidate(scope))+ context.insert(try AssociationEvent(event: event, recordedAt: timestamp)); merged.append(event)+ }+ // Endpoint arrival was not an edit of a known local field. The+ // later shared mutation finalizer must not add an artificial barrier+ // after the archive's own coherent bundle has been materialized.+ var handledScopes = scopes.union(projection.arrivalScopes)+ for id in entries where actual.sourceStates[id] == nil {+ for owner in projected.sourceOwnerIDs[id, default: []] { handledScopes.insert(.entry(workID: owner, entryID: id)) }+ }+ for address in records where actual.targetStates[address] == nil {+ for owner in projected.targetOwnerIDs[address, default: []] {+ handledScopes.insert(.record(workID: owner, kind: address.kind, recordID: address.id))+ }+ }+ return .init(before: before, plannedScopes: handledScopes,+ incomingEvents: payload.associationEvents, incomingNotes: payload.pairNoteVersions,+ mergedEvents: merged, quarantinedIDs: union.quarantinedEventIDs)+ }++ func finish(context: ModelContext, timestamp: Date) throws {+ _ = try before.finish(context: context, timestamp: timestamp,+ additionalEvents: mergedEvents, additionalQuarantinedIDs: quarantinedIDs,+ invalidationExemptions: plannedScopes)+ // A current local physical copy may also have been byte-identical to an+ // incoming variant. Preserve that incoming whole value after carry,+ // within the SAME final save, without stamping its other variants.+ try Self.insertMissing(events: incomingEvents, notes: incomingNotes, context: context)+ }++ private static func insertMissing(events: [AssociationRawEvent], notes: [AssociationRawNote], context: ModelContext) throws {+ let eventIDs = Array(Set(events.map(\.id))), noteIDs = Array(Set(notes.map(\.id)))+ var eventBodies: Set<String> = [], noteBodies: Set<String> = []+ if !eventIDs.isEmpty {+ eventBodies = Set(try context.fetch(FetchDescriptor<AssociationEvent>(predicate: #Predicate { eventIDs.contains($0.id) }))+ .map { AssociationRawEvent($0).variantIdentity })+ }+ if !noteIDs.isEmpty {+ noteBodies = Set(try context.fetch(FetchDescriptor<PairNoteVersion>(predicate: #Predicate { noteIDs.contains($0.id) }))+ .map { AssociationRawNote($0).variantIdentity })+ }+ for raw in events where eventBodies.insert(raw.variantIdentity).inserted { context.insert(AssociationEvent(raw: raw)) }+ for raw in notes where noteBodies.insert(raw.variantIdentity).inserted { context.insert(PairNoteVersion(raw: raw)) }+ }++ private static func changedExistingScopes(before: AssociationEndpointInventory, after: AssociationEndpointInventory,+ entries: Set<UUID>, records: Set<AssociationRecordAddress>,+ pairs: Set<AssociationPair>) -> Set<AssociationScope> {+ let entryOwners = Dictionary(grouping: pairs, by: \.entryID).mapValues { Set($0.map(\.workID)) }+ let recordOwners = Dictionary(grouping: pairs) { AssociationRecordAddress(kind: $0.kind, id: $0.recordID) }+ .mapValues { Set($0.map(\.workID)) }+ var result: Set<AssociationScope> = []+ for id in entries where before.sourceStates[id] != nil && before.sourceStates[id] != after.sourceStates[id] {+ for owner in before.sourceOwnerIDs[id, default: []].union(after.sourceOwnerIDs[id, default: []])+ .union(entryOwners[id, default: []]) { result.insert(.entry(workID: owner, entryID: id)) }+ }+ for address in records where before.targetStates[address] != nil && before.targetStates[address] != after.targetStates[address] {+ for owner in before.targetOwnerIDs[address, default: []].union(after.targetOwnerIDs[address, default: []])+ .union(recordOwners[address, default: []]) {+ result.insert(.record(workID: owner, kind: address.kind, recordID: address.id))+ }+ }+ return result+ }++ /// Potential *winning value changes*, rather than the presence of archive+ /// arrays. An older/forbidden Work and its memberships cannot change the+ /// normalization used by the later Entry writer.+ private static func normalizationMayChange(_ payload: BackupImportPayload, context: ModelContext) throws -> Bool {+ let types = try LibraryRepository.workTypeDirectory(context: context)+ let workIDs = payload.works.map(\.id)+ let works = workIDs.isEmpty ? [] : try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { workIDs.contains($0.id) }))+ let grouped = Dictionary(grouping: works, by: \.id)+ var applied: Set<UUID> = []+ var changed = false+ for record in payload.works {+ let rows = grouped[record.id, default: []]+ if !rows.isEmpty {+ guard let group = LibraryRepository.workGroup(id: record.id, rows: rows, types: types),+ !group.isTorn, record.modifiedAt >= group.modifiedAt else { continue }+ }+ applied.insert(record.id)+ if rows.isEmpty { changed = true; continue }+ let publication = try record.publicationState?.canonicalData()+ for row in rows {+ // These are the relation key, authored classification and+ // survivor-election inputs of DuplicateScan, excluding progress+ // and modification timestamps which do not alter its answer.+ if row.lastParsedTitle != record.lastParsedTitle+ || row.displayTitle != record.displayTitle || row.titleProvenance != record.titleProvenance+ || row.genericNotes != record.genericNotes || row.genreTags != record.genreTags+ || row.workTypeID != record.workTypeID || row.workStatusRaw != record.workStatus.rawValue+ || row.publicationStateData != publication || row.readingStatusRaw != record.readingStatus.rawValue+ || row.verdict != record.verdict || row.seriesID != record.seriesID || row.seriesPosition != record.seriesPosition+ || row.releaseDays != record.releaseDays || row.createdAt != record.createdAt+ || row.thumbnailShapeRaw != record.thumbnailShape+ || row.thumbnailDigest != record.thumbnail.map(Hexadecimal.sha256) {+ changed = true+ }+ }+ }+ let memberships = try context.fetch(FetchDescriptor<WorkSiteMembership>())+ let byMembership = Dictionary(grouping: memberships, by: \.id)+ let existing = Set(byMembership.keys)+ for record in LibraryRepository.normalizedMemberships(payload.memberships,+ existingMembershipIDs: existing, appliedWorkIDs: applied)+ where LibraryRepository.willWriteMembership(record, existingMembershipIDs: existing, appliedWorkIDs: applied) {+ let rows = byMembership[record.id, default: []]+ if rows.isEmpty || rows.contains(where: {+ $0.hostname != record.hostname || $0.workID != (record.workID ?? $0.workID)+ || $0.urlIdentity != record.urlIdentity || $0.urlIdentityState != record.urlIdentityState+ || $0.urlIdentityRuleID != record.urlIdentityRuleID || $0.workURLString != record.workURLString+ }) { changed = true }+ }+ let distinct = Dictionary(grouping: try context.fetch(FetchDescriptor<WorkDistinctPair>()), by: \.id)+ for record in payload.distinctPairs {+ let rows = distinct[record.id, default: []]+ if rows.isEmpty || rows.contains(where: { record.recordedAt >= $0.recordedAt+ && ($0.lowerWorkID != record.lowerWorkID || $0.higherWorkID != record.higherWorkID) }) { changed = true }+ }+ for record in payload.workTypes {+ guard record.stateRaw == WorkTypeState.merged.rawValue || WorkTypeName.validate(record.name) == nil else { continue }+ guard let identity = types[record.id] else { changed = true; continue }+ if identity.state != .merged && (record.stateRaw == WorkTypeState.merged.rawValue+ || (record.stateRaw == WorkTypeState.active.rawValue && identity.state == .removed)) { changed = true }+ }+ for record in payload.works where record.workTypeID != nil && record.typeName != nil {+ if let id = record.workTypeID, types[id] == nil, let name = record.typeName,+ WorkTypeName.validate(name) == nil { changed = true }+ }+ return changed+ }++ /// Project only fields this archive is allowed to win. The writer shares+ /// its existing torn/newer-local predicates; no model or live field is+ /// changed while deciding whether a chunk needs an invalidation.+ private static func project(_ payload: BackupImportPayload, onto original: AssociationEndpointInventory,+ context: ModelContext) throws -> (endpoints: AssociationEndpointInventory, uncertainScopes: Set<AssociationScope>, arrivalScopes: Set<AssociationScope>) {+ var result = original+ var uncertainScopes: Set<AssociationScope> = [], arrivalScopes: Set<AssociationScope> = []+ let entryIDs = payload.entries.map(\.id)+ let entryRows = entryIDs.isEmpty ? [] : try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { entryIDs.contains($0.id) }))+ let byEntry = Dictionary(grouping: entryRows, by: \.id)+ let hasSplitManualOwners = byEntry.values.contains { rows in+ Set(rows.filter { $0.workAssignmentProvenance == .manual }.compactMap { $0.work?.id }).count > 1+ }+ let mayChangeNormalization = try hasSplitManualOwners && normalizationMayChange(payload, context: context)+ let canonical = try LibraryRepository.canonicalWorkIDs(normalising: entryRows, context: context)+ let relevantWorks = Array(Set(payload.works.map(\.id)).union(payload.entries.compactMap(\.workID))+ .union(payload.characters.compactMap(\.workID)).union(payload.places.map(\.workID))+ .union(original.sourceOwnerIDs.values.flatMap { $0 }).union(original.targetOwnerIDs.values.flatMap { $0 }))+ let present = relevantWorks.isEmpty ? [] : try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { relevantWorks.contains($0.id) }))+ let presentWorkIDs = Set(present.map(\.id))+ let incomingWorkIDs = Set(payload.works.map(\.id))+ let liveWorks = presentWorkIDs.union(incomingWorkIDs)+ result.liveWorkIDs.formUnion(liveWorks)+ for record in payload.entries {+ let rows = byEntry[record.id, default: []]+ let chapter = payload.chapterEntries[record.id]+ let targetData: Data?, redirect: UUID?+ if let chapter { targetData = chapter.authoredTargetData; redirect = chapter.mergedIntoEntryID }+ else { targetData = rows.first?.authoredTargetData; redirect = rows.first?.mergedIntoEntryID }+ let eligible = redirect == nil && (targetData == nil || targetData.flatMap { try? AuthoredEntryTarget.decode($0) }?.kind == .chapter)+ let owner = record.workID.flatMap { liveWorks.contains($0) ? $0 : nil }+ if !rows.isEmpty, LibraryRepository.applicableImportedEntryGroup(record, rows: rows,+ hasChapterRecord: chapter != nil, canonicalWorkIDs: canonical) == nil {+ // Works/types/memberships/distinct decisions land BEFORE the+ // writer rederives assignment normalization. A currently torn+ // split may become eligible then. Hold its genuinely uncertain+ // scope now, before any relevant base save, rather than assuming+ // the current normalization directory remains the winning one.+ let manualOwners = Set(rows.filter { $0.workAssignmentProvenance == .manual }.compactMap { $0.work?.id })+ if mayChangeNormalization, manualOwners.count > 1,+ LibraryRepository.importedEntryFieldsAllowed(record, rows: rows, hasChapterRecord: chapter != nil) {+ let intended = AssociationEndpointInventory.sourceFingerprint(id: record.id, workID: owner,+ eligible: eligible, note: record.note)+ if rows.contains(where: { AssociationEndpointInventory.sourceFingerprint($0) != intended }) {+ for work in Set(rows.compactMap { $0.work?.id }).union(owner.map { [$0] } ?? []) {+ uncertainScopes.insert(.entry(workID: work, entryID: record.id))+ }+ }+ }+ continue+ }+ if let owner, incomingWorkIDs.contains(owner), !presentWorkIDs.contains(owner),+ let current = original.sources[record.id], current.workID == nil,+ current.fingerprint == AssociationEndpointInventory.sourceFingerprint(id: record.id,+ workID: nil, eligible: eligible, note: record.note),+ !rows.isEmpty, rows.allSatisfy({ row in+ guard row.work == nil, !row.intentionallyUnattached,+ let citations = try? row.citations, case .pattern = citations.workAssignment,+ citations.workAssignment == record.citations.workAssignment,+ citations.workURL == nil, citations.workURLAssignmentKind == nil else { return false }+ return true+ }) {+ // A valid unresolved pattern assignment and its missing Work+ // arrived together. This closes unchanged metadata; it does not+ // reinterpret a deliberate/manual unattachment or a torn body.+ arrivalScopes.insert(.entry(workID: owner, entryID: record.id))+ }+ let fp = AssociationEndpointInventory.sourceFingerprint(id: record.id, workID: owner, eligible: eligible, note: record.note)+ result.sources[record.id] = .init(id: record.id, workID: owner, eligible: eligible, note: record.note,+ fingerprint: fp, title: record.captureTitle)+ result.sourceStates[record.id] = AssociationDigest.of("association/source-group/v1", [fp])+ result.sourceOwnerIDs[record.id] = owner.map { Set([$0]) } ?? []+ }+ func apply<Row: RecordRow>(_ archived: [Row.ArchiveRecord], type: Row.Type) throws where Row.ArchiveRecord: ArchivedRecord {+ let ids = archived.map(\.recordID)+ let rows = try Row.rows(ids: ids, context: context)+ let grouped = Dictionary(grouping: rows, by: \.recordID)+ for record in archived {+ let copies = grouped[record.recordID, default: []]+ if !copies.isEmpty, LibraryRepository.applicableImportedRecordGroup(record, rows: copies) == nil { continue }+ let address = AssociationRecordAddress(kind: Row.kind, id: record.recordID)+ let archivedOwner = record.archivedWorkID+ if Row.kind == .character, let owner = archivedOwner,+ incomingWorkIDs.contains(owner), !presentWorkIDs.contains(owner),+ let current = original.targets[address], current.workID == nil,+ current.fingerprint == AssociationEndpointInventory.targetFingerprint(kind: Row.kind,+ id: record.recordID, workID: nil, name: record.name, nameKey: record.nameKey, aliases: record.aliases),+ !copies.isEmpty, copies.allSatisfy({ row in+ row.ownerWorkID == nil && ExactScalarString(row.name) == ExactScalarString(record.name)+ && ExactScalarString(row.nameKey) == ExactScalarString(record.nameKey)+ && Set(row.aliases.map(ExactScalarString.init)) == Set(record.aliases.map(ExactScalarString.init))+ }) {+ arrivalScopes.insert(.record(workID: owner, kind: Row.kind, recordID: record.recordID))+ }+ let owners: [UUID?] = copies.isEmpty ? [Row.kind == .place ? archivedOwner : archivedOwner.flatMap { liveWorks.contains($0) ? $0 : nil }]+ : copies.map { row in+ if let archivedOwner, liveWorks.contains(archivedOwner) { return archivedOwner }+ if Row.kind == .place, let owner = row.ownerWorkID, !liveWorks.contains(owner) { return archivedOwner }+ return row.ownerWorkID+ }+ let fingerprints = Set(owners.map { owner in+ AssociationEndpointInventory.targetFingerprint(kind: Row.kind, id: record.recordID,+ workID: owner, name: record.name, nameKey: record.nameKey, aliases: record.aliases)+ }).sorted()+ result.targetStates[address] = AssociationDigest.of("association/target-group/v1", fingerprints)+ result.targetOwnerIDs[address] = Set(owners.compactMap { $0 })+ if fingerprints.count == 1 {+ result.targets[address] = .init(address: address, workID: owners[0],+ names: [record.name, record.nameKey] + record.aliases, fingerprint: fingerprints[0], displayName: record.name)+ } else { result.targets.removeValue(forKey: address) }+ }+ }+ try apply(payload.characters, type: CharacterRecord.self)+ try apply(payload.places, type: Place.self)+ return (result, uncertainScopes, arrivalScopes)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationLedger.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationLedger.swiftnew file mode 100644index 00000000..69d82aa2--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationLedger.swift@@ -0,0 +1,524 @@+import Foundation++/// Stable application identities; neither a URL nor a SwiftData object identifier.+public struct AssociationPair: Sendable, Hashable, Codable {+ public var workID: UUID+ public var entryID: UUID+ public var kind: RecordKind+ public var recordID: UUID+ public init(workID: UUID, entryID: UUID, kind: RecordKind, recordID: UUID) {+ self.workID = workID; self.entryID = entryID; self.kind = kind; self.recordID = recordID+ }+}++public enum AssociationScope: Sendable, Hashable, Codable {+ case entry(workID: UUID, entryID: UUID)+ case record(workID: UUID, kind: RecordKind, recordID: UUID)+ case work(UUID)+ public var workID: UUID {+ switch self { case .entry(let work, _), .record(let work, _, _), .work(let work): work }+ }+}++public struct AssociationEvidence: Sendable, Hashable, Codable {+ public var key: String+ /// Exact current saved-note spelling. Historical acceptance spelling is not current evidence.+ public var spelling: String+ public init(key: String, spelling: String) { self.key = key; self.spelling = spelling }+ public static func == (lhs: Self, rhs: Self) -> Bool {+ lhs.key == rhs.key && ExactScalarString(lhs.spelling) == ExactScalarString(rhs.spelling)+ }+ static func ordered(_ lhs: Self, _ rhs: Self) -> Bool {+ if lhs.key != rhs.key { return lhs.key.utf8.lexicographicallyPrecedes(rhs.key.utf8) }+ return lhs.spelling.utf8.lexicographicallyPrecedes(rhs.spelling.utf8)+ }+ public func hash(into hasher: inout Hasher) {+ hasher.combine(key); hasher.combine(ExactScalarString(spelling))+ }+}++public struct AssociationCurrentPair: Sendable, Equatable {+ public var pair: AssociationPair+ public var sourceFingerprint: String+ public var matchingFingerprint: String+ public var evidence: [AssociationEvidence]+ public init(pair: AssociationPair, sourceFingerprint: String, matchingFingerprint: String,+ evidence: [AssociationEvidence]) {+ self.pair = pair; self.sourceFingerprint = sourceFingerprint+ self.matchingFingerprint = matchingFingerprint; self.evidence = evidence+ }+}++/// The existing identity operation, recorded compactly with the acceptance.+/// Its permitted changed axes are explicit; importing an arbitrary pair mapping+/// cannot authorize a different kind of identity change.+public enum AssociationRebindOperation: Sendable, Equatable, Codable {+ case entryMerge(workID: UUID, fromEntryID: UUID, toEntryID: UUID)+ case recordMerge(workID: UUID, kind: RecordKind, fromRecordID: UUID, toRecordID: UUID)+ case conversion(workID: UUID, fromKind: RecordKind, fromRecordID: UUID, toRecordID: UUID)+ case workMerge(fromWorkID: UUID, toWorkID: UUID)+ func permits(from: AssociationPair, to: AssociationPair) -> Bool {+ switch self {+ case .entryMerge(let work, let source, let destination):+ from.workID == work && to.workID == work && from.entryID == source+ && to.entryID == destination && source != destination+ && from.kind == to.kind && from.recordID == to.recordID+ case .recordMerge(let work, let kind, let source, let destination):+ from.workID == work && to.workID == work && from.kind == kind && to.kind == kind+ && from.recordID == source && to.recordID == destination && source != destination+ && from.entryID == to.entryID+ case .conversion(let work, let kind, let source, let destination):+ from.workID == work && to.workID == work && from.kind == kind && to.kind == kind.other+ && from.recordID == source && to.recordID == destination && from.entryID == to.entryID+ case .workMerge(let source, let destination):+ from.workID == source && to.workID == destination && source != destination+ && from.entryID == to.entryID && from.kind == to.kind && from.recordID == to.recordID+ }+ }+}++public struct AssociationRebind: Sendable, Equatable, Codable {+ public var operation: AssociationRebindOperation+ public var predecessorIDs: [UUID]+ public init(operation: AssociationRebindOperation, predecessorIDs: [UUID]) {+ self.operation = operation+ self.predecessorIDs = AssociationDigest.ordered(predecessorIDs)+ }+}++public struct AssociationAcceptance: Sendable, Equatable, Codable {+ public var pair: AssociationPair+ public var spellingKeys: [String]+ public var reconsideredRejectionIDs: [UUID]+ public var rebind: AssociationRebind?+ public init(pair: AssociationPair, spellingKeys: [String], reconsideredRejectionIDs: [UUID] = [],+ rebind: AssociationRebind? = nil) {+ self.pair = pair; self.spellingKeys = Array(Set(spellingKeys)).sorted()+ self.reconsideredRejectionIDs = AssociationDigest.ordered(reconsideredRejectionIDs); self.rebind = rebind+ }+}++public struct AssociationRejection: Sendable, Equatable, Codable {+ public var pair: AssociationPair+ public var spellingKeys: [String]+ public init(pair: AssociationPair, spellingKeys: [String]) {+ self.pair = pair; self.spellingKeys = Array(Set(spellingKeys)).sorted()+ }+}++public struct AssociationRetirement: Sendable, Equatable, Codable {+ public var pair: AssociationPair+ public var acceptanceIDs: [UUID]+ public init(pair: AssociationPair, acceptanceIDs: [UUID]) {+ self.pair = pair; self.acceptanceIDs = AssociationDigest.ordered(acceptanceIDs)+ }+}++public struct AssociationCoverage: Sendable, Equatable, Codable {+ public var workID: UUID+ public var entryID: UUID+ public var eligibilityDigest: String+ public init(workID: UUID, entryID: UUID, eligibilityDigest: String) {+ self.workID = workID; self.entryID = entryID; self.eligibilityDigest = eligibilityDigest+ }+}++public enum AssociationEventPayload: Sendable, Equatable, Codable {+ case accept(AssociationAcceptance)+ case reject(AssociationRejection)+ case retire(AssociationRetirement)+ case invalidate(AssociationScope)+ case coverage(AssociationCoverage)+ case pendingReview(AssociationPendingReview)+ case reviewAcknowledgement(AssociationReviewAcknowledgement)+ public var workID: UUID {+ switch self {+ case .accept(let value): value.pair.workID+ case .reject(let value): value.pair.workID+ case .retire(let value): value.pair.workID+ case .invalidate(let value): value.workID+ case .coverage(let value): value.workID+ case .pendingReview(let value): value.workID+ case .reviewAcknowledgement(let value): value.workID+ }+ }+ public var pair: AssociationPair? {+ switch self {+ case .accept(let value): value.pair+ case .reject(let value): value.pair+ case .retire(let value): value.pair+ default: nil+ }+ }+}++/// One indivisible proof of the current pair. Variants never merge field by field.+public struct AssociationValidationReceipt: Sendable, Equatable, Hashable, Codable {+ public var pair: AssociationPair+ public var sourceFingerprint: String+ public var matchingFingerprint: String+ public var sourceBarrierDigest: String+ public var recordBarrierDigest: String+ public var decisionDigest: String+ public var evidence: [AssociationEvidence]+}++public struct AssociationLedgerEvent: Sendable, Equatable, Codable {+ public var id: UUID+ public var payload: AssociationEventPayload+ public var validation: AssociationValidationReceipt?+ public init(id: UUID = UUID(), payload: AssociationEventPayload, validation: AssociationValidationReceipt? = nil) {+ self.id = id; self.payload = payload; self.validation = validation+ }+ public func validated(by receipt: AssociationValidationReceipt) -> Self {+ var value = self; value.validation = receipt; return value+ }+}++/// Length framing and typed domains prevent concatenation and cross-scope collisions.+/// Dates and physical row order deliberately do not enter any decision.+public enum AssociationDigest {+ public static func of(_ domain: String, _ components: [String]) -> String {+ var bytes = Data()+ for part in [domain] + components {+ let value = Data(part.utf8)+ bytes.append(contentsOf: "\(value.count):".utf8); bytes.append(value)+ }+ return Hexadecimal.sha256(bytes)+ }+ static func ordered(_ ids: [UUID]) -> [UUID] {+ Array(Set(ids)).sorted { $0.uuidString < $1.uuidString }+ }+ static func scopeToken(_ scope: AssociationScope) -> [String] {+ switch scope {+ case .entry(let work, let entry): ["entry", work.uuidString, entry.uuidString]+ case .record(let work, let kind, let record): ["record", work.uuidString, kind.rawValue, record.uuidString]+ case .work(let work): ["work", work.uuidString]+ }+ }+ static func pairToken(_ pair: AssociationPair) -> [String] {+ [pair.workID.uuidString, pair.entryID.uuidString, pair.kind.rawValue, pair.recordID.uuidString]+ }+}++/// A single operation-local inventory shared by every selected pair. Immutable+/// identity validation and historical closure are computed once, never per pair.+public struct AssociationLedgerInventory: Sendable {+ private var events: [UUID: AssociationLedgerEvent] = [:]+ private var receipts: [UUID: Set<AssociationValidationReceipt>] = [:]+ private var acceptances: [UUID: AssociationAcceptance] = [:]+ private var rootsByPair: [AssociationPair: Set<UUID>] = [:]+ private var rejectionsByPair: [AssociationPair: [(UUID, AssociationRejection)]] = [:]+ private var acknowledgements: [UUID: [String: Set<UUID>]] = [:]+ private var barriers: [AssociationScope: Set<UUID>] = [:]+ private var barriersByWork: [UUID: Set<UUID>] = [:]+ public private(set) var pendingReviews = AssociationPendingReviewInventory(events: [])+ private var coverageByEntry: [UUID: [AssociationCoverage]] = [:]+ private var barrierDigests: [AssociationScope: String] = [:]+ private var decisionsByEntry: [UUID: Set<UUID>] = [:]+ private var consumed: Set<UUID> = []+ private var retired: Set<UUID> = []+ public private(set) var invalidIDs: Set<UUID> = []+ public var eventCount: Int { events.count }++ public init(events copies: [AssociationLedgerEvent], quarantinedIDs: Set<UUID> = []) {+ invalidIDs = quarantinedIDs+ for (id, rows) in Dictionary(grouping: copies, by: \.id) {+ guard !invalidIDs.contains(id), let first = rows.first, rows.allSatisfy({ $0.payload == first.payload }) else {+ invalidIDs.insert(id); continue+ }+ events[id] = first+ receipts[id] = Set(rows.compactMap(\.validation))+ if case .accept(let core) = first.payload { acceptances[id] = core }+ }+ var valid: [UUID: Bool] = [:]+ func validate(_ id: UUID, visiting: Set<UUID>) -> Bool {+ if let cached = valid[id] { return cached }+ guard !visiting.contains(id), let core = acceptances[id], !core.spellingKeys.isEmpty,+ core.spellingKeys.allSatisfy({ !$0.isEmpty && RecordNameKey.normalize($0) == $0 })+ else { return false }+ var next = visiting; next.insert(id)+ for rejectionID in core.reconsideredRejectionIDs {+ guard let event = events[rejectionID], case .reject(let rejection) = event.payload,+ rejection.pair == core.pair,+ !rejection.spellingKeys.isEmpty,+ rejection.spellingKeys.allSatisfy({ !$0.isEmpty && RecordNameKey.normalize($0) == $0 }),+ !Set(rejection.spellingKeys).isDisjoint(with: core.spellingKeys) else {+ valid[id] = false; return false+ }+ }+ if let rebind = core.rebind {+ guard !rebind.predecessorIDs.isEmpty,+ rebind.predecessorIDs.allSatisfy({ validate($0, visiting: next) }) else {+ valid[id] = false; return false+ }+ // This operation identity binds an explicit observed set. A+ // self-pair rebind would manufacture history rather than move it.+ guard rebind.predecessorIDs.allSatisfy({ parentID in+ guard let parent = acceptances[parentID] else { return false }+ return rebind.operation.permits(from: parent.pair, to: core.pair)+ }) else {+ valid[id] = false; return false+ }+ }+ valid[id] = true; return true+ }+ for id in acceptances.keys { if !validate(id, visiting: []) { invalidIDs.insert(id) } }+ var childrenByParent: [UUID: Set<AssociationPair>] = [:]+ for (id, core) in acceptances where !invalidIDs.contains(id) {+ for parent in core.rebind?.predecessorIDs ?? [] {+ childrenByParent[parent, default: []].insert(core.pair)+ }+ }+ // Opposing destinations quarantine both branches and hold their old+ // root inactive. Propagate through all historical descendants before+ // granting any acknowledgement authority or indexing current roots.+ let opposingParents = Set(childrenByParent.compactMap { $0.value.count > 1 ? $0.key : nil })+ consumed.formUnion(opposingParents)+ var changed = true+ while changed {+ changed = false+ for (id, core) in acceptances where !invalidIDs.contains(id) {+ let parents = core.rebind?.predecessorIDs ?? []+ if parents.contains(where: { opposingParents.contains($0) || invalidIDs.contains($0) }) {+ invalidIDs.insert(id); changed = true+ }+ }+ }+ for (id, core) in acceptances where !invalidIDs.contains(id) {+ rootsByPair[core.pair, default: []].insert(id)+ consumed.formUnion(core.rebind?.predecessorIDs ?? [])+ for rejectionID in core.reconsideredRejectionIDs {+ if case .reject(let rejection) = events[rejectionID]?.payload {+ for key in Set(rejection.spellingKeys).intersection(core.spellingKeys) {+ acknowledgements[rejectionID, default: [:]][key, default: []].insert(id)+ }+ }+ decisionsByEntry[core.pair.entryID, default: []].insert(id)+ }+ }+ for (id, event) in events {+ switch event.payload {+ case .reject(let rejection):+ guard !rejection.spellingKeys.isEmpty,+ rejection.spellingKeys.allSatisfy({ !$0.isEmpty && RecordNameKey.normalize($0) == $0 }) else {+ invalidIDs.insert(id); continue+ }+ rejectionsByPair[rejection.pair, default: []].append((id, rejection))+ decisionsByEntry[rejection.pair.entryID, default: []].insert(id)+ case .retire(let retirement):+ // A missing/conflicting sibling must never undo a known+ // removal. Hold each individually verified, correctly scoped+ // root; preserve the invalid batch for review as well.+ if retirement.acceptanceIDs.isEmpty { invalidIDs.insert(id) }+ for acceptanceID in retirement.acceptanceIDs {+ if acceptances[acceptanceID]?.pair == retirement.pair,+ !invalidIDs.contains(acceptanceID) {+ retired.insert(acceptanceID)+ } else { invalidIDs.insert(id) }+ }+ case .invalidate(let scope):+ barriers[scope, default: []].insert(id)+ if case .entry = scope {} else { barriersByWork[scope.workID, default: []].insert(id) }+ case .coverage(let coverage):+ coverageByEntry[coverage.entryID, default: []].append(coverage)+ default: break+ }+ }+ var scopes = Set(barriers.keys)+ for pair in rootsByPair.keys {+ scopes.insert(.entry(workID: pair.workID, entryID: pair.entryID))+ scopes.insert(.record(workID: pair.workID, kind: pair.kind, recordID: pair.recordID))+ }+ for scope in scopes { barrierDigests[scope] = makeBarrierDigest(scope) }+ pendingReviews = .init(events: copies, quarantinedIDs: invalidIDs)+ }++ public var pairs: Set<AssociationPair> { Set(rootsByPair.keys) }++ public func acceptance(_ id: UUID) -> AssociationAcceptance? {+ invalidIDs.contains(id) ? nil : acceptances[id]+ }+ public func isSuppressed(pair: AssociationPair, spellingKey: String) -> Bool {+ rejectionsByPair[pair, default: []].contains { id, rejection in+ rejection.spellingKeys.contains(spellingKey) && (acknowledgements[id]?[spellingKey]?.isEmpty ?? true)+ }+ }+ public func rejectionIDs(pair: AssociationPair, spellingKeys: [String]) -> [UUID] {+ AssociationDigest.ordered(rejectionsByPair[pair, default: []].compactMap { id, rejection in+ !Set(rejection.spellingKeys).isDisjoint(with: spellingKeys) ? id : nil+ })+ }+ private func makeBarrierDigest(_ scope: AssociationScope) -> String {+ let ids = barriers[scope, default: []].union(barriers[.work(scope.workID), default: []])+ return AssociationDigest.of("association/barriers/v1", AssociationDigest.scopeToken(scope)+ + AssociationDigest.ordered(Array(ids)).map(\.uuidString))+ }+ private func barrierDigest(_ scope: AssociationScope) -> String {+ barrierDigests[scope] ?? makeBarrierDigest(scope)+ }+ public func receipt(for current: AssociationCurrentPair) -> AssociationValidationReceipt {+ let evidence = Array(Set(current.evidence.filter {+ !$0.key.isEmpty && RecordNameKey.normalize($0.key) == $0.key+ && !isSuppressed(pair: current.pair, spellingKey: $0.key)+ })).sorted(by: AssociationEvidence.ordered)+ let relevant = rejectionIDs(pair: current.pair, spellingKeys: evidence.map(\.key))+ let decisions = relevant + relevant.flatMap { rejectionID in+ evidence.flatMap { Array(acknowledgements[rejectionID]?[$0.key] ?? []) }+ }+ return AssociationValidationReceipt(pair: current.pair,+ sourceFingerprint: current.sourceFingerprint, matchingFingerprint: current.matchingFingerprint,+ sourceBarrierDigest: barrierDigest(.entry(workID: current.pair.workID, entryID: current.pair.entryID)),+ recordBarrierDigest: barrierDigest(.record(workID: current.pair.workID, kind: current.pair.kind, recordID: current.pair.recordID)),+ decisionDigest: AssociationDigest.of("association/decisions/v1", AssociationDigest.pairToken(current.pair)+ + AssociationDigest.ordered(decisions).map(\.uuidString)), evidence: evidence)+ }+ func canRevalidateAcceptance(_ id: UUID, pair: AssociationPair) -> Bool {+ acceptances[id]?.pair == pair && !invalidIDs.contains(id) && !retired.contains(id) && !consumed.contains(id)+ }++ public func activeAcceptanceIDs(for current: AssociationCurrentPair) -> Set<UUID> {+ let expected = receipt(for: current)+ guard !expected.evidence.isEmpty else { return [] }+ return rootsByPair[current.pair, default: []].filter {+ !invalidIDs.contains($0) && !retired.contains($0) && !consumed.contains($0)+ && receipts[$0, default: []].contains(expected)+ }+ }+ public var spellingDecisions: [AssociationPair: [String: AssociationSpellingDecision]] {+ var result: [AssociationPair: [String: AssociationSpellingDecision]] = [:]+ for (pair, rejections) in rejectionsByPair {+ for key in Set(rejections.flatMap { $0.1.spellingKeys }) {+ result[pair, default: [:]][key] = .init(rejectionIDs: rejectionIDs(pair: pair, spellingKeys: [key]),+ suppressed: isSuppressed(pair: pair, spellingKey: key))+ }+ }+ return result+ }+ public func sourceGuard(workID: UUID, entryID: UUID, sourceFingerprint: String) -> String {+ AssociationDigest.of("association/source-guard/v1", [sourceFingerprint,+ barrierDigest(.entry(workID: workID, entryID: entryID))])+ }+ public func coverageBaseDigest(workID: UUID, entryID: UUID, sourceFingerprint: String,+ matchingDirectory: String) -> String {+ AssociationDigest.of("association/coverage/v1", [workID.uuidString, entryID.uuidString,+ sourceFingerprint, matchingDirectory,+ barrierDigest(.entry(workID: workID, entryID: entryID))]+ + AssociationDigest.ordered(Array(barriersByWork[workID, default: []]+ .union(decisionsByEntry[entryID, default: []]))).map(\.uuidString))+ }+ public func coverageDigest(workID: UUID, entryID: UUID, sourceFingerprint: String,+ matchingDirectory: String) -> String {+ let base = coverageBaseDigest(workID: workID, entryID: entryID, sourceFingerprint: sourceFingerprint,+ matchingDirectory: matchingDirectory)+ let markers = pendingReviews.markerIDs(workID: workID, entryID: entryID)+ return markers.isEmpty ? base : AssociationDigest.of("association/coverage-pending/v1",+ [base] + AssociationDigest.ordered(Array(markers)).map(\.uuidString))+ }+ public func hasCoverage(workID: UUID, entryID: UUID, digest: String) -> Bool {+ coverageByEntry[entryID, default: []].contains {+ $0.workID == workID && $0.eligibilityDigest == digest+ }+ }+}++public enum AssociationNoteOperation: String, Sendable, Codable {+ case text, clear, recover, rebind+}++/// Exact immutable authored version; parent consumption is historical, never+/// recomputed from today's membership. The raw version remains recoverable.+public struct AssociationNoteValue: Sendable, Equatable, Codable {+ public var id: UUID+ public var pair: AssociationPair+ public var attachmentAcceptanceIDs: [UUID]+ public var parentHeadIDs: [UUID]+ public var operation: AssociationNoteOperation+ public var text: String+ public var originalContext: String+ public var rebindAcceptanceID: UUID?+ public var authoredAt: Date+ public init(id: UUID = UUID(), pair: AssociationPair, attachmentAcceptanceIDs: [UUID],+ parentHeadIDs: [UUID] = [], operation: AssociationNoteOperation = .text,+ text: String = "", originalContext: String = "", rebindAcceptanceID: UUID? = nil,+ authoredAt: Date = .init(timeIntervalSince1970: 0)) {+ self.id = id; self.pair = pair+ self.attachmentAcceptanceIDs = AssociationDigest.ordered(attachmentAcceptanceIDs)+ self.parentHeadIDs = AssociationDigest.ordered(parentHeadIDs); self.operation = operation+ self.text = text; self.originalContext = originalContext+ self.rebindAcceptanceID = rebindAcceptanceID; self.authoredAt = authoredAt+ }+ public static func == (lhs: Self, rhs: Self) -> Bool {+ lhs.id == rhs.id && lhs.pair == rhs.pair+ && lhs.attachmentAcceptanceIDs == rhs.attachmentAcceptanceIDs+ && lhs.parentHeadIDs == rhs.parentHeadIDs && lhs.operation == rhs.operation+ && ExactScalarString(lhs.text) == ExactScalarString(rhs.text)+ && ExactScalarString(lhs.originalContext) == ExactScalarString(rhs.originalContext)+ && lhs.rebindAcceptanceID == rhs.rebindAcceptanceID && lhs.authoredAt.timeIntervalSinceReferenceDate.bitPattern == rhs.authoredAt.timeIntervalSinceReferenceDate.bitPattern+ }++}++public struct AssociationNoteFold: Sendable {+ public let rawNotes: [AssociationNoteValue]+ public let invalidIDs: Set<UUID>+ private let validHeads: [AssociationNoteValue]+ private let groupedHeads: [AssociationPair: [AssociationNoteValue]]+ public var allHeads: [AssociationNoteValue] { validHeads }+ public init(notes: [AssociationNoteValue], ledger: AssociationLedgerInventory, quarantinedIDs: Set<UUID> = []) {+ rawNotes = notes+ var unique: [UUID: AssociationNoteValue] = [:]+ var invalid = quarantinedIDs+ for (id, copies) in Dictionary(grouping: notes, by: \.id) {+ guard let first = copies.first, copies.allSatisfy({ $0 == first }) else {+ invalid.insert(id); continue+ }+ unique[id] = first+ }+ var memo: [UUID: Bool] = [:]+ func validate(_ id: UUID, visiting: Set<UUID>) -> Bool {+ if let value = memo[id] { return value }+ guard !visiting.contains(id), let note = unique[id], !invalid.contains(id),+ !note.attachmentAcceptanceIDs.isEmpty,+ note.attachmentAcceptanceIDs.allSatisfy({ ledger.acceptance($0)?.pair == note.pair }),+ note.operation != .clear || note.text.isEmpty else { return false }+ var next = visiting; next.insert(id)+ for parentID in note.parentHeadIDs {+ guard validate(parentID, visiting: next), let parent = unique[parentID] else {+ memo[id] = false; return false+ }+ if note.operation == .rebind {+ guard let rebindID = note.rebindAcceptanceID,+ let core = ledger.acceptance(rebindID), core.pair == note.pair,+ note.attachmentAcceptanceIDs.contains(rebindID),+ let predecessorIDs = core.rebind?.predecessorIDs,+ !Set(predecessorIDs).isDisjoint(with: parent.attachmentAcceptanceIDs),+ ExactScalarString(parent.text) == ExactScalarString(note.text),+ ExactScalarString(parent.originalContext) == ExactScalarString(note.originalContext) else { memo[id] = false; return false }+ } else {+ guard parent.pair == note.pair,+ note.operation == .recover || !Set(parent.attachmentAcceptanceIDs)+ .isDisjoint(with: note.attachmentAcceptanceIDs) else { memo[id] = false; return false }+ }+ }+ if note.operation == .rebind && note.parentHeadIDs.isEmpty { memo[id] = false; return false }+ memo[id] = true; return true+ }+ for id in unique.keys { if !validate(id, visiting: []) { invalid.insert(id) } }+ var consumed: Set<UUID> = []+ for (id, note) in unique where !invalid.contains(id) { consumed.formUnion(note.parentHeadIDs) }+ invalidIDs = invalid+ let heads = unique.values.filter { !invalid.contains($0.id) && !consumed.contains($0.id) }+ .sorted { $0.id.uuidString < $1.id.uuidString }+ validHeads = heads; groupedHeads = Dictionary(grouping: heads, by: \.pair)+ }+ public func heads(for pair: AssociationPair) -> [AssociationNoteValue] { groupedHeads[pair, default: []] }+ public func textHeads(for pair: AssociationPair, activeAcceptanceIDs: Set<UUID>) -> [AssociationNoteValue] {+ heads(for: pair).filter { $0.operation != .clear && !$0.text.isEmpty+ && !Set($0.attachmentAcceptanceIDs).isDisjoint(with: activeAcceptanceIDs) }+ }+ public func detachedTextHeads(activeAcceptanceIDs: Set<UUID>) -> [AssociationNoteValue] {+ validHeads.filter { $0.operation != .clear && !$0.text.isEmpty+ && Set($0.attachmentAcceptanceIDs).isDisjoint(with: activeAcceptanceIDs) }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationModels.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationModels.swiftnew file mode 100644index 00000000..f73d58cf--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationModels.swift@@ -0,0 +1,88 @@+import Foundation+import SwiftData++public typealias AssociationEvent = AsterismSchemaV21.AssociationEvent+public typealias PairNoteVersion = AsterismSchemaV21.PairNoteVersion++extension AsterismSchemaV21 {+ @Model public final class AssociationEvent {+ #Index<AssociationEvent>([\.id], [\.workID], [\.entryID], [\.recordID])+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var entryID: UUID?+ public var recordKindRaw: String?+ public var recordID: UUID?+ public var eventData: Data = Data()+ public var validationData: Data?+ public var recordedAt: Date = Date(timeIntervalSince1970: 0)+ public init() {}+ public init(event: AssociationLedgerEvent, recordedAt: Date) throws {+ id = event.id; workID = event.payload.workID; self.recordedAt = recordedAt+ entryID = event.payload.pair?.entryID+ recordKindRaw = event.payload.pair?.kind.rawValue+ recordID = event.payload.pair?.recordID+ switch event.payload {+ case .invalidate(.entry(_, let entry)): entryID = entry+ case .invalidate(.record(_, let kind, let record)):+ recordKindRaw = kind.rawValue; recordID = record+ case .coverage(let coverage): entryID = coverage.entryID+ case .pendingReview(let marker): entryID = marker.entryID+ case .reviewAcknowledgement(let acknowledgement): entryID = acknowledgement.entryID+ default: break+ }+ eventData = try JSONBlob.encode(event.payload)+ validationData = try event.validation.map { try JSONBlob.encode($0) }+ }+ }++ @Model public final class PairNoteVersion {+ #Index<PairNoteVersion>([\.id], [\.workID])+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var originPairData: Data = Data()+ public var attachmentAcceptIDsData: Data = Data()+ public var parentHeadIDsData: Data = Data()+ public var operationRaw: String = "text"+ public var text: String = ""+ public var originalContextData: Data = Data()+ public var authoredAt: Date = Date(timeIntervalSince1970: 0)+ public init() {}+ public init(note: AssociationNoteValue) throws {+ id = note.id; workID = note.pair.workID+ originPairData = try JSONBlob.encode(note.pair)+ attachmentAcceptIDsData = try JSONBlob.encode(note.attachmentAcceptanceIDs)+ parentHeadIDsData = try JSONBlob.encode(AssociationNoteParents(+ ids: note.parentHeadIDs, rebindAcceptanceID: note.rebindAcceptanceID))+ operationRaw = note.operation.rawValue; text = note.text+ originalContextData = try JSONBlob.encode(note.originalContext)+ authoredAt = note.authoredAt+ }+ }+}++/// The rebind reference is parent metadata, not another persisted relationship.+struct AssociationNoteParents: Codable {+ var ids: [UUID]+ var rebindAcceptanceID: UUID?+}++extension AssociationEvent {+ var ledgerValue: AssociationLedgerEvent? { AssociationRawEvent(self).value }+ convenience init(raw: AssociationRawEvent) {+ self.init()+ id = raw.id; workID = raw.workID; entryID = raw.entryID+ recordKindRaw = raw.recordKindRaw; recordID = raw.recordID+ eventData = raw.eventData; validationData = raw.validationData; recordedAt = raw.recordedAt+ }+}++extension PairNoteVersion {+ var noteValue: AssociationNoteValue? { AssociationRawNote(self).value }+ convenience init(raw: AssociationRawNote) {+ self.init()+ id = raw.id; workID = raw.workID; originPairData = raw.originPairData+ attachmentAcceptIDsData = raw.attachmentAcceptIDsData; parentHeadIDsData = raw.parentHeadIDsData+ operationRaw = raw.operationRaw; text = raw.text; originalContextData = raw.originalContextData+ authoredAt = raw.authoredAt+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationMutation.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationMutation.swiftnew file mode 100644index 00000000..7f58d651--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationMutation.swift@@ -0,0 +1,237 @@+import Foundation+import SwiftData++/// Captured once in an existing transaction, before its selected fields change.+/// Only roots active in this snapshot may receive a refreshed whole receipt.+struct AssociationMutation {+ let storage: AssociationStorageInventory+ let endpoints: AssociationEndpointInventory+ let pairs: Set<AssociationPair>+ let active: [AssociationPair: Set<UUID>]+ let entryIDs: Set<UUID>+ let records: Set<AssociationRecordAddress>+ let workIDs: Set<UUID>++ static func capture(context: ModelContext, workIDs: Set<UUID>, entryIDs: Set<UUID> = [],+ records: Set<AssociationRecordAddress> = [], allPairs: Bool = false) throws -> Self {+ // Current owner pointers can be missing after sync. Discover the known+ // selected scopes by indexed columns before loading their Work ledgers.+ // Full immutable-copy validation below still decides which pairs exist.+ var knownWorkIDs = workIDs+ let selectedEntries: [UUID?] = entryIDs.map { $0 }+ let selectedRecords: [UUID?] = Array(Set(records.map(\.id))).map { $0 }+ if !selectedEntries.isEmpty || !selectedRecords.isEmpty {+ let observed = try context.fetch(FetchDescriptor<AssociationEvent>(predicate: #Predicate {+ selectedEntries.contains($0.entryID) || selectedRecords.contains($0.recordID)+ }))+ knownWorkIDs.formUnion(observed.map(\.workID))+ }+ let storage = try AssociationStorageInventory.read(context: context, workIDs: knownWorkIDs)+ let pairs = storage.ledger.pairs.filter {+ allPairs || entryIDs.contains($0.entryID) || records.contains(.init(kind: $0.kind, id: $0.recordID))+ }+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: pairs,+ entryIDs: entryIDs, records: records)+ var active: [AssociationPair: Set<UUID>] = [:]+ for pair in pairs {+ if let current = endpoints.current(pair) {+ let ids = storage.ledger.activeAcceptanceIDs(for: current)+ if !ids.isEmpty { active[pair] = ids }+ }+ }+ return .init(storage: storage, endpoints: endpoints, pairs: pairs, active: active,+ entryIDs: entryIDs, records: records, workIDs: knownWorkIDs)+ }++ /// Typed descriptors come from the already verified identity operation.+ /// They map only observed roots; a later unknown loser is never guessed.+ @discardableResult+ func finish(context: ModelContext, timestamp: Date, rebinds: [AssociationRebindOperation] = [],+ additionalRecords: Set<AssociationRecordAddress> = [],+ additionalEvents: [AssociationLedgerEvent] = [],+ additionalQuarantinedIDs: Set<UUID> = [],+ invalidationExemptions: Set<AssociationScope> = []) throws+ -> (validationBasis: AssociationLedgerInventory, endpoints: AssociationEndpointInventory) {+ struct Path {+ var source: AssociationPair+ var destinations: [(AssociationPair, AssociationRebindOperation)]+ }+ var paths: [Path] = []+ for source in active.keys {+ var current = source, steps: [(AssociationPair, AssociationRebindOperation)] = []+ for operation in rebinds {+ if let destination = operation.destination(from: current) {+ steps.append((destination, operation)); current = destination+ }+ }+ if !steps.isEmpty { paths.append(.init(source: source, destinations: steps)) }+ }+ let allPairs = pairs.union(paths.flatMap { $0.destinations.map(\.0) })+ .union(additionalEvents.compactMap { $0.payload.pair })+ let after = try AssociationEndpointInventory.read(context: context, pairs: allPairs,+ entryIDs: entryIDs, records: records.union(additionalRecords))+ let changedEntries = entryIDs.filter { endpoints.sourceStates[$0] != after.sourceStates[$0] }+ let changedRecords = records.union(additionalRecords).filter { endpoints.targetStates[$0] != after.targetStates[$0] }+ let pairOwnersByEntry = Dictionary(grouping: pairs, by: \.entryID).mapValues { Set($0.map(\.workID)) }+ let pairOwnersByRecord = Dictionary(grouping: pairs) { AssociationRecordAddress(kind: $0.kind, id: $0.recordID) }+ .mapValues { Set($0.map(\.workID)) }+ var events = storage.rawEvents.compactMap(\.value) + additionalEvents+ var barriers: Set<AssociationScope> = []+ for id in changedEntries {+ let owners = endpoints.sourceOwnerIDs[id, default: []].union(after.sourceOwnerIDs[id, default: []])+ .union(pairOwnersByEntry[id, default: []])+ for owner in owners { barriers.insert(.entry(workID: owner, entryID: id)) }+ }+ for address in changedRecords {+ let owners = endpoints.targetOwnerIDs[address, default: []].union(after.targetOwnerIDs[address, default: []])+ .union(pairOwnersByRecord[address, default: []])+ for owner in owners { barriers.insert(.record(workID: owner, kind: address.kind, recordID: address.id)) }+ }+ for scope in barriers where !invalidationExemptions.contains(scope) {+ let event = AssociationLedgerEvent(payload: .invalidate(scope))+ context.insert(try AssociationEvent(event: event, recordedAt: timestamp)); events.append(event)+ }+ struct Plan {+ var source: AssociationPair+ var current: AssociationCurrentPair?+ var stages: [AssociationLedgerEvent]+ }+ var plans: [Plan] = []+ for path in paths {+ guard let final = path.destinations.last?.0,+ after.liveWorkIDs.contains(final.workID),+ let source = after.sources[final.entryID], source.workID == final.workID, source.eligible,+ let target = after.targets[.init(kind: final.kind, id: final.recordID)], target.workID == final.workID,+ let oldIDs = active[path.source] else { continue }+ let current = after.current(final)+ let historicalKeys = Array(Set(oldIDs.compactMap { storage.ledger.acceptance($0) }.flatMap(\.spellingKeys)))+ var predecessors = Array(oldIDs), stages: [AssociationLedgerEvent] = []+ for (destination, operation) in path.destinations {+ let event = AssociationLedgerEvent(payload: .accept(.init(pair: destination,+ spellingKeys: current?.evidence.map(\.key) ?? historicalKeys,+ rebind: .init(operation: operation, predecessorIDs: predecessors))))+ stages.append(event); events.append(event); predecessors = [event.id]+ }+ let retirement = AssociationLedgerEvent(payload: .retire(.init(pair: path.source, acceptanceIDs: Array(oldIDs))))+ events.append(retirement); context.insert(try AssociationEvent(event: retirement, recordedAt: timestamp))+ plans.append(.init(source: path.source, current: current, stages: stages))+ }+ // One historical fold for all verified operations/decisions. Receipt+ // generation does not require intermediate endpoints or receipt union.+ let ledger = AssociationLedgerInventory(events: events, quarantinedIDs: storage.quarantinedEventIDs.union(additionalQuarantinedIDs))+ let headsByPair = Dictionary(grouping: storage.notes.allHeads, by: \.pair)+ for plan in plans {+ guard let oldIDs = active[plan.source] else { continue }+ var heads = headsByPair[plan.source, default: []].filter {+ !Set($0.attachmentAcceptanceIDs).isDisjoint(with: oldIDs)+ }+ for (index, core) in plan.stages.enumerated() {+ var event = core+ if index == plan.stages.count - 1, let current = plan.current,+ !lostSupportedMention(from: plan.source, to: current.pair, after: after, ledger: ledger) {+ event.validation = ledger.receipt(for: current)+ }+ context.insert(try AssociationEvent(event: event, recordedAt: timestamp))+ guard let destination = event.payload.pair else { continue }+ heads = try heads.map { head in+ let note = AssociationNoteValue(pair: destination, attachmentAcceptanceIDs: [event.id],+ parentHeadIDs: [head.id], operation: .rebind, text: head.text,+ originalContext: head.originalContext, rebindAcceptanceID: event.id, authoredAt: timestamp)+ context.insert(try PairNoteVersion(note: note)); return note+ }+ }+ }+ let rebound = Set(plans.map(\.source))+ let rowsByID = Dictionary(grouping: storage.eventRows, by: \.id)+ for (pair, capturedIDs) in active where !rebound.contains(pair) {+ let ids = capturedIDs.filter { ledger.canRevalidateAcceptance($0, pair: pair) }+ guard !ids.isEmpty else { continue }+ if lostSupportedMention(from: pair, to: pair, after: after, ledger: ledger) {+ try retire(pair: pair, ids: ids, context: context, timestamp: timestamp)+ continue+ }+ if let current = after.current(pair) {+ let receipt = ledger.receipt(for: current)+ if receipt.evidence.isEmpty { try retire(pair: pair, ids: ids, context: context, timestamp: timestamp) }+ else {+ let bytes = try JSONBlob.encode(receipt)+ let beforeReceipt = endpoints.current(pair).map { storage.ledger.receipt(for: $0) }+ guard receipt != beforeReceipt else { continue }+ let alreadyCurrent = ledger.activeAcceptanceIDs(for: current)+ for id in ids.subtracting(alreadyCurrent) {+ for row in rowsByID[id, default: []]+ where row.validationData != bytes && row.ledgerValue?.validation == beforeReceipt {+ row.validationData = bytes+ }+ }+ }+ } else if definitelyRemoved(pair, after: after, changedEntries: changedEntries, changedRecords: changedRecords) {+ try retire(pair: pair, ids: ids, context: context, timestamp: timestamp)+ }+ }+ return (ledger, after)+ }++ /// Only an observed supported-to-unsupported transition is authority to+ /// retire a captured root or withhold a rebind's current receipt. Unchanged+ /// legacy literal receipts retain their exact evidence and authority.+ private func lostSupportedMention(from original: AssociationPair, to destination: AssociationPair,+ after: AssociationEndpointInventory, ledger: AssociationLedgerInventory) -> Bool {+ guard let beforeCurrent = endpoints.current(original),+ let beforeSource = endpoints.sources[original.entryID],+ let beforeTarget = endpoints.targets[.init(kind: original.kind, id: original.recordID)],+ after.liveWorkIDs.contains(destination.workID),+ let afterSource = after.sources[destination.entryID], afterSource.eligible,+ afterSource.workID == destination.workID,+ let afterTarget = after.targets[.init(kind: destination.kind, id: destination.recordID)],+ afterTarget.workID == destination.workID else { return false }+ let beforeAllowed = Set(storage.ledger.receipt(for: beforeCurrent).evidence.map(\.key))+ guard RecordMentionGrounding.maintenanceEvidence(names: beforeTarget.names, in: beforeSource.note)+ .contains(where: { beforeAllowed.contains($0.key) }) else { return false }+ let afterAllowed = after.current(destination).map { Set(ledger.receipt(for: $0).evidence.map(\.key)) } ?? []+ return !RecordMentionGrounding.maintenanceEvidence(names: afterTarget.names, in: afterSource.note)+ .contains(where: { afterAllowed.contains($0.key) })+ }++ private func definitelyRemoved(_ pair: AssociationPair, after: AssociationEndpointInventory,+ changedEntries: Set<UUID>, changedRecords: Set<AssociationRecordAddress>) -> Bool {+ let address = AssociationRecordAddress(kind: pair.kind, id: pair.recordID)+ if changedEntries.contains(pair.entryID) {+ if after.sourceStates[pair.entryID] == nil { return true }+ if let source = after.sources[pair.entryID], !source.eligible || source.workID != pair.workID { return true }+ }+ if changedRecords.contains(address) {+ if after.targetStates[address] == nil { return true }+ if let target = after.targets[address], target.workID != pair.workID { return true }+ }+ // Coherent present endpoints can prove literal support loss. Missing+ // or torn sync endpoints cannot prove deliberate removal.+ guard changedEntries.contains(pair.entryID) || changedRecords.contains(address),+ after.liveWorkIDs.contains(pair.workID), let source = after.sources[pair.entryID], source.eligible,+ source.workID == pair.workID, let target = after.targets[address], target.workID == pair.workID else { return false }+ return RecordMentionGrounding.evidence(names: target.names, in: source.note).isEmpty+ }+ private func retire(pair: AssociationPair, ids: Set<UUID>, context: ModelContext, timestamp: Date) throws {+ guard !ids.isEmpty else { return }+ context.insert(try AssociationEvent(event: .init(payload: .retire(.init(pair: pair, acceptanceIDs: Array(ids)))),+ recordedAt: timestamp))+ }+}++extension AssociationRebindOperation {+ func destination(from pair: AssociationPair) -> AssociationPair? {+ var result = pair+ switch self {+ case .entryMerge(let work, let source, let destination):+ guard pair.workID == work, pair.entryID == source else { return nil }; result.entryID = destination+ case .recordMerge(let work, let kind, let source, let destination):+ guard pair.workID == work, pair.kind == kind, pair.recordID == source else { return nil }; result.recordID = destination+ case .conversion(let work, let kind, let source, let destination):+ guard pair.workID == work, pair.kind == kind, pair.recordID == source else { return nil }+ result.kind = kind.other; result.recordID = destination+ case .workMerge(let source, let destination):+ guard pair.workID == source else { return nil }; result.workID = destination+ }+ return permits(from: pair, to: result) ? result : nil+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationNotesFixture.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationNotesFixture.swiftnew file mode 100644index 00000000..bc2ca4d4--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationNotesFixture.swift@@ -0,0 +1,131 @@+import Foundation+import SwiftData++#if DEBUG+extension LibraryRepository {+ public static let associationFixtureChapterID = UUID(uuidString: "24680000-0000-4000-8000-000000000002")!+ public static let associationFixtureRecoveryChapterID = UUID(uuidString: "24680000-0000-4000-8000-000000000003")!+ private static let associationFixtureWorkID = UUID(uuidString: "24680000-0000-4000-8000-000000000001")!+ private static let associationFixtureCharacterID = UUID(uuidString: "24680000-0000-4000-8000-000000000004")!+ private static let associationFixturePlaceID = UUID(uuidString: "24680000-0000-4000-8000-000000000005")!+ private static let associationFixtureMarker = "Completed isolated T-2468 journey fixture"++ /// DEBUG-only synthetic fixture. A completed known fixture may reopen, but+ /// an unrelated or partially seeded library is refused rather than changed.+ public func seedAssociationNotesFixture(verifyUnicodeAppend: Bool = false) async throws {+ let workID = Self.associationFixtureWorkID+ let firstID = Self.associationFixtureChapterID+ let secondID = Self.associationFixtureRecoveryChapterID+ let characterID = Self.associationFixtureCharacterID+ let placeID = Self.associationFixturePlaceID+ let wasEmpty = try await recordCounts().holdsNoReaderRecords+ guard !verifyUnicodeAppend || !wasEmpty else {+ throw LibraryRepositoryError.invalidInput(operation: "checking isolated association fixture",+ reason: "readback requires the completed synthetic journey library")+ }+ let completed = try await withLockedContext(mode: .exclusive, operation: "preparing isolated association fixture") { context in+ let works = try context.fetch(FetchDescriptor<Work>())+ let entries = try context.fetch(FetchDescriptor<Entry>())+ if !wasEmpty {+ guard works.count == 1, let work = works.first, work.id == workID,+ work.displayTitle == "The Link Book", work.genericNotes == Self.associationFixtureMarker,+ entries.contains(where: { $0.id == firstID }), entries.contains(where: { $0.id == secondID }) else {+ throw LibraryRepositoryError.invalidInput(operation: "preparing isolated association fixture",+ reason: "destination is not the completed synthetic journey library")+ }+ return true+ }+ let work = Work(id: workID, displayTitle: "The Link Book", timestamp: Date())+ let character = CharacterRecord(id: characterID, name: "Alice", nameKey: "alice", work: nil)+ let place = Place(id: placeID, name: "Harbor", nameKey: "harbor", workID: workID)+ context.insert(work); context.insert(character); context.insert(place); character.work = work+ for (id, title, designation) in [(firstID, "Arrival", "1"), (secondID, "Return", "2")] {+ let entry = Entry(id: id, captureTitle: title, captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: Date(), note: "Alice visits Harbor.")+ try entry.authorTarget(.init(kind: .chapter, title: title, designation: designation))+ context.insert(entry); entry.work = work; Self.applyManualAssignment(to: entry, at: entry.modifiedAt)+ }+ try saveStrategy.save(context)+ return false+ }+ if completed {+ if verifyUnicodeAppend {+ let pair = AssociationPair(workID: workID, entryID: secondID, kind: .place, recordID: placeID)+ let expected = "Cafe\u{301} seeded link note ASCII appended"+ guard let saved = try await associationNoteBasis(pair: pair), saved.heads.count == 1,+ Data(saved.heads[0].text.utf8) == Data(expected.utf8) else {+ throw LibraryRepositoryError.invalidInput(operation: "checking isolated association fixture",+ reason: "repository Unicode readback did not match the synthetic expected bytes")+ }+ }+ return+ }++ func accept(_ entryID: UUID, _ kind: RecordKind) async throws -> AssociationPair {+ let name = kind == .character ? "Alice" : "Harbor"+ let recordID = kind == .character ? characterID : placeID+ let result = try await commitDecision(.init(workID: workID, kind: kind, action: .accept,+ displayedKeys: [RecordNameKey.normalize(name)], displayedTargetID: recordID, proposedName: name,+ mentions: [.init(entryID: entryID, noteFingerprint: CharacterCoverageFingerprint.of("Alice visits Harbor."),+ spellingKeys: [RecordNameKey.normalize(name)])]))+ guard case .committed = result else {+ throw LibraryRepositoryError.invalidInput(operation: "preparing isolated association fixture", reason: "association acceptance refused")+ }+ return .init(workID: workID, entryID: entryID, kind: kind, recordID: recordID)+ }+ let first = try await accept(firstID, .character)+ _ = try await accept(firstID, .place)+ let recovery = try await accept(secondID, .character)+ guard let firstBasis = try await associationNoteBasis(pair: first),+ let recoveryBasis = try await associationNoteBasis(pair: recovery),+ try await saveAssociationNote(basis: firstBasis, text: "Saved arrival note") == .committed,+ try await saveAssociationNote(basis: recoveryBasis, text: "Earlier chapter link note") == .committed else {+ throw LibraryRepositoryError.invalidInput(operation: "preparing isolated association fixture", reason: "note seed refused")+ }+ for note in ["Nobody visits.", "Alice visits Harbor."] {+ let current = try await entry(id: secondID)+ guard try await updateEntry(id: secondID, basis: .init(entry: current), note: note, rating: nil) == .committed else {+ throw LibraryRepositoryError.invalidInput(operation: "preparing isolated association fixture", reason: "chapter seed edit refused")+ }+ }+ _ = try await accept(secondID, .character)+ guard let currentBasis = try await associationNoteBasis(pair: recovery),+ try await saveAssociationNote(basis: currentBasis, text: "Current destination note") == .committed else {+ throw LibraryRepositoryError.invalidInput(operation: "preparing isolated association fixture", reason: "destination note seed refused")+ }+ let unicodePair = try await accept(secondID, .place)+ guard let unicodeBasis = try await associationNoteBasis(pair: unicodePair),+ try await saveAssociationNote(basis: unicodeBasis, text: "Cafe\u{301} seeded link note") == .committed else {+ throw LibraryRepositoryError.invalidInput(operation: "preparing isolated association fixture", reason: "Unicode note seed refused")+ }+ let placePair = AssociationPair(workID: workID, entryID: firstID, kind: .place, recordID: placeID)+ guard let placeBasis = try await associationNoteBasis(pair: placePair) else {+ throw LibraryRepositoryError.invalidInput(operation: "preparing isolated association fixture", reason: "place basis missing")+ }+ try await withLockedContext(mode: .exclusive, operation: "completing isolated association fixture") { context in+ // Two concurrent authored heads: this tolerated arrival is deliberately+ // unavailable through sequential Save, which consumes observed heads.+ for text in ["Harbor note from device A", "Harbor note from device B"] {+ context.insert(try PairNoteVersion(note: .init(pair: placePair,+ attachmentAcceptanceIDs: Array(placeBasis.acceptanceIDs), text: text,+ originalContext: placeBasis.originalContext)))+ }+ let missing = AssociationPair(workID: workID, entryID: UUID(), kind: .character, recordID: UUID())+ context.insert(try PairNoteVersion(note: .init(pair: missing, attachmentAcceptanceIDs: [UUID()],+ text: "Missing endpoint note", originalContext: "Removed chapter: original context")))+ let raw = PairNoteVersion()+ raw.workID = UUID(); raw.originPairData = Data([0xff]); raw.attachmentAcceptIDsData = Data([0xff])+ raw.parentHeadIDsData = Data([0xff]); raw.operationRaw = "malformed"+ raw.text = "Cafe\u{301} raw text remains copyable"+ raw.originalContextData = try JSONBlob.encode("Missing chapter: preserved original context")+ context.insert(raw)+ let work = try context.fetch(FetchDescriptor<Work>()).first { $0.id == workID }+ guard let work else {+ throw LibraryRepositoryError.invalidInput(operation: "completing isolated association fixture", reason: "synthetic Work missing")+ }+ work.genericNotes = Self.associationFixtureMarker+ try saveStrategy.save(context)+ }+ }+}+#endif
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationPendingReviews.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationPendingReviews.swiftnew file mode 100644index 00000000..662bd1ae--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationPendingReviews.swift@@ -0,0 +1,148 @@+import Foundation++/// Coverage-only identity. It never routes a saved link or carries authored text.+public struct AssociationReviewKey: Sendable, Equatable, Hashable, Codable {+ public var kind: RecordKind+ public var nameKey: String+ public init(kind: RecordKind, nameKey: String) { self.kind = kind; self.nameKey = nameKey }+}+public struct AssociationPendingReviewItem: Sendable, Equatable, Hashable, Codable {+ public var key: AssociationReviewKey+ public var targetID: UUID?+ public var spellingKeys: [String]+ public init(key: AssociationReviewKey, targetID: UUID?, spellingKeys: [String]) {+ self.key = key; self.targetID = targetID; self.spellingKeys = Array(Set(spellingKeys)).sorted()+ }+}+public struct AssociationPendingReview: Sendable, Equatable, Codable {+ public var workID: UUID+ public var entryID: UUID+ public var sourceGuard: String+ public var items: [AssociationPendingReviewItem]+ public init(workID: UUID, entryID: UUID, sourceGuard: String, items: [AssociationPendingReviewItem]) {+ self.workID = workID; self.entryID = entryID; self.sourceGuard = sourceGuard+ let combined = Dictionary(grouping: items, by: \.key).values.flatMap { values -> [AssociationPendingReviewItem] in+ guard let first = values.first, Set(values.map(\.targetID)).count == 1 else { return values }+ return [.init(key: first.key, targetID: first.targetID, spellingKeys: values.flatMap(\.spellingKeys))]+ }+ self.items = combined.sorted { [$0.key.kind.rawValue, $0.key.nameKey, $0.targetID?.uuidString ?? "", $0.spellingKeys.joined(separator: "\u{0}")]+ .lexicographicallyPrecedes([$1.key.kind.rawValue, $1.key.nameKey, $1.targetID?.uuidString ?? "", $1.spellingKeys.joined(separator: "\u{0}")]) }+ }+}+public struct AssociationReviewReference: Sendable, Equatable, Hashable, Codable {+ public var markerID: UUID+ public var key: AssociationReviewKey+ public init(markerID: UUID, key: AssociationReviewKey) { self.markerID = markerID; self.key = key }+}+public enum AssociationReviewOutcome: Sendable, Equatable, Codable {+ case kept(kind: RecordKind, recordID: UUID)+ case skipped+}+public struct AssociationReviewAcknowledgement: Sendable, Equatable, Codable {+ public var workID: UUID+ public var entryID: UUID+ public var references: [AssociationReviewReference]+ public var outcome: AssociationReviewOutcome?+ public init(workID: UUID, entryID: UUID, references: [AssociationReviewReference], outcome: AssociationReviewOutcome? = nil) {+ self.outcome = outcome+ self.workID = workID; self.entryID = entryID+ self.references = Array(Set(references)).sorted {+ [$0.markerID.uuidString, $0.key.kind.rawValue, $0.key.nameKey]+ .lexicographicallyPrecedes([$1.markerID.uuidString, $1.key.kind.rawValue, $1.key.nameKey])+ }+ }+}+public struct AssociationPendingReviewRequest: Sendable, Equatable {+ public var markerID: UUID+ public var marker: AssociationPendingReview+ public var originalEligibilityBase: String?+ public var originalEligibilityDigest: String?+ public init(markerID: UUID = UUID(), marker: AssociationPendingReview,+ originalEligibilityBase: String?, originalEligibilityDigest: String?) {+ self.markerID = markerID; self.marker = marker+ self.originalEligibilityBase = originalEligibilityBase; self.originalEligibilityDigest = originalEligibilityDigest+ }+}+public struct AssociationPendingReviewResult: Sendable, Equatable {+ public var workID: UUID+ public var entryID: UUID+ public var completionDigest: String?+ public var references: [AssociationReviewReference]+ public init(workID: UUID, entryID: UUID, completionDigest: String?, references: [AssociationReviewReference]) {+ self.workID = workID; self.entryID = entryID; self.completionDigest = completionDigest; self.references = references+ }+}++struct AssociationReviewSource: Hashable, Sendable {+ var workID: UUID+ var entryID: UUID+}++struct AssociationReviewWitnessIdentity: Hashable, Sendable {+ var sourceGuard: String+ var item: AssociationPendingReviewItem+}+struct AssociationReviewKeptTarget: Hashable, Sendable {+ var kind: RecordKind+ var recordID: UUID+}++/// One operation-local fold of minimal pending keys and explicit decisions.+/// Conflicting marker copies hold every observed scope; they cannot resurrect+/// an earlier completion by disappearing from the valid event dictionary.+public struct AssociationPendingReviewInventory: Sendable {+ public private(set) var markers: [UUID: [AssociationPendingReview]] = [:]+ public private(set) var invalidIDs: Set<UUID> = []+ var markersBySource: [AssociationReviewSource: [(UUID, AssociationPendingReview)]] = [:]+ private var idsBySource: [AssociationReviewSource: Set<UUID>] = [:]+ var keepWitnesses: [AssociationReviewSource: [AssociationReviewWitnessIdentity: Set<AssociationReviewKeptTarget>]] = [:]+ private var acknowledged: Set<AssociationReviewReference> = []+ init(events copies: [AssociationLedgerEvent], quarantinedIDs: Set<UUID> = []) {+ let grouped = Dictionary(grouping: copies, by: \.id)+ invalidIDs = quarantinedIDs+ for (id, rows) in grouped {+ if let first = rows.first, !rows.allSatisfy({ $0.payload == first.payload }) { invalidIDs.insert(id) }+ for row in rows {+ guard case .pendingReview(let marker) = row.payload else { continue }+ if !markers[id, default: []].contains(marker) { markers[id, default: []].append(marker) }+ if marker.sourceGuard.isEmpty || marker.items.isEmpty || Set(marker.items.map(\.key)).count != marker.items.count || marker.items.contains(where: {+ $0.key.nameKey.isEmpty || RecordNameKey.normalize($0.key.nameKey) != $0.key.nameKey+ || $0.spellingKeys.isEmpty || $0.spellingKeys.contains { $0.isEmpty || RecordNameKey.normalize($0) != $0 }+ }) { invalidIDs.insert(id) }+ }+ }+ for (id, values) in markers {+ for marker in values {+ let source = AssociationReviewSource(workID: marker.workID, entryID: marker.entryID)+ markersBySource[source, default: []].append((id, marker))+ idsBySource[source, default: []].insert(id)+ }+ }+ for (id, rows) in grouped where !invalidIDs.contains(id) {+ guard let first = rows.first, case .reviewAcknowledgement(let acknowledgement) = first.payload else { continue }+ guard !acknowledgement.references.isEmpty,+ acknowledgement.references.allSatisfy({ reference in+ !invalidIDs.contains(reference.markerID) && markers[reference.markerID]?.contains(where: {+ $0.workID == acknowledgement.workID && $0.entryID == acknowledgement.entryID+ && $0.items.contains(where: { $0.key == reference.key })+ }) == true+ }) else { invalidIDs.insert(id); continue }+ acknowledged.formUnion(acknowledgement.references)+ if let outcome = acknowledgement.outcome, case .kept(let kind, let recordID) = outcome {+ let source = AssociationReviewSource(workID: acknowledgement.workID, entryID: acknowledgement.entryID)+ for reference in acknowledgement.references {+ for marker in markers[reference.markerID, default: []] {+ for item in marker.items where item.key == reference.key && item.key.kind == kind && (item.targetID == nil || item.targetID == recordID) {+ let identity = AssociationReviewWitnessIdentity(sourceGuard: marker.sourceGuard, item: item)+ keepWitnesses[source, default: [:]][identity, default: []].insert(.init(kind: kind, recordID: recordID))+ }+ }+ }+ }+ }+ }+ public func markerIDs(workID: UUID, entryID: UUID) -> Set<UUID> {+ idsBySource[.init(workID: workID, entryID: entryID), default: []]+ }+ public func isAcknowledged(_ reference: AssociationReviewReference) -> Bool { acknowledged.contains(reference) }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationRawRecords.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationRawRecords.swiftnew file mode 100644index 00000000..aa5301d9--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationRawRecords.swift@@ -0,0 +1,167 @@+import Foundation++/// Format20 raw feature timestamps are decimal UInt64 IEEE754 bit-pattern+/// strings of Date.timeIntervalSinceReferenceDate. This local representation+/// preserves historical precision without changing released base archive dates.+private struct AssociationRawInstant: Codable {+ var value: Date+ init(_ value: Date) { self.value = value }+ init(from decoder: any Decoder) throws {+ let container = try decoder.singleValueContainer()+ let string = try container.decode(String.self)+ guard let bits = UInt64(string) else {+ throw DecodingError.dataCorruptedError(in: container, debugDescription: "invalid raw timestamp bit pattern")+ }+ value = Date(timeIntervalSinceReferenceDate: Double(bitPattern: bits))+ }+ func encode(to encoder: any Encoder) throws {+ var container = encoder.singleValueContainer()+ try container.encode(String(value.timeIntervalSinceReferenceDate.bitPattern))+ }+}+++/// Raw archive/recovery values retain malformed metadata and whole receipt+/// variants. Decoding failure must not turn authored content into an empty list.+public struct AssociationRawEvent: Sendable, Equatable, Codable {+ public var id: UUID+ public var workID: UUID+ public var entryID: UUID?+ public var recordKindRaw: String?+ public var recordID: UUID?+ public var eventData: Data+ public var validationData: Data?+ public var recordedAt: Date+ private enum CodingKeys: String, CodingKey { case id, workID, entryID, recordKindRaw, recordID, eventData, validationData, recordedAt }+ public init(from decoder: any Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ id = try container.decode(UUID.self, forKey: .id)+ workID = try container.decode(UUID.self, forKey: .workID)+ entryID = try container.decodeIfPresent(UUID.self, forKey: .entryID)+ recordKindRaw = try container.decodeIfPresent(String.self, forKey: .recordKindRaw)+ recordID = try container.decodeIfPresent(UUID.self, forKey: .recordID)+ eventData = try container.decode(Data.self, forKey: .eventData)+ validationData = try container.decodeIfPresent(Data.self, forKey: .validationData)+ recordedAt = try container.decode(AssociationRawInstant.self, forKey: .recordedAt).value+ }+ public func encode(to encoder: any Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(id, forKey: .id)+ try container.encode(workID, forKey: .workID)+ try container.encodeIfPresent(entryID, forKey: .entryID)+ try container.encodeIfPresent(recordKindRaw, forKey: .recordKindRaw)+ try container.encodeIfPresent(recordID, forKey: .recordID)+ try container.encode(eventData, forKey: .eventData)+ try container.encodeIfPresent(validationData, forKey: .validationData)+ try container.encode(AssociationRawInstant(recordedAt), forKey: .recordedAt)+ }+ init(_ row: AssociationEvent) {+ id = row.id; workID = row.workID; entryID = row.entryID+ recordKindRaw = row.recordKindRaw; recordID = row.recordID+ eventData = row.eventData; validationData = row.validationData; recordedAt = row.recordedAt+ }+ var value: AssociationLedgerEvent? {+ guard let payload = try? JSONBlob.decode(AssociationEventPayload.self, from: eventData) else { return nil }+ var expectedEntry = payload.pair?.entryID+ var expectedKind = payload.pair?.kind.rawValue+ var expectedRecord = payload.pair?.recordID+ switch payload {+ case .invalidate(.entry(_, let entry)): expectedEntry = entry+ case .invalidate(.record(_, let kind, let record)): expectedKind = kind.rawValue; expectedRecord = record+ case .coverage(let coverage): expectedEntry = coverage.entryID+ case .pendingReview(let marker): expectedEntry = marker.entryID+ case .reviewAcknowledgement(let acknowledgement): expectedEntry = acknowledgement.entryID+ default: break+ }+ guard workID == payload.workID, entryID == expectedEntry,+ recordKindRaw == expectedKind, recordID == expectedRecord else { return nil }+ let receipt = validationData.flatMap { try? JSONBlob.decode(AssociationValidationReceipt.self, from: $0) }+ return AssociationLedgerEvent(id: id, payload: payload, validation: receipt)+ }+ public static func == (lhs: Self, rhs: Self) -> Bool {+ lhs.id == rhs.id && lhs.workID == rhs.workID && lhs.entryID == rhs.entryID+ && lhs.recordKindRaw.map(ExactScalarString.init) == rhs.recordKindRaw.map(ExactScalarString.init) && lhs.recordID == rhs.recordID+ && lhs.eventData == rhs.eventData && lhs.validationData == rhs.validationData+ && lhs.recordedAt.timeIntervalSinceReferenceDate.bitPattern == rhs.recordedAt.timeIntervalSinceReferenceDate.bitPattern+ }++}++public struct AssociationRawNote: Sendable, Equatable, Codable {+ public var id: UUID+ public var workID: UUID+ public var originPairData: Data+ public var attachmentAcceptIDsData: Data+ public var parentHeadIDsData: Data+ public var operationRaw: String+ public var text: String+ public var originalContextData: Data+ public var authoredAt: Date+ private enum CodingKeys: String, CodingKey { case id, workID, originPairData, attachmentAcceptIDsData, parentHeadIDsData, operationRaw, text, originalContextData, authoredAt }+ public init(from decoder: any Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ id = try container.decode(UUID.self, forKey: .id)+ workID = try container.decode(UUID.self, forKey: .workID)+ originPairData = try container.decode(Data.self, forKey: .originPairData)+ attachmentAcceptIDsData = try container.decode(Data.self, forKey: .attachmentAcceptIDsData)+ parentHeadIDsData = try container.decode(Data.self, forKey: .parentHeadIDsData)+ operationRaw = try container.decode(String.self, forKey: .operationRaw)+ text = try container.decode(String.self, forKey: .text)+ originalContextData = try container.decode(Data.self, forKey: .originalContextData)+ authoredAt = try container.decode(AssociationRawInstant.self, forKey: .authoredAt).value+ }+ public func encode(to encoder: any Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(id, forKey: .id)+ try container.encode(workID, forKey: .workID)+ try container.encode(originPairData, forKey: .originPairData)+ try container.encode(attachmentAcceptIDsData, forKey: .attachmentAcceptIDsData)+ try container.encode(parentHeadIDsData, forKey: .parentHeadIDsData)+ try container.encode(operationRaw, forKey: .operationRaw)+ try container.encode(text, forKey: .text)+ try container.encode(originalContextData, forKey: .originalContextData)+ try container.encode(AssociationRawInstant(authoredAt), forKey: .authoredAt)+ }+ init(_ row: PairNoteVersion) {+ id = row.id; workID = row.workID; originPairData = row.originPairData+ attachmentAcceptIDsData = row.attachmentAcceptIDsData; parentHeadIDsData = row.parentHeadIDsData+ operationRaw = row.operationRaw; text = row.text+ originalContextData = row.originalContextData; authoredAt = row.authoredAt+ }+ var value: AssociationNoteValue? {+ guard let pair = try? JSONBlob.decode(AssociationPair.self, from: originPairData),+ pair.workID == workID,+ let attachments = try? JSONBlob.decode([UUID].self, from: attachmentAcceptIDsData),+ let parents = try? JSONBlob.decode(AssociationNoteParents.self, from: parentHeadIDsData),+ let operation = AssociationNoteOperation(rawValue: operationRaw),+ let context = try? JSONBlob.decode(String.self, from: originalContextData) else { return nil }+ return AssociationNoteValue(id: id, pair: pair, attachmentAcceptanceIDs: attachments,+ parentHeadIDs: parents.ids, operation: operation, text: text, originalContext: context,+ rebindAcceptanceID: parents.rebindAcceptanceID, authoredAt: authoredAt)+ }+ public static func == (lhs: Self, rhs: Self) -> Bool {+ lhs.id == rhs.id && lhs.workID == rhs.workID && lhs.originPairData == rhs.originPairData+ && lhs.attachmentAcceptIDsData == rhs.attachmentAcceptIDsData+ && lhs.parentHeadIDsData == rhs.parentHeadIDsData && ExactScalarString(lhs.operationRaw) == ExactScalarString(rhs.operationRaw)+ && ExactScalarString(lhs.text) == ExactScalarString(rhs.text)+ && lhs.originalContextData == rhs.originalContextData+ && lhs.authoredAt.timeIntervalSinceReferenceDate.bitPattern == rhs.authoredAt.timeIntervalSinceReferenceDate.bitPattern+ }+}++extension AssociationRawEvent {+ var variantIdentity: String {+ AssociationDigest.of("association/raw-event-variant/v1", [id.uuidString, workID.uuidString,+ entryID?.uuidString ?? "", recordKindRaw == nil ? "nil" : "value", recordKindRaw ?? "",+ recordID?.uuidString ?? "", eventData.base64EncodedString(), validationData == nil ? "nil" : "value",+ validationData?.base64EncodedString() ?? "", String(recordedAt.timeIntervalSinceReferenceDate.bitPattern)])+ }+}+extension AssociationRawNote {+ var variantIdentity: String {+ AssociationDigest.of("association/raw-note-variant/v1", [id.uuidString, workID.uuidString,+ originPairData.base64EncodedString(), attachmentAcceptIDsData.base64EncodedString(),+ parentHeadIDsData.base64EncodedString(), operationRaw, text, originalContextData.base64EncodedString(),+ String(authoredAt.timeIntervalSinceReferenceDate.bitPattern)])+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationSnapshots.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationSnapshots.swiftnew file mode 100644index 00000000..df7a52af--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationSnapshots.swift@@ -0,0 +1,97 @@+import Foundation++public struct AssociationMentionDecision: Sendable, Equatable {+ public var entryID: UUID+ public var noteFingerprint: String+ public var sourceGuard: String?+ public var spellingKeys: [String]+ public var observedRejectionIDs: [UUID]+ public init(entryID: UUID, noteFingerprint: String, spellingKeys: [String], observedRejectionIDs: [UUID] = [], sourceGuard: String? = nil) {+ self.sourceGuard = sourceGuard+ self.entryID = entryID; self.noteFingerprint = noteFingerprint+ self.spellingKeys = Array(Set(spellingKeys)).sorted()+ self.observedRejectionIDs = AssociationDigest.ordered(observedRejectionIDs)+ }+}++public struct AssociationSpellingDecision: Sendable, Equatable {+ public var rejectionIDs: [UUID]+ public var suppressed: Bool+ public init(rejectionIDs: [UUID], suppressed: Bool) {+ self.rejectionIDs = AssociationDigest.ordered(rejectionIDs); self.suppressed = suppressed+ }+}++/// The existing extraction lane receives only mention eligibility/decisions.+/// Authored link-note text never enters this value or a model request.+public struct AssociationMentionIndex: Sendable, Equatable {+ public var workID: UUID?+ public var eligibleEntries: Set<UUID>+ public var eligibilityByEntry: [UUID: String]+ public var sourceGuards: [UUID: String]+ public var coverageBases: [UUID: String]+ public var pendingReviewReferences: [UUID: [AssociationReviewReference]]+ public var coherentRecordIDs: [RecordKind: Set<UUID>]?+ public var activePairs: Set<AssociationPair>+ public var decisions: [AssociationPair: [String: AssociationSpellingDecision]]+ public init(workID: UUID?, eligibleEntries: Set<UUID>, eligibilityByEntry: [UUID: String],+ activePairs: Set<AssociationPair>, decisions: [AssociationPair: [String: AssociationSpellingDecision]], sourceGuards: [UUID: String] = [:], coherentRecordIDs: [RecordKind: Set<UUID>]? = nil, coverageBases: [UUID: String] = [:], pendingReviewReferences: [UUID: [AssociationReviewReference]] = [:]) {+ self.workID = workID; self.eligibleEntries = eligibleEntries; self.eligibilityByEntry = eligibilityByEntry+ self.sourceGuards = sourceGuards+ self.coverageBases = coverageBases; self.pendingReviewReferences = pendingReviewReferences+ self.coherentRecordIDs = coherentRecordIDs+ self.activePairs = activePairs; self.decisions = decisions+ }+ public static let empty = Self(workID: nil, eligibleEntries: [], eligibilityByEntry: [:], activePairs: [], decisions: [:])+ public func canLink(kind: RecordKind, recordID: UUID) -> Bool {+ coherentRecordIDs.map { $0[kind, default: []].contains(recordID) } ?? true+ }+ /// Refresh only the newly displayed target's narrow decision basis.+ /// Automatic review never acknowledges a newly suppressed spelling.+ public func refreshed(_ mention: AssociationMentionDecision, kind: RecordKind,+ recordID: UUID?, reconsider: Bool) -> AssociationMentionDecision? {+ var result = mention+ guard let recordID else { result.observedRejectionIDs = []; return result }+ guard canLink(kind: kind, recordID: recordID) else { return nil }+ if !reconsider {+ result.spellingKeys = mention.spellingKeys.filter {+ !isSuppressed(entryID: mention.entryID, kind: kind, recordID: recordID, spellingKey: $0)+ }+ }+ guard !result.spellingKeys.isEmpty else { return nil }+ result.observedRejectionIDs = rejectionIDs(entryID: mention.entryID, kind: kind,+ recordID: recordID, spellingKeys: result.spellingKeys)+ return result+ }+ public func pair(entryID: UUID, kind: RecordKind, recordID: UUID) -> AssociationPair? {+ workID.map { .init(workID: $0, entryID: entryID, kind: kind, recordID: recordID) }+ }+ public func isSuppressed(entryID: UUID, kind: RecordKind, recordID: UUID, spellingKey: String) -> Bool {+ guard let pair = pair(entryID: entryID, kind: kind, recordID: recordID) else { return false }+ return decisions[pair]?[spellingKey]?.suppressed ?? false+ }+ public func rejectionIDs(entryID: UUID, kind: RecordKind, recordID: UUID, spellingKeys: [String]) -> [UUID] {+ guard let pair = pair(entryID: entryID, kind: kind, recordID: recordID) else { return [] }+ return AssociationDigest.ordered(spellingKeys.flatMap { decisions[pair]?[$0]?.rejectionIDs ?? [] })+ }+}++public struct ChapterAssociationSnapshot: Sendable, Equatable, Identifiable {+ public var id: AssociationPair { pair }+ public var pair: AssociationPair+ public var recordName: String+ public var chapterTitle: String+ public var evidence: [AssociationEvidence]+ public var activeAcceptanceIDs: Set<UUID>+ public var validationReceipt: AssociationValidationReceipt?+ public var noteHeads: [AssociationNoteValue]+ public var rawNotes: [AssociationRawNote]+ public init(pair: AssociationPair, recordName: String, chapterTitle: String,+ evidence: [AssociationEvidence], activeAcceptanceIDs: Set<UUID>,+ validationReceipt: AssociationValidationReceipt?, noteHeads: [AssociationNoteValue] = [],+ rawNotes: [AssociationRawNote] = []) {+ self.pair = pair; self.recordName = recordName; self.chapterTitle = chapterTitle+ self.evidence = evidence; self.activeAcceptanceIDs = activeAcceptanceIDs+ self.validationReceipt = validationReceipt; self.noteHeads = noteHeads; self.rawNotes = rawNotes+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AssociationStorage.swift b/Packages/AsterismCore/Sources/AsterismCore/AssociationStorage.swiftnew file mode 100644index 00000000..2d45bcfc--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AssociationStorage.swift@@ -0,0 +1,108 @@+import Foundation+import SwiftData++/// One selected Work ledger inventory, not one scan per pair. Current endpoint+/// reads remain selected by application IDs and include all physical copies.+/// Cross-Work histories are loaded only through encountered parent scopes;+/// endpoint coherence is checked globally before any receipt can be active.+struct AssociationStorageInventory {+ let eventRows: [AssociationEvent]+ let noteRows: [PairNoteVersion]+ let rawEvents: [AssociationRawEvent]+ let rawNotes: [AssociationRawNote]+ let quarantinedEventIDs: Set<UUID>+ let ledger: AssociationLedgerInventory+ let notes: AssociationNoteFold+ let eventFetchCount: Int+ let noteFetchCount: Int++ static func read(context: ModelContext, workIDs: Set<UUID>, includeNotes: Bool = true,+ eventIDs seedEvents: Set<UUID> = [], noteIDs seedNotes: Set<UUID> = []) throws -> Self {+ guard !workIDs.isEmpty || !seedEvents.isEmpty || !seedNotes.isEmpty else {+ return Self(eventRows: [], noteRows: [], rawEvents: [], rawNotes: [],+ quarantinedEventIDs: [], ledger: .init(events: []), notes: .init(notes: [], ledger: .init(events: [])),+ eventFetchCount: 0, noteFetchCount: 0)+ }+ var selectedWorks = workIDs+ var readWorks: Set<UUID> = []+ var checkedEventIDs: Set<UUID> = []+ var checkedNoteIDs: Set<UUID> = []+ var eventRows: [ObjectIdentifier: AssociationEvent] = [:]+ var noteRows: [ObjectIdentifier: PairNoteVersion] = [:]+ var eventFetchCount = 0, noteFetchCount = 0+ var processedEvents: Set<ObjectIdentifier> = []+ var processedNotes: Set<ObjectIdentifier> = []+ var rawEventsByObject: [ObjectIdentifier: AssociationRawEvent] = [:]+ var rawNotesByObject: [ObjectIdentifier: AssociationRawNote] = [:]+ var values: [ObjectIdentifier: AssociationLedgerEvent] = [:]+ var noteValues: [ObjectIdentifier: AssociationNoteValue] = [:]+ var badEvents: Set<UUID> = [], badNotes: Set<UUID> = []+ var requiredEvents = seedEvents+ var requiredNotes = seedNotes+ while true {+ let works = Array(selectedWorks.subtracting(readWorks))+ if !works.isEmpty {+ readWorks.formUnion(works)+ eventFetchCount += 1+ for row in try context.fetch(FetchDescriptor<AssociationEvent>(predicate: #Predicate { works.contains($0.workID) })) {+ eventRows[ObjectIdentifier(row)] = row; requiredEvents.insert(row.id)+ }+ if includeNotes {+ noteFetchCount += 1+ for row in try context.fetch(FetchDescriptor<PairNoteVersion>(predicate: #Predicate { works.contains($0.workID) })) {+ noteRows[ObjectIdentifier(row)] = row; requiredNotes.insert(row.id)+ }+ }+ }+ let noteIDs = Array(requiredNotes.subtracting(checkedNoteIDs))+ if !noteIDs.isEmpty {+ checkedNoteIDs.formUnion(noteIDs)+ noteFetchCount += 1+ for row in try context.fetch(FetchDescriptor<PairNoteVersion>(predicate: #Predicate { noteIDs.contains($0.id) })) {+ noteRows[ObjectIdentifier(row)] = row+ }+ }+ // Batch all physical copies before deriving parent closure. A bad+ // off-scope copy is retained and quarantines the application ID.+ for (object, row) in noteRows where processedNotes.insert(object).inserted {+ let raw = AssociationRawNote(row); rawNotesByObject[object] = raw+ if let value = raw.value {+ noteValues[object] = value+ requiredEvents.formUnion(value.attachmentAcceptanceIDs)+ requiredNotes.formUnion(value.parentHeadIDs)+ if let rebind = value.rebindAcceptanceID { requiredEvents.insert(rebind) }+ } else { badNotes.insert(row.id) }+ }+ let eventIDs = Array(requiredEvents.subtracting(checkedEventIDs))+ if !eventIDs.isEmpty {+ checkedEventIDs.formUnion(eventIDs)+ eventFetchCount += 1+ for row in try context.fetch(FetchDescriptor<AssociationEvent>(predicate: #Predicate { eventIDs.contains($0.id) })) {+ eventRows[ObjectIdentifier(row)] = row+ }+ }+ for (object, row) in eventRows where processedEvents.insert(object).inserted {+ let raw = AssociationRawEvent(row); rawEventsByObject[object] = raw+ guard let event = raw.value else { badEvents.insert(row.id); continue }+ values[object] = event+ selectedWorks.insert(event.payload.workID)+ switch event.payload {+ case .accept(let core):+ requiredEvents.formUnion(core.reconsideredRejectionIDs)+ requiredEvents.formUnion(core.rebind?.predecessorIDs ?? [])+ case .retire(let retirement): requiredEvents.formUnion(retirement.acceptanceIDs)+ case .reviewAcknowledgement(let acknowledgement): requiredEvents.formUnion(acknowledgement.references.map(\.markerID))+ default: break+ }+ }+ if requiredEvents.isSubset(of: checkedEventIDs), requiredNotes.isSubset(of: checkedNoteIDs),+ selectedWorks.isSubset(of: readWorks) { break }+ }+ let events = Array(eventRows.values), notes = Array(noteRows.values)+ let rawEvents = Array(rawEventsByObject.values), rawNotes = Array(rawNotesByObject.values)+ let ledger = AssociationLedgerInventory(events: Array(values.values), quarantinedIDs: badEvents)+ let foldedNotes = AssociationNoteFold(notes: Array(noteValues.values), ledger: ledger, quarantinedIDs: badNotes)+ return Self(eventRows: events, noteRows: notes, rawEvents: rawEvents, rawNotes: rawNotes,+ quarantinedEventIDs: badEvents, ledger: ledger, notes: foldedNotes, eventFetchCount: eventFetchCount, noteFetchCount: noteFetchCount)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20.swiftindex 0631eb82..2019959a 100644--- a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20.swift@@ -1,7 +1,7 @@ import Foundation import SwiftData -/// The live schema. V20 adds authored chapter metadata, durable redirects and source associations.+/// Frozen V20 schema; its stored fields are in AsterismSchemaV20Models.swift. public enum AsterismSchemaV20: VersionedSchema { public static let versionIdentifier = Schema.Version(20, 0, 0) @@ -26,29 +26,3 @@ public enum AsterismV20MigrationPlan: SchemaMigrationPlan { .lightweight(fromVersion: AsterismSchemaV19.self, toVersion: AsterismSchemaV20.self)] } }--extension AsterismSchemaV20 {- @Model public final class NoEpisodeAction {- public var workID: UUID = UUID()- public var key: String = ""- public var payloadData: Data = Data()- public init(workID: UUID, key: String, payloadData: Data) {- self.workID = workID; self.key = key; self.payloadData = payloadData- }- }- @Model public final class EntrySource {- public var id: UUID = UUID()- public var entryID: UUID = UUID()- public var urlString: String = ""- public var hostname: String = ""- public var createdAt: Date = Date(timeIntervalSince1970: 0)- public var modifiedAt: Date = Date(timeIntervalSince1970: 0)- public var evidenceData: Data?- public init(id: UUID = UUID(), entryID: UUID, urlString: String, hostname: String,- timestamp: Date, evidenceData: Data? = nil) {- self.id = id; self.entryID = entryID; self.urlString = urlString- self.hostname = hostname; self.createdAt = timestamp; self.modifiedAt = timestamp- self.evidenceData = evidenceData- }- }-}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20Models.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20Models.swiftnew file mode 100644index 00000000..03d3f8b0--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV20Models.swift@@ -0,0 +1,314 @@+import Foundation+import SwiftData++/// Frozen V20 stored model snapshot. Defaults retain CaptureTitleSource.manual,+/// EntryIdentityBasis.conservative, TitleProvenance.manual, WorkStatus.ongoing,+/// ReadingStatus.reading, SiteMode.untaught, WorkTypeState.active,+/// CharacterSuppressionKind.candidate, CharacterSuppressionStatus.active,+/// URLRuleOrigin.readerTaught and WorkURLIdentityState.none. Thumbnail .externalStorage and all inverses+/// are part of this frozen shape. ReleaseDay and ThumbnailShape spellings,+/// SHA-256 digests, JunkSuffixRule and SegmentPositionSpec retain their contracts.+extension AsterismSchemaV20 {++@Model+public final class Entry {+ public var authoredTargetData: Data?+ public var mergedIntoEntryID: UUID?+ public var mergeResolutionData: Data?+ public var id: UUID = UUID()+ public var captureTitle: String = ""+ public var captureTitleSourceRaw: String = CaptureTitleSource.manual.rawValue+ public var rawURLString: String = ""+ public var canonicalURLString: String?+ public var hostname: String = ""+ public var site: Site?+ public var entryIdentityKey: String = ""+ public var conservativeIdentityKey: String = ""+ public var identityBasisRaw: String = EntryIdentityBasis.conservative.rawValue+ public var urlWorkIdentity: String?+ public var chapterSequence: String?+ public var chapterTitle: String?+ public var note: String = ""+ public var ratingRaw: String?+ public var firstCapturedAt: Date = Date(timeIntervalSince1970: 0)+ public var lastSharedAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var work: Work?+ public var intentionallyUnattached: Bool = false+ public var characterExtractionFingerprint: String?+ public var citationsData: Data?++ public init() {}+}++@Model+public final class Work {+ public var chapterCaptureDefaultRaw: String = "ordinary"+ public var id: UUID = UUID()+ public var displayTitle: String = ""+ public var lastParsedTitle: String?+ public var genericNotes: String = ""+ public var workTypeID: UUID?+ public var genreTags: [String] = []+ public var titleProvenanceRaw: String = TitleProvenance.manual.rawValue+ public var workStatusRaw: String = WorkStatus.ongoing.rawValue+ public var readingStatusRaw: String = ReadingStatus.reading.rawValue+ public var verdict: String = ""+ public var seriesID: UUID?+ public var seriesPosition: Double?+ public var releaseDaysRaw: [String] = []+ public var publicationStateData: Data? = nil+ public var catchUpConfirmationData: Data? = nil+ public var lastChapterOverrideData: Data? = nil+ @Attribute(.externalStorage)+ public var thumbnailData: Data?+ public var thumbnailShapeRaw: String?+ public var thumbnailDigest: String?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var genericNotesExtractionFingerprint: String?+ @Relationship(deleteRule: .nullify, inverse: \Entry.work)+ public var entries: [Entry]?+ @Relationship(deleteRule: .nullify, inverse: \Character.work)+ public var characters: [Character]?+ @Relationship(deleteRule: .nullify, inverse: \CharacterSuppression.work)+ public var characterSuppressions: [CharacterSuppression]?+ @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.work)+ public var siteMemberships: [WorkSiteMembership]? = []++ public init() {}+}++@Model+public final class Site {+ public var hostname: String = ""+ public var displayName: String = ""+ public var modeRaw: String = SiteMode.untaught.rawValue+ @Relationship(deleteRule: .cascade, inverse: \TitlePattern.site)+ public var patterns: [TitlePattern]?+ @Relationship(deleteRule: .cascade, inverse: \URLRulePattern.site)+ public var urlRules: [URLRulePattern]?+ @Relationship(deleteRule: .nullify, inverse: \Entry.site)+ var entries: [Entry]?+ @Relationship(deleteRule: .nullify, inverse: \WorkSiteMembership.site)+ var workMemberships: [WorkSiteMembership]?++ public init() {}+}++@Model+public final class TitlePattern {+ public var id: UUID = UUID()+ public var version: Int = 1+ public var isActive: Bool = false+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var definitionData: Data?+ public var site: Site?++ public init() {}+}++@Model+public final class URLRulePattern {+ public var id: UUID = UUID()+ public var version: Int = 1+ public var isCurrent: Bool = false+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var originRaw: String = URLRuleOrigin.readerTaught.rawValue+ public var definitionData: Data = Data()+ public var site: Site?++ public init() {}+}++@Model+public final class WorkTypeEntity {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = WorkTypeState.active.rawValue+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class Character {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameKey: String = ""+ public var aliases: [String] = []+ public var note: String = ""+ public var factsData: Data?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var work: Work?++ public init() {}+}++@Model+public final class CharacterSuppression {+ public var id: UUID = UUID()+ public var work: Work?+ public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+ public var nameKey: String = ""+ public var sourceKindRaw: String?+ public var sourceEntryID: UUID?+ public var evidence: String?+ public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+ public var actionAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class WorkSiteMembership {+ public var id: UUID = UUID()+ public var hostname: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var urlIdentity: String?+ public var urlIdentityStateRaw: String = WorkURLIdentityState.none.rawValue+ public var urlIdentityRuleID: UUID?+ public var workURLString: String?+ public var workID: UUID?+ public var work: Work?+ public var site: Site?++ public init() {}+}++@Model+public final class WorkDistinctPair {+ public var id: UUID = UUID()+ public var lowerWorkID: UUID = UUID()+ public var higherWorkID: UUID = UUID()+ public var recordedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class Series {+ public var id: UUID = UUID()+ public var name: String = ""+ public var notes: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class WorkLink {+ public var id: UUID = UUID()+ public var lowerWorkID: UUID = UUID()+ public var higherWorkID: UUID = UUID()+ public var linkType: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class Creator {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var notes: String = ""+ public var notesModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = "active"+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class CreatorRole {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var position: Int = 0+ public var positionModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var stateRaw: String = "active"+ public var stateModifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var canonicalID: UUID?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class WorkCredit {+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var creatorID: UUID = UUID()+ public var roleIDs: [String] = []+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class Place {+ public var id: UUID = UUID()+ public var name: String = ""+ public var nameKey: String = ""+ public var aliases: [String] = []+ public var note: String = ""+ public var factsData: Data?+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var workID: UUID = UUID()++ public init() {}+}++@Model+public final class PlaceSuppression {+ public var id: UUID = UUID()+ public var workID: UUID = UUID()+ public var kindRaw: String = CharacterSuppressionKind.candidate.rawValue+ public var nameKey: String = ""+ public var sourceKindRaw: String?+ public var sourceEntryID: UUID?+ public var evidence: String?+ public var statusRaw: String = CharacterSuppressionStatus.active.rawValue+ public var actionAt: Date = Date(timeIntervalSince1970: 0)++ public init() {}+}++@Model+public final class NoEpisodeAction {+ public var workID: UUID = UUID()+ public var key: String = ""+ public var payloadData: Data = Data()++ public init() {}+}++}+++extension AsterismSchemaV20 {+@Model public final class EntrySource {+ public var id: UUID = UUID()+ public var entryID: UUID = UUID()+ public var urlString: String = ""+ public var hostname: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var evidenceData: Data?+ public init() {}+}+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV21.swift b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV21.swiftnew file mode 100644index 00000000..18493b22--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/AsterismSchemaV21.swift@@ -0,0 +1,55 @@+import Foundation+import SwiftData++/// Live V21 adds an extraction-owned association ledger and authored link-note versions.+public enum AsterismSchemaV21: VersionedSchema {+ public static let versionIdentifier = Schema.Version(21, 0, 0)++ public static var models: [any PersistentModel.Type] {+ [Entry.self, Work.self, Site.self, TitlePattern.self, URLRulePattern.self,+ WorkTypeEntity.self, Character.self, CharacterSuppression.self,+ WorkSiteMembership.self, WorkDistinctPair.self, Series.self, WorkLink.self,+ Creator.self, CreatorRole.self, WorkCredit.self, Place.self,+ PlaceSuppression.self, NoEpisodeAction.self, EntrySource.self, AssociationEvent.self, PairNoteVersion.self]+ }+}++public enum AsterismV21MigrationPlan: SchemaMigrationPlan {+ public static var schemas: [any VersionedSchema.Type] {+ [AsterismSchemaV16.self, AsterismSchemaV17.self, AsterismSchemaV18.self, AsterismSchemaV19.self, AsterismSchemaV20.self, AsterismSchemaV21.self]+ }++ public static var stages: [MigrationStage] {+ [.lightweight(fromVersion: AsterismSchemaV16.self, toVersion: AsterismSchemaV17.self),+ .lightweight(fromVersion: AsterismSchemaV17.self, toVersion: AsterismSchemaV18.self),+ .lightweight(fromVersion: AsterismSchemaV18.self, toVersion: AsterismSchemaV19.self),+ .lightweight(fromVersion: AsterismSchemaV19.self, toVersion: AsterismSchemaV20.self),+ .lightweight(fromVersion: AsterismSchemaV20.self, toVersion: AsterismSchemaV21.self)]+ }+}++extension AsterismSchemaV21 {+ @Model public final class NoEpisodeAction {+ public var workID: UUID = UUID()+ public var key: String = ""+ public var payloadData: Data = Data()+ public init(workID: UUID, key: String, payloadData: Data) {+ self.workID = workID; self.key = key; self.payloadData = payloadData+ }+ }+ @Model public final class EntrySource {+ public var id: UUID = UUID()+ public var entryID: UUID = UUID()+ public var urlString: String = ""+ public var hostname: String = ""+ public var createdAt: Date = Date(timeIntervalSince1970: 0)+ public var modifiedAt: Date = Date(timeIntervalSince1970: 0)+ public var evidenceData: Data?+ public init(id: UUID = UUID(), entryID: UUID, urlString: String, hostname: String,+ timestamp: Date, evidenceData: Data? = nil) {+ self.id = id; self.entryID = entryID; self.urlString = urlString+ self.hostname = hostname; self.createdAt = timestamp; self.modifiedAt = timestamp+ self.evidenceData = evidenceData+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swiftindex d579d383..a5ca982e 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupArchiveProjection.swift@@ -619,9 +619,9 @@ extension LibraryRepository { /// The record an Entry identity group archives as (Req 8.2): the /// representative row's capture evidence, the **group's** authored content,- /// and the member timestamps — which is exactly what `snapshot(_ group:)`- /// composes for every read surface, so the file and the screens agree about- /// what one record is.+ /// and the member timestamps, following `snapshot(_ group:)`'s logical+ /// composition. Legacy chapter fields remain raw beside their citations;+ /// V19+ carries the effective authored target separately. /// /// The citation blob comes from one of two rows on purpose. The /// work-assignment arm travels off the **carrier**, with the chapter-title@@ -658,7 +658,9 @@ extension LibraryRepository { identityBasis: entry.identityBasis, urlWorkIdentity: entry.urlWorkIdentity, chapterSequence: entry.chapterSequence,- chapterTitle: snap.chapterTitle,+ // This legacy field and its citation must come from the same raw+ // row. The effective authored target travels separately in V19+.+ chapterTitle: group.isSplit ? carrier.chapterTitle : entry.chapterTitle, note: snap.note, rating: snap.rating, firstCapturedAt: snap.firstCapturedAt,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swiftindex 672f0c81..1172cfe8 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImportRecords.swift@@ -130,9 +130,7 @@ extension LibraryRepository { for record in records { let target = record.archivedWorkID.flatMap { workTargets[$0] } if let rows = rowsByID[record.recordID], !rows.isEmpty {- guard let group = recordGroup(id: record.recordID, rows: rows), !group.isTorn,- record.modifiedAt >= group.modifiedAt- else { continue }+ guard let group = applicableImportedRecordGroup(record, rows: rows) else { continue } // Every row of the group takes the write, or the archive lands // on one row and tears the group it was applying to (Req 2.7's // rule, and Q85's).@@ -159,6 +157,14 @@ extension LibraryRepository { } } + static func applicableImportedRecordGroup<Row: RecordRow>(_ record: Row.ArchiveRecord,+ rows: [Row]) -> RecordGroup<Row>?+ where Row.ArchiveRecord: ArchivedRecord {+ guard let group = recordGroup(id: record.recordID, rows: rows), !group.isTorn,+ record.modifiedAt >= group.modifiedAt else { return nil }+ return group+ }+ /// One suppression array into one table. Keyed by **row** UUID rather than /// by group, because a suppression is a system record: it never tears, and /// the store reads a set of them through by `actionAt` (Q82).
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swiftindex 67513988..0ea7a301 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupImporter.swift@@ -16,6 +16,8 @@ import OSLog /// keeping them separate is what lets a future generation arrive without the /// upsert learning its envelope. public struct BackupImportPayload: Sendable, Equatable {+ public let associationEvents: [AssociationRawEvent]+ public let pairNoteVersions: [AssociationRawNote] public let chapterEntries: [UUID: BackupV19Entry] public let workCaptureDefaults: [UUID: ChapterCaptureDefault] public let entrySources: [BackupV19EntrySource]@@ -59,8 +61,11 @@ public struct BackupImportPayload: Sendable, Equatable { noEpisodeActions: [BackupV18NoEpisodeAction] = [], chapterEntries: [UUID: BackupV19Entry] = [:], workCaptureDefaults: [UUID: ChapterCaptureDefault] = [:],- entrySources: [BackupV19EntrySource] = []+ entrySources: [BackupV19EntrySource] = [],+ associationEvents: [AssociationRawEvent] = [], pairNoteVersions: [AssociationRawNote] = [] ) {+ self.associationEvents = associationEvents+ self.pairNoteVersions = pairNoteVersions self.chapterEntries = chapterEntries self.workCaptureDefaults = workCaptureDefaults self.entrySources = entrySources@@ -108,7 +113,8 @@ public struct BackupImportPayload: Sendable, Equatable { noEpisodeActions: payload.noEpisodeActions) } - public init(_ payload: BackupV19Payload) {+ public init(_ payload: BackupV19Payload, associationEvents: [AssociationRawEvent] = [],+ pairNoteVersions: [AssociationRawNote] = []) { self.init(entries: payload.entries.map(\.predecessorRecord), works: payload.works.map(\.predecessorRecord), sites: payload.sites, titlePatterns: payload.titlePatterns, urlRules: payload.urlRules, workTypes: payload.workTypes, memberships: payload.memberships, distinctPairs: payload.distinctPairs,@@ -118,7 +124,12 @@ public struct BackupImportPayload: Sendable, Equatable { noEpisodeActions: payload.noEpisodeActions, chapterEntries: Dictionary(uniqueKeysWithValues: payload.entries.map { ($0.id, $0) }), workCaptureDefaults: Dictionary(uniqueKeysWithValues: payload.works.map { ($0.id, $0.chapterCaptureDefault) }),- entrySources: payload.entrySources)+ entrySources: payload.entrySources, associationEvents: associationEvents,+ pairNoteVersions: pairNoteVersions)+ }+ public init(_ payload: BackupV20Payload) {+ self.init(payload.library, associationEvents: payload.associationEvents,+ pairNoteVersions: payload.pairNoteVersions) } /// Whether any record carries a character-extraction coverage fingerprint.@@ -278,7 +289,7 @@ public enum BackupImporter { /// constants, so the accepted pair moves with the generation rather than /// being restated here. private static let supportedVersions = (- format: BackupV19Document.formatVersion, schema: BackupV19Document.schemaVersion+ format: BackupV20Document.formatVersion, schema: BackupV20Document.schemaVersion ) // MARK: - Plan Dispatch (Req 5.1, 5.2, Decision 2)@@ -291,7 +302,7 @@ public enum BackupImporter { let (formatVersion, schemaVersion) = try detectVersions(data) logger.debug("Detected format=\(formatVersion) schema=\(schemaVersion)") - guard (formatVersion, schemaVersion) == supportedVersions || (formatVersion, schemaVersion) == (18, 19) else {+ guard (formatVersion, schemaVersion) == supportedVersions || (formatVersion, schemaVersion) == (19, 20) || (formatVersion, schemaVersion) == (18, 19) else { // The pair is named, always. An older archive was restorable until // its read path was retired, so a reader meeting this has done // nothing wrong and is owed the version rather than a shrug.@@ -309,8 +320,8 @@ public enum BackupImporter { } private static func planFromArchive(_ data: Data) throws -> BackupImportPlan {- let compatible: CompatibleBackupDocument- do { compatible = try BackupV19Codec.decodeCompatible(data) }+ let compatible: CompatibleBackupV20Document+ do { compatible = try BackupV20Codec.decodeCompatible(data) } catch { throw BackupImportError.decodingFailed(reason: String(describing: error)) } let payload: BackupImportPayload let metadata: BackupImportMetadata@@ -329,6 +340,14 @@ public enum BackupImporter { schemaVersion: document.databaseSchemaVersion, appBuild: document.appBuild, exportedAt: document.exportedAt, capabilityGate: document.capabilityGate, entryCount: document.entryCount, workCount: document.workCount)+ case .legacy(let document):+ // Keep absence distinct: importing an old archive may not reset a+ // newer work default or authored target it could not represent.+ payload = BackupImportPayload(document.payload)+ metadata = BackupImportMetadata(formatVersion: document.backupFormatVersion,+ schemaVersion: document.databaseSchemaVersion, appBuild: document.appBuild,+ exportedAt: document.exportedAt, capabilityGate: document.capabilityGate,+ entryCount: document.entryCount, workCount: document.workCount) } let counts = try validate(payload) return BackupImportPlan(
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV18Exporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV18Exporter.swiftindex d8b10808..23b1b281 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupV18Exporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV18Exporter.swift@@ -107,7 +107,10 @@ extension LibraryRepository: BackupV18SnapshotProviding { public func backupV18Snapshot() async throws -> BackupV18Payload { let outcome: Result<BackupV18Payload, BackupV18ExportError> = try await withLockedBackupContext { context in- do { return .success(try Self.projectV18Payload(context: context)) }+ do {+ try Self.requireLegacyAssociationRepresentation(context: context)+ return .success(try Self.projectV18Payload(context: context))+ } catch let error as BackupV18ExportError { return .failure(error) } } return try outcome.get()
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV19Exporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV19Exporter.swiftindex 27f5fc18..4b1b555c 100644--- a/Packages/AsterismCore/Sources/AsterismCore/BackupV19Exporter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV19Exporter.swift@@ -10,72 +10,77 @@ extension LibraryRepository: BackupV19SnapshotProviding { let outcome: Result<BackupV19Payload, BackupV18ExportError> = try await withLockedBackupContext { context in do {- let predecessor = try Self.projectV18Payload(context: context)- let entryRows = try context.fetch(FetchDescriptor<Entry>())- let groups = Self.entryGroups(entryRows,- canonicalWorkIDs: try Self.canonicalWorkIDs(normalising: entryRows, context: context),- includeResolvedRedirects: true)- let workRows = try context.fetch(FetchDescriptor<Work>())- for row in workRows where ChapterCaptureDefault(rawValue: row.chapterCaptureDefaultRaw) == nil {- throw BackupV18ExportError.unrepresentableValue(record: "Work \(row.id)",- field: "chapterCaptureDefault", value: row.chapterCaptureDefaultRaw)- }- let works = Self.workGroups(workRows, types: try Self.workTypeDirectory(context: context))- let sources = try context.fetch(FetchDescriptor<EntrySource>())- let bySourceID = Dictionary(grouping: sources, by: \.id)- let index = try EntrySourceIndex(context: context)- let sourceCopies = try bySourceID.keys.sorted { $0.uuidString < $1.uuidString }.map { id in- let rows = bySourceID[id]!- guard Set(rows.compactMap { index.destination(of: $0.entryID) }).count == 1,- rows.allSatisfy({ index.destination(of: $0.entryID) != nil }), Set(rows.map { ExactScalarString($0.urlString) }).count == 1,- Set(rows.map(\.hostname)).count == 1 else {- throw BackupV18ExportError.unrepresentableValue(record: "EntrySource \(id)", field: "ownership", value: "differing copies")- }- let evidence = try rows.compactMap { row in- try row.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }- }- let first = rows[0]- return BackupV19EntrySource(id: id, entryID: index.destination(of: first.entryID)!, urlString: first.urlString,- hostname: first.hostname, createdAt: rows.map(\.createdAt).min()!,- modifiedAt: rows.map(\.modifiedAt).max()!,- evidenceData: evidence.isEmpty ? nil : try EntrySourceEvidence.union(evidence).encoded())- }- let pairs = Dictionary(grouping: sourceCopies) {- ExactScalarString("\($0.entryID.uuidString)/\($0.urlString)")- }- let sourceRecords = try pairs.values.map { copies in- let winner = copies.min { $0.id.uuidString < $1.id.uuidString }!- let evidence = try copies.compactMap { copy in- try copy.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }- }- return BackupV19EntrySource(id: winner.id, entryID: winner.entryID, urlString: winner.urlString,- hostname: winner.hostname, createdAt: copies.map(\.createdAt).min()!,- modifiedAt: copies.map(\.modifiedAt).max()!,- evidenceData: evidence.isEmpty ? nil : try EntrySourceEvidence.union(evidence).encoded())- }.sorted { $0.id.uuidString < $1.id.uuidString }- let payload = BackupV19Payload(entries: predecessor.entries.map { record in- let carrier = groups[record.id]!.carrier- return BackupV19Entry(predecessor: record, authoredTargetData: carrier.authoredTargetData,- mergedIntoEntryID: carrier.mergedIntoEntryID, mergeResolutionData: carrier.mergeResolutionData)- }, works: predecessor.works.map { record in- BackupV19Work(predecessor: record, chapterCaptureDefault: works[record.id]!.carrier.chapterCaptureDefault)- }, sites: predecessor.sites, titlePatterns: predecessor.titlePatterns, urlRules: predecessor.urlRules,- workTypes: predecessor.workTypes, memberships: predecessor.memberships,- distinctPairs: predecessor.distinctPairs, characters: predecessor.characters,- suppressions: predecessor.suppressions, places: predecessor.places,- placeSuppressions: predecessor.placeSuppressions, series: predecessor.series,- links: predecessor.links, creators: predecessor.creators, creatorRoles: predecessor.creatorRoles,- credits: predecessor.credits, noEpisodeActions: predecessor.noEpisodeActions, entrySources: sourceRecords)- try BackupV19ReferenceValidator.validate(payload: payload)- return .success(payload)- } catch let error as BackupV18ExportError {- return .failure(error)- }+ try Self.requireLegacyAssociationRepresentation(context: context)+ return .success(try Self.projectV19Payload(context: context))+ } catch let error as BackupV18ExportError { return .failure(error) } } return try outcome.get() } } +extension LibraryRepository {+ static func projectV19Payload(context: ModelContext) throws -> BackupV19Payload {+ let predecessor = try Self.projectV18Payload(context: context)+ let entryRows = try context.fetch(FetchDescriptor<Entry>())+ let groups = Self.entryGroups(entryRows,+ canonicalWorkIDs: try Self.canonicalWorkIDs(normalising: entryRows, context: context),+ includeResolvedRedirects: true)+ let workRows = try context.fetch(FetchDescriptor<Work>())+ for row in workRows where ChapterCaptureDefault(rawValue: row.chapterCaptureDefaultRaw) == nil {+ throw BackupV18ExportError.unrepresentableValue(record: "Work \(row.id)",+ field: "chapterCaptureDefault", value: row.chapterCaptureDefaultRaw)+ }+ let works = Self.workGroups(workRows, types: try Self.workTypeDirectory(context: context))+ let sources = try context.fetch(FetchDescriptor<EntrySource>())+ let bySourceID = Dictionary(grouping: sources, by: \.id)+ let index = try EntrySourceIndex(context: context)+ let sourceCopies = try bySourceID.keys.sorted { $0.uuidString < $1.uuidString }.map { id in+ let rows = bySourceID[id]!+ guard Set(rows.compactMap { index.destination(of: $0.entryID) }).count == 1,+ rows.allSatisfy({ index.destination(of: $0.entryID) != nil }), Set(rows.map { ExactScalarString($0.urlString) }).count == 1,+ Set(rows.map(\.hostname)).count == 1 else {+ throw BackupV18ExportError.unrepresentableValue(record: "EntrySource \(id)", field: "ownership", value: "differing copies")+ }+ let evidence = try rows.compactMap { row in+ try row.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }+ }+ let first = rows[0]+ return BackupV19EntrySource(id: id, entryID: index.destination(of: first.entryID)!, urlString: first.urlString,+ hostname: first.hostname, createdAt: rows.map(\.createdAt).min()!,+ modifiedAt: rows.map(\.modifiedAt).max()!,+ evidenceData: evidence.isEmpty ? nil : try EntrySourceEvidence.union(evidence).encoded())+ }+ let pairs = Dictionary(grouping: sourceCopies) {+ ExactScalarString("\($0.entryID.uuidString)/\($0.urlString)")+ }+ let sourceRecords = try pairs.values.map { copies in+ let winner = copies.min { $0.id.uuidString < $1.id.uuidString }!+ let evidence = try copies.compactMap { copy in+ try copy.evidenceData.map { try JSONBlob.decode(EntrySourceEvidence.self, from: $0) }+ }+ return BackupV19EntrySource(id: winner.id, entryID: winner.entryID, urlString: winner.urlString,+ hostname: winner.hostname, createdAt: copies.map(\.createdAt).min()!,+ modifiedAt: copies.map(\.modifiedAt).max()!,+ evidenceData: evidence.isEmpty ? nil : try EntrySourceEvidence.union(evidence).encoded())+ }.sorted { $0.id.uuidString < $1.id.uuidString }+ let payload = BackupV19Payload(entries: predecessor.entries.map { record in+ let carrier = groups[record.id]!.carrier+ return BackupV19Entry(predecessor: record, authoredTargetData: carrier.authoredTargetData,+ mergedIntoEntryID: carrier.mergedIntoEntryID, mergeResolutionData: carrier.mergeResolutionData)+ }, works: predecessor.works.map { record in+ BackupV19Work(predecessor: record, chapterCaptureDefault: works[record.id]!.carrier.chapterCaptureDefault)+ }, sites: predecessor.sites, titlePatterns: predecessor.titlePatterns, urlRules: predecessor.urlRules,+ workTypes: predecessor.workTypes, memberships: predecessor.memberships,+ distinctPairs: predecessor.distinctPairs, characters: predecessor.characters,+ suppressions: predecessor.suppressions, places: predecessor.places,+ placeSuppressions: predecessor.placeSuppressions, series: predecessor.series,+ links: predecessor.links, creators: predecessor.creators, creatorRoles: predecessor.creatorRoles,+ credits: predecessor.credits, noEpisodeActions: predecessor.noEpisodeActions, entrySources: sourceRecords)+ try BackupV19ReferenceValidator.validate(payload: payload)+ return payload+ }+}+ public final class BackupV19Exporter: Sendable { private let repository: any BackupV19SnapshotProviding private let stagingDirectory: URL
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV20Codec.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV20Codec.swiftnew file mode 100644index 00000000..fa9796e7--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV20Codec.swift@@ -0,0 +1,158 @@+import Foundation++/// Current archive codec; released predecessor codecs remain frozen.+public enum BackupV20Codec {+ /// Pinned literally. 20/21 ships at the multi-site gate; a future gate flip+ /// cannot retroactively change what these files say.+ static let gate = "multi-site"++ /// The generation this codec speaks, as it appears in decode diagnostics.+ static let label = "V20"++ // MARK: - Encode++ /// The envelope's keys that sort **before** `"payload"`, and the one that+ /// sorts after it.+ ///+ /// The payload is encoded once, for the checksum, and then spliced into the+ /// envelope rather than encoded a second time as `BackupV20Document.payload`+ /// would be. Over a covered library the payload is tens of megabytes and the+ /// envelope is a hundred bytes, so the second encode was the whole file+ /// written twice to add nine keys to it.+ ///+ /// Two halves rather than a search for where to insert: the canonical+ /// encoder sorts keys, so the split point is a fact about the alphabet+ /// (`exportedAt` < `payload` < `workCount`) and not something to look for in+ /// bytes a build string could have imitated.+ private struct EnvelopeHead: Encodable {+ let appBuild: String+ let backupFormatVersion: Int+ let capabilityGate: String+ let checksum: String+ let databaseSchemaVersion: Int+ let entryCount: Int+ let exportedAt: Date+ }++ private struct EnvelopeTail: Encodable {+ let workCount: Int+ }++ public static func encode(+ payload: BackupV20Payload,+ metadata: BackupV19Metadata+ ) throws -> Data {+ let encoder = BackupCanonicalJSON.encoder()++ let payloadData = try encoder.encode(payload)+ let checksum = BackupCanonicalJSON.sha256Hex(payloadData)++ let head = try encoder.encode(EnvelopeHead(+ appBuild: metadata.appBuild,+ backupFormatVersion: BackupV20Document.formatVersion,+ capabilityGate: Self.gate,+ checksum: checksum,+ databaseSchemaVersion: BackupV20Document.schemaVersion,+ entryCount: payload.library.entries.count,+ exportedAt: metadata.exportedAt))+ let tail = try encoder.encode(EnvelopeTail(workCount: payload.library.works.count))++ guard head.first == UInt8(ascii: "{"), head.last == UInt8(ascii: "}"),+ tail.first == UInt8(ascii: "{"), tail.last == UInt8(ascii: "}")+ else {+ throw BackupCodecError.encodingFailed(reason: "envelope halves are not JSON objects")+ }++ var document = Data(capacity: head.count + payloadData.count + tail.count + 16)+ document.append(head.dropLast()) // {"appBuild":…,"exportedAt":"…"+ document.append(contentsOf: Array(#","payload":"#.utf8))+ document.append(payloadData)+ document.append(UInt8(ascii: ","))+ document.append(tail.dropFirst()) // "workCount":N}+ return document+ }++ // MARK: - Decode++ /// Exact20/21 envelope with required/checksummed raw arrays. Base record+ /// validation remains the released V19 contract; feature metadata may be+ /// incomplete or contradictory and is preserved raw for named review.+ public static func decode(_ data: Data) throws -> BackupV20Document {+ do {+ let rootKeys = try DuplicateJSONKeyValidator.validate(data)+ try BackupArchiveShapeValidator.validate(rootKeys: rootKeys)++ let document = try BackupCanonicalJSON.decoder()+ .decode(BackupV20Document.self, from: data)++ guard document.backupFormatVersion == BackupV20Document.formatVersion else {+ throw BackupCodecError.invalidFormatVersion(document.backupFormatVersion)+ }+ guard document.databaseSchemaVersion == BackupV20Document.schemaVersion else {+ throw BackupCodecError.invalidSchemaVersion(document.databaseSchemaVersion)+ }+ guard document.capabilityGate == Self.gate else {+ throw BackupCodecError.unsupportedGate(document.capabilityGate)+ }++ guard document.entryCount == document.payload.library.entries.count else {+ throw BackupCodecError.countMismatch(+ field: "entryCount",+ expected: document.entryCount,+ actual: document.payload.library.entries.count+ )+ }+ guard document.workCount == document.payload.library.works.count else {+ throw BackupCodecError.countMismatch(+ field: "workCount",+ expected: document.workCount,+ actual: document.payload.library.works.count+ )+ }++ // Verify checksum: re-encode payload with the same settings.+ let payloadData = try BackupCanonicalJSON.encoder().encode(document.payload)+ let computedChecksum = BackupCanonicalJSON.sha256Hex(payloadData)+ guard document.checksum == computedChecksum else {+ throw BackupCodecError.checksumMismatch(+ expected: document.checksum,+ actual: computedChecksum+ )+ }++ try BackupV19ReferenceValidator.validate(payload: document.payload.library)++ return document+ } catch let error as BackupCodecError { throw error }+ catch {+ throw BackupCodecError.decodingFailed(reason: String(describing: error))+ }+ }+}+++public enum CompatibleBackupV20Document: Sendable {+ case current(BackupV20Document)+ case predecessor(BackupV19Document)+ case legacy(BackupV18Document)+ public var payload: BackupV20Payload {+ switch self {+ case .current(let document): document.payload+ case .predecessor(let document): .init(library: document.payload)+ case .legacy(let document): .init(library: .init(predecessor: document.payload))+ }+ }+}++extension BackupV20Codec {+ public static func decodeCompatible(_ data: Data) throws -> CompatibleBackupV20Document {+ struct Versions: Decodable { let backupFormatVersion: Int; let databaseSchemaVersion: Int }+ let versions = try BackupCanonicalJSON.decoder().decode(Versions.self, from: data)+ switch (versions.backupFormatVersion, versions.databaseSchemaVersion) {+ case (20, 21): return .current(try decode(data))+ case (19, 20): return .predecessor(try BackupV19Codec.decode(data))+ case (18, 19): return .legacy(try BackupV18Codec.decode(data))+ default: throw BackupCodecError.invalidFormatVersion(versions.backupFormatVersion)+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV20Exporter.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV20Exporter.swiftnew file mode 100644index 00000000..10895969--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV20Exporter.swift@@ -0,0 +1,107 @@+import Foundation+import SwiftData++public protocol BackupV20SnapshotProviding: Sendable {+ func backupV20Snapshot() async throws -> BackupV20Payload+}++extension LibraryRepository: BackupV20SnapshotProviding {+ public func backupV20Snapshot() async throws -> BackupV20Payload {+ let outcome: Result<BackupV20Payload, BackupV18ExportError> =+ try await withLockedBackupContext { context in+ do {+ let base = try Self.projectV19Payload(context: context)+ let events = try context.fetch(FetchDescriptor<AssociationEvent>()).map(AssociationRawEvent.init)+ .sorted { [$0.id.uuidString, $0.variantIdentity].lexicographicallyPrecedes([$1.id.uuidString, $1.variantIdentity]) }+ let notes = try context.fetch(FetchDescriptor<PairNoteVersion>()).map(AssociationRawNote.init)+ .sorted { [$0.id.uuidString, $0.variantIdentity].lexicographicallyPrecedes([$1.id.uuidString, $1.variantIdentity]) }+ return .success(.init(library: base, associationEvents: events, pairNoteVersions: notes))+ } catch let error as BackupV18ExportError { return .failure(error) }+ }+ return try outcome.get()+ }+}++public final class BackupV20Exporter: Sendable {+ private let repository: any BackupV20SnapshotProviding+ private let stagingDirectory: URL++ public init(+ repository: any BackupV20SnapshotProviding,+ stagingDirectory: URL+ ) {+ self.repository = repository+ self.stagingDirectory = stagingDirectory+ }++ public func export(metadata: BackupV20Metadata) async throws -> BackupExportResult {+ let payload: BackupV20Payload+ do {+ payload = try await repository.backupV20Snapshot()+ } catch let error as BackupV18ExportError {+ throw error+ } catch {+ throw BackupV18ExportError.snapshotFailed(reason: String(describing: error))+ }++ let encoded: Data+ do {+ encoded = try BackupV20Codec.encode(payload: payload, metadata: metadata)+ } catch {+ throw BackupV18ExportError.encodingFailed(reason: String(describing: error))+ }++ do {+ let decoded = try BackupV20Codec.decode(encoded)+ guard decoded.payload == payload else {+ throw BackupV18ExportError.encodingFailed(reason: "decode-validation payload mismatch")+ }+ } catch let error as BackupV18ExportError {+ throw error+ } catch {+ throw BackupV18ExportError.encodingFailed(reason: "decode-validation failed: \(error)")+ }++ do {+ try FileManager.default.createDirectory(+ at: stagingDirectory, withIntermediateDirectories: true)+ let fileURL = stagingDirectory.appending(+ path: ExportStaging.backupFilename(+ version: "v\(BackupV20Document.formatVersion)",+ exportedAt: metadata.exportedAt))+ do {+ try ExportStaging.write(encoded, to: fileURL)+ } catch {+ throw BackupV18ExportError.stagingFailed(reason: String(describing: error))+ }+ return BackupExportResult(fileURL: fileURL)+ } catch let error as BackupV18ExportError {+ throw error+ } catch {+ throw BackupV18ExportError.stagingFailed(+ reason: "preparing staging directory failed: \(error)")+ }+ }++ public func cleanup(_ result: BackupExportResult) {+ try? FileManager.default.removeItem(at: result.fileURL)+ }++ /// Removes abandoned backup files older than 24 hours from the staging area,+ /// which still covers the files a previous build staged at an earlier+ /// generation.+ public func scavengeStaleFiles() {+ ExportStaging.scavengeBackups(in: stagingDirectory)+ }+}++extension LibraryRepository {+ static func requireLegacyAssociationRepresentation(context: ModelContext) throws {+ var events = FetchDescriptor<AssociationEvent>(); events.fetchLimit = 1+ var notes = FetchDescriptor<PairNoteVersion>(); notes.fetchLimit = 1+ guard try context.fetch(events).isEmpty && context.fetch(notes).isEmpty else {+ throw BackupV18ExportError.unrepresentableValue(record: "Chapter associations", field: "archive format",+ value: "Use the current backup format to preserve chapter links and authored notes.")+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/BackupV20Types.swift b/Packages/AsterismCore/Sources/AsterismCore/BackupV20Types.swiftnew file mode 100644index 00000000..fa7418ed--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/BackupV20Types.swift@@ -0,0 +1,67 @@+import Foundation++// Archive20/schema21 adds two raw feature arrays while retaining the released+// library record shapes. Old codecs remain frozen for bounded conversion.++public struct BackupV20Document: Codable, Equatable, Sendable {+ public static let formatVersion = 20+ public static let schemaVersion = 21++ public let backupFormatVersion: Int+ public let databaseSchemaVersion: Int+ public let appBuild: String+ public let exportedAt: Date+ public let capabilityGate: String+ public let entryCount: Int+ public let workCount: Int+ public let checksum: String+ public let payload: BackupV20Payload++ public init(+ appBuild: String,+ exportedAt: Date,+ capabilityGate: String,+ entryCount: Int,+ workCount: Int,+ checksum: String,+ payload: BackupV20Payload+ ) {+ backupFormatVersion = Self.formatVersion+ databaseSchemaVersion = Self.schemaVersion+ self.appBuild = appBuild+ self.exportedAt = exportedAt+ self.capabilityGate = capabilityGate+ self.entryCount = entryCount+ self.workCount = workCount+ self.checksum = checksum+ self.payload = payload+ }+}+++public typealias BackupV20Metadata = BackupV19Metadata++/// Composition in memory keeps the released library record types unchanged.+/// On the wire the two raw arrays share the existing flat payload object.+public struct BackupV20Payload: Codable, Equatable, Sendable {+ public var library: BackupV19Payload+ public var associationEvents: [AssociationRawEvent]+ public var pairNoteVersions: [AssociationRawNote]+ public init(library: BackupV19Payload, associationEvents: [AssociationRawEvent] = [],+ pairNoteVersions: [AssociationRawNote] = []) {+ self.library = library; self.associationEvents = associationEvents; self.pairNoteVersions = pairNoteVersions+ }+ private enum CodingKeys: String, CodingKey { case associationEvents, pairNoteVersions }+ public init(from decoder: any Decoder) throws {+ library = try BackupV19Payload(from: decoder)+ let container = try decoder.container(keyedBy: CodingKeys.self)+ associationEvents = try container.decode([AssociationRawEvent].self, forKey: .associationEvents)+ pairNoteVersions = try container.decode([AssociationRawNote].self, forKey: .pairNoteVersions)+ }+ public func encode(to encoder: any Encoder) throws {+ try library.encode(to: encoder)+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(associationEvents, forKey: .associationEvents)+ try container.encode(pairNoteVersions, forKey: .pairNoteVersions)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/CharacterExtractionTypes.swift b/Packages/AsterismCore/Sources/AsterismCore/CharacterExtractionTypes.swiftindex 609f39ca..bdea59ee 100644--- a/Packages/AsterismCore/Sources/AsterismCore/CharacterExtractionTypes.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/CharacterExtractionTypes.swift@@ -32,12 +32,24 @@ public struct CharacterExtractionSource: Sendable, Equatable { public let fingerprint: String /// The fingerprint a pass last covered, or nil where none has. public let coveredFingerprint: String?+ public let mentionEligibilityDigest: String?+ public let coveredMentionEligibilityDigest: String?+ public let displayTitle: String+ public let capturedAt: Date?+ public let isChapter: Bool+ public let stableOrder: Int - public init(ref: SourceRef, text: String, fingerprint: String, coveredFingerprint: String?) {+ public init(ref: SourceRef, text: String, fingerprint: String, coveredFingerprint: String?,+ mentionEligibilityDigest: String? = nil, coveredMentionEligibilityDigest: String? = nil,+ displayTitle: String = "", capturedAt: Date? = nil, isChapter: Bool = false, stableOrder: Int = 0) { self.ref = ref self.text = text self.fingerprint = fingerprint self.coveredFingerprint = coveredFingerprint+ self.mentionEligibilityDigest = mentionEligibilityDigest+ self.coveredMentionEligibilityDigest = coveredMentionEligibilityDigest+ self.displayTitle = displayTitle; self.capturedAt = capturedAt+ self.isChapter = isChapter; self.stableOrder = stableOrder } /// Coverage is per revision: editing the note *is* the invalidation.@@ -45,7 +57,14 @@ public struct CharacterExtractionSource: Sendable, Equatable { /// One column per source whatever kind decided it (Q9): a place decision /// covers the note exactly as a character decision does, and no second /// coverage column exists to disagree with this one.- public var isCovered: Bool { coveredFingerprint == fingerprint }+ public var isCovered: Bool {+ coveredFingerprint == fingerprint && (mentionEligibilityDigest == nil+ || coveredMentionEligibilityDigest == mentionEligibilityDigest)+ }+ public var completedSource: CompletedSource {+ .init(ref: ref, fingerprint: fingerprint, mentionEligibilityDigest: mentionEligibilityDigest)+ }+ public var attemptFingerprint: String { mentionEligibilityDigest ?? fingerprint } } /// An existing record of one kind, as decision-time matching sees it@@ -113,6 +132,7 @@ public struct ExtractionCandidate: Sendable, Equatable { /// decided content (Req 1.7). public let acceptedFacts: [RecordKind: Set<RecordFactIdentity>] public let suppressions: [RecordKind: SuppressionIndex]+ public let mentionIndex: AssociationMentionIndex public init( workID: UUID,@@ -121,7 +141,8 @@ public struct ExtractionCandidate: Sendable, Equatable { sources: [CharacterExtractionSource], records: [RecordKind: [MatchTarget]], acceptedFacts: [RecordKind: Set<RecordFactIdentity>],- suppressions: [RecordKind: SuppressionIndex]+ suppressions: [RecordKind: SuppressionIndex],+ mentionIndex: AssociationMentionIndex = .empty ) { self.workID = workID self.displayTitle = displayTitle@@ -130,6 +151,7 @@ public struct ExtractionCandidate: Sendable, Equatable { self.records = records self.acceptedFacts = acceptedFacts self.suppressions = suppressions+ self.mentionIndex = mentionIndex } public func records(of kind: RecordKind) -> [MatchTarget] { records[kind] ?? [] }@@ -160,7 +182,30 @@ public struct ExtractionCandidate: Sendable, Equatable { /// retained key, then alias key, lowest record UUID within a tier. Proposed /// aliases deliberately take no part (Q93). The caller has already narrowed the /// targets to one kind; there is no cross-kind tier and never will be (Q13).+public enum RecordRecognition: Sendable, Equatable {+ case noMatch+ case unique(UUID)+ case ambiguous+}+ public enum RecordMatching {+ /// Unattended character routing uses the same tiers, before UUID tie-break.+ /// Duplicate physical copies must agree, and torn identities never confer authority.+ public static func recognition(nameKey: String, among records: [MatchTarget]) -> RecordRecognition {+ guard !nameKey.isEmpty else { return .noMatch }+ let tiers: [(MatchTarget) -> Bool] = [+ { $0.currentNameKey == nameKey }, { $0.retainedKey == nameKey }, { $0.aliasKeys.contains(nameKey) },+ ]+ for tier in tiers {+ let matches = records.filter(tier)+ guard !matches.isEmpty else { continue }+ guard Set(matches.map(\.id)).count == 1, let first = matches.first,+ !matches.contains(where: \.isTorn), records.filter({ $0.id == first.id }).allSatisfy({ $0 == first }) else { return .ambiguous }+ return .unique(first.id)+ }+ return .noMatch+ }+ public static func match( nameKey: String, among records: [MatchTarget] ) -> MatchTarget? {@@ -232,6 +277,14 @@ public struct DecisionRequest: Sendable, Equatable { /// proposed from. Verified against current text (Req 2.7) and written as /// coverage in the same save (Q65). public var completedSources: [CompletedSource]+ public var reviewedKey: AssociationReviewKey?+ public var reviewAcknowledgements: [AssociationReviewAcknowledgement]+ public var mentions: [AssociationMentionDecision]+ /// Names-only redesigned decisions require a live coherent source even without chapter mentions.+ public var requiresCurrentSources: Bool+ /// Provenance authority is independent of whether all outcomes from a source have settled.+ public var guardedSources: [CompletedSource]?+ var sourceAuthority: [CompletedSource] { guardedSources ?? completedSources } public init( workID: UUID,@@ -244,7 +297,9 @@ public struct DecisionRequest: Sendable, Equatable { proposedAliases: [String] = [], facts: [RecordFact] = [], untickedFacts: [RecordFactIdentity] = [],- completedSources: [CompletedSource] = []+ completedSources: [CompletedSource] = [],+ mentions: [AssociationMentionDecision] = [], reviewAcknowledgements: [AssociationReviewAcknowledgement] = [], reviewedKey: AssociationReviewKey? = nil,+ requiresCurrentSources: Bool = false, guardedSources: [CompletedSource]? = nil ) { self.workID = workID self.kind = kind@@ -257,6 +312,10 @@ public struct DecisionRequest: Sendable, Equatable { self.facts = facts self.untickedFacts = untickedFacts self.completedSources = completedSources+ self.mentions = mentions+ self.requiresCurrentSources = requiresCurrentSources+ self.guardedSources = guardedSources+ self.reviewAcknowledgements = reviewAcknowledgements; self.reviewedKey = reviewedKey } /// The kinds a name-key suppression is written under when this row is@@ -301,10 +360,10 @@ public struct DecisionRequest: Sendable, Equatable { public struct CompletedSource: Sendable, Equatable, Hashable { public let ref: SourceRef public let fingerprint: String+ public let mentionEligibilityDigest: String? - public init(ref: SourceRef, fingerprint: String) {- self.ref = ref- self.fingerprint = fingerprint+ public init(ref: SourceRef, fingerprint: String, mentionEligibilityDigest: String? = nil) {+ self.ref = ref; self.fingerprint = fingerprint; self.mentionEligibilityDigest = mentionEligibilityDigest } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swiftindex 0d7d784c..f02d80fd 100644--- a/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/DuplicateReconciler.swift@@ -317,6 +317,10 @@ enum DuplicateReconciler { let rowsByID = try LibraryRepository.recordRows( Row.self, ids: resolvable.map(\.key).compactMap(\.memberIDs.first), context: context)+ let associationRows = rowsByID.values.flatMap { $0 }+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(associationRows.compactMap(\.ownerWorkID)),+ records: Set(associationRows.map { .init(kind: Row.kind, id: $0.recordID) })) var wrote = false for set in resolvable { guard let id = set.key.memberIDs.first,@@ -342,7 +346,10 @@ enum DuplicateReconciler { // No clock write (Q56): every value above is derived from synced content, // so two devices reach the same fixed point. Stamping `modifiedAt` here // would make convergence itself an edit and the fixed point unreachable.- if wrote { try saveStrategy.save(context) }+ if wrote {+ try associationBefore.finish(context: context, timestamp: associationRows.map(\.modifiedAt).max() ?? .distantPast)+ try saveStrategy.save(context)+ } return outcome } @@ -557,9 +564,19 @@ enum DuplicateReconciler { ids: Array(Set(resolvable.flatMap(\.key.memberIDs))), context: context) // Reject unreadable authored values before the first fan-out or deletion. for row in rowsByID.values.flatMap({ $0 }) { _ = try row.decodedPublicationState() }- var pending = Chunk(batchSize: batchSize)-- for set in resolvable {+ for chunkSets in convergenceChunks(resolvable, batchSize: batchSize, rowCount: { set in+ set.key.memberIDs.reduce(0) { $0 + (rowsByID[$1]?.count ?? 0) }+ }) {+ var pending = Chunk(batchSize: batchSize)+ let noteHistory = NoEpisodeWriter.HistorySession(context: context)+ let chunkRows = chunkSets.flatMap { $0.key.memberIDs }.flatMap { rowsByID[$0] ?? [] }+ let chunkEntries = chunkRows.flatMap { $0.entryValues }+ let workRecords = try WorkRecordRows(works: chunkRows, context: context)+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(chunkRows.map(\.id)), entryIDs: Set(chunkEntries.map(\.id)),+ records: workRecords.addresses, allPairs: true)+ var associationRebinds: [AssociationRebindOperation] = []+ for set in chunkSets { guard let survivorID = set.members.first?.id, let survivorRows = rowsByID[survivorID], !survivorRows.isEmpty else { continue }@@ -596,10 +613,16 @@ enum DuplicateReconciler { let moved = repointEntries( from: set.members.dropFirst().compactMap { rowsByID[$0.id] }.flatMap { $0 }, to: survivor)- result.noteActionsChanged = try NoEpisodeWriter.recordNoteTransition(+ result.noteActionsChanged = try noteHistory.record( before: beforeNotes,- after: NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar),- context: context) || result.noteActionsChanged+ after: NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar)) || result.noteActionsChanged+ let losingWorks = set.members.dropFirst().compactMap { rowsByID[$0.id] }.flatMap { $0 }+ let losingIDs = Set(losingWorks.map(\.id))+ if losingWorks.contains(where: { !$0.characterValues.isEmpty || !$0.characterSuppressionValues.isEmpty })+ || workRecords.contains(owners: losingIDs) { wrote = true }+ LibraryRepository.moveCharacters(from: losingWorks, to: survivor, timestamp: latest)+ workRecords.move(from: Set(losingWorks.map(\.id)), to: survivor, timestamp: latest)+ associationRebinds += set.members.dropFirst().map { .workMerge(fromWorkID: $0.id, toWorkID: survivorID) } if moved > 0 { wrote = true } if wrote { result.outcome.contentWrites += 1 }@@ -618,11 +641,12 @@ enum DuplicateReconciler { fingerprint: fingerprint) : nil, settling: !settled && !losers.isEmpty)- try pending.commitIfFull(+ }+ try associationBefore.finish(context: context,+ timestamp: chunkRows.map(\.modifiedAt).max() ?? .distantPast, rebinds: associationRebinds)+ try pending.commit( context: context, saveStrategy: saveStrategy, ledger: &ledger, into: &result) }- try pending.commit(- context: context, saveStrategy: saveStrategy, ledger: &ledger, into: &result) return result } @@ -989,9 +1013,15 @@ enum DuplicateReconciler { // Scoped to these sets' members, for the reason the Work phase states. let rowsByID = try entryRows( ids: Array(Set(resolvable.flatMap(\.key.memberIDs))), context: context)- var pending = Chunk(batchSize: batchSize)-- for set in resolvable {+ for chunkSets in convergenceChunks(resolvable, batchSize: batchSize, rowCount: { set in+ set.key.memberIDs.reduce(0) { $0 + (rowsByID[$1]?.count ?? 0) }+ }) {+ var pending = Chunk(batchSize: batchSize)+ let noteHistory = NoEpisodeWriter.HistorySession(context: context)+ let chunkRows = chunkSets.flatMap { $0.key.memberIDs }.flatMap { rowsByID[$0] ?? [] }+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(chunkRows.compactMap { $0.work?.id }), entryIDs: Set(chunkRows.map(\.id)))+ for set in chunkSets { guard let survivorID = set.members.first?.id, let survivorRows = rowsByID[survivorID], !survivorRows.isEmpty else { continue }@@ -1027,10 +1057,9 @@ enum DuplicateReconciler { wrote = true } }- result.noteActionsChanged = try NoEpisodeWriter.recordNoteTransition(+ result.noteActionsChanged = try noteHistory.record( before: beforeNotes,- after: NoEpisodeWriter.facts(rows: allRows, calendar: noteCalendar),- context: context) || result.noteActionsChanged+ after: NoEpisodeWriter.facts(rows: allRows, calendar: noteCalendar)) || result.noteActionsChanged if wrote { result.outcome.contentWrites += 1 } pending.add(records: allRows.count)@@ -1047,11 +1076,12 @@ enum DuplicateReconciler { fingerprint: fingerprint) : nil, settling: !settled && !losers.isEmpty)- try pending.commitIfFull(+ }+ try associationBefore.finish(context: context,+ timestamp: chunkRows.map(\.modifiedAt).max() ?? .distantPast)+ try pending.commit( context: context, saveStrategy: saveStrategy, ledger: &ledger, into: &result) }- try pending.commit(- context: context, saveStrategy: saveStrategy, ledger: &ledger, into: &result) return result } @@ -1118,6 +1148,8 @@ enum DuplicateReconciler { var committed: [DuplicateSetKey] = [] for chunk in deletionChunks(of: plans) {+ let noteHistory = NoEpisodeWriter.HistorySession(context: context)+ var entrySources = EntrySourceInventory() // Read per chunk, not per plan: staging a chunk saves nothing and // rolls nothing back, so one read of a table that is tens of rows // (Q20) serves every plan in it. It is read again below because the@@ -1129,6 +1161,9 @@ enum DuplicateReconciler { // is found where it now is. var creditsByWork = creditBuckets( of: try context.fetch(FetchDescriptor<WorkCredit>()))+ let deletionState = try deletionAssociations(chunk, rows: rows, context: context)+ let associationBefore = deletionState.mutation+ var associationRebinds: [AssociationRebindOperation] = [] var staged: [DuplicateDeletionPlan] = [] var doomedEntries: [Entry] = [] // The place tables, read once for the chunk's Entry plans rather@@ -1142,16 +1177,22 @@ enum DuplicateReconciler { guard try stage( plan, rows: &rows, canonicalWorkIDs: canonicalWorkIDs, types: types, distinctPairs: distinctPairs, links: links, creditsByWork: &creditsByWork,- creators: creators, placeRows: placeRows, doomedEntries: &doomedEntries,- context: context, noteCalendar: noteCalendar)+ creators: creators, placeRows: placeRows, workRecords: deletionState.records, doomedEntries: &doomedEntries,+ context: context, noteCalendar: noteCalendar, noteHistory: noteHistory,+ entrySources: &entrySources) else { continue }+ associationRebinds += deletionRebinds(plan, before: associationBefore) staged.append(plan) } guard !staged.isEmpty else { continue } delete(entries: doomedEntries, context: context)+ try associationBefore.finish(context: context, timestamp: .distantPast, rebinds: associationRebinds) if try commitDeletion( context: context, saveStrategy: saveStrategy,- refault: { try rows.refault(context: context) })+ refault: {+ try rows.refault(context: context)+ try deletionState.records.refault(context: context)+ }) { committed += staged.map(\.key) continue@@ -1166,7 +1207,12 @@ enum DuplicateReconciler { creditsByWork = creditBuckets( of: try context.fetch(FetchDescriptor<WorkCredit>())) for plan in staged {+ // The chunk rollback discarded both base mutations and the+ // feature rows. Rebuild value authority from this transaction.+ let replayState = try deletionAssociations([plan], rows: rows, context: context)+ let replayAssociations = replayState.mutation var replayed: [Entry] = []+ var replayEntrySources = EntrySourceInventory() // Per plan here, deliberately: the replay commits one plan at a // time and a failure rolls back, so its rows have to be read // after that rollback like every other row this loop touches.@@ -1178,13 +1224,20 @@ enum DuplicateReconciler { guard try stage( plan, rows: &rows, canonicalWorkIDs: canonicalWorkIDs, types: types, distinctPairs: distinctPairs, links: links, creditsByWork: &creditsByWork,- creators: creators, placeRows: replayPlaceRows, doomedEntries: &replayed,- context: context, noteCalendar: noteCalendar)+ creators: creators, placeRows: replayPlaceRows, workRecords: replayState.records, doomedEntries: &replayed,+ context: context, noteCalendar: noteCalendar,+ noteHistory: NoEpisodeWriter.HistorySession(context: context),+ entrySources: &replayEntrySources) else { continue } delete(entries: replayed, context: context)+ try replayAssociations.finish(context: context, timestamp: .distantPast,+ rebinds: deletionRebinds(plan, before: replayAssociations)) if try commitDeletion( context: context, saveStrategy: saveStrategy,- refault: { try rows.refault(context: context) })+ refault: {+ try rows.refault(context: context)+ try replayState.records.refault(context: context)+ }) { committed.append(plan.key) }@@ -1193,6 +1246,99 @@ enum DuplicateReconciler { return committed } + /// Current physical source presence for ONE deletion save chunk. No model+ /// rows or state survive save, rollback or replay; a combine invalidates it.+ struct EntrySourceInventory {+ private var entryIDs: Set<UUID>?++ mutating func contains(+ any ids: [UUID], context: ModelContext,+ fetchRows: (ModelContext) throws -> [EntrySource] = {+ try $0.fetch(FetchDescriptor<EntrySource>())+ }+ ) throws -> Bool {+ if entryIDs == nil {+ entryIDs = Set(try fetchRows(context).map(\.entryID))+ }+ return !entryIDs!.isDisjoint(with: ids)+ }++ mutating func invalidate() { entryIDs = nil }+ }++ /// Selected once per actual Work save chunk, including late children at+ /// the deletion boundary. Empty Entry-only chunks perform no table reads.+ private struct WorkRecordRows {+ var places: [UUID: [Place]]+ var suppressions: [UUID: [PlaceSuppression]]+ var addresses: Set<AssociationRecordAddress>+ var characterSuppressionIDs: [UUID]+ var placeSuppressionIDs: [UUID]+ init(works: [Work], context: ModelContext) throws {+ let placeRows = works.isEmpty ? [] : try Place.rows(of: works, context: context)+ let suppressionRows = works.isEmpty ? [] : try PlaceSuppression.rows(of: works, context: context)+ places = Dictionary(grouping: placeRows, by: \.workID)+ suppressions = Dictionary(grouping: suppressionRows, by: \.workID)+ characterSuppressionIDs = works.flatMap(\.characterSuppressionValues).map(\.id)+ placeSuppressionIDs = suppressionRows.map(\.id)+ addresses = Set(works.flatMap(\.characterValues).map { .init(kind: .character, id: $0.id) })+ .union(placeRows.map { .init(kind: .place, id: $0.id) })+ }+ func refault(context: ModelContext) throws {+ // Scope by the physical transaction's known application IDs, since+ // rolled-back owner accessors themselves may still be cached.+ _ = try CharacterRecord.rows(ids: addresses.filter { $0.kind == .character }.map(\.id), context: context)+ _ = try Place.rows(ids: addresses.filter { $0.kind == .place }.map(\.id), context: context)+ let characters = characterSuppressionIDs, places = placeSuppressionIDs+ if !characters.isEmpty {+ _ = try context.fetch(FetchDescriptor<CharacterSuppression>(predicate: #Predicate { characters.contains($0.id) }))+ }+ if !places.isEmpty {+ _ = try context.fetch(FetchDescriptor<PlaceSuppression>(predicate: #Predicate { places.contains($0.id) }))+ }+ }+ func contains(owners: Set<UUID>) -> Bool {+ owners.contains { !(places[$0] ?? []).isEmpty || !(suppressions[$0] ?? []).isEmpty }+ }+ func move(from owners: Set<UUID>, to target: [Work], timestamp: Date) {+ LibraryRepository.movePlaces(rows: owners.flatMap { places[$0] ?? [] },+ suppressions: owners.flatMap { suppressions[$0] ?? [] }, to: target, timestamp: timestamp)+ }+ }++ /// One selected inventory per existing save chunk (or failed-chunk replay).+ /// Known Work/Entry UUIDs also find historical ownership when sync has+ /// temporarily removed a live owner pointer.+ private static func deletionAssociations(_ plans: [DuplicateDeletionPlan], rows: DeletionRows,+ context: ModelContext) throws -> (mutation: AssociationMutation, records: WorkRecordRows) {+ let workIDs = Set(plans.filter { $0.key.recordType == .work }.flatMap(\.key.memberIDs))+ let works = workIDs.flatMap { rows.works[$0] ?? [] }+ let entries = plans.filter { $0.key.recordType == .entry }.flatMap(\.key.memberIDs)+ .flatMap { rows.entries[$0] ?? [] } + works.flatMap(\.entryValues)+ let owners = workIDs.union(entries.compactMap { $0.work?.id })+ let records = try WorkRecordRows(works: works, context: context)+ let mutation = try AssociationMutation.capture(context: context, workIDs: owners,+ entryIDs: Set(entries.map(\.id)), records: records.addresses, allPairs: !workIDs.isEmpty)+ return (mutation, records)+ }++ /// Only a plan that passed the existing commit-time fingerprint check may+ /// provide identity routing. There is no inferred route from missing rows.+ private static func deletionRebinds(_ plan: DuplicateDeletionPlan,+ before: AssociationMutation) -> [AssociationRebindOperation] {+ switch plan.key.recordType {+ case .entry:+ guard let destination = before.endpoints.sources[plan.survivorID]?.workID else { return [] }+ return plan.loserIDs.compactMap { id in+ guard let source = before.endpoints.sources[id], source.workID == destination else { return nil }+ return .entryMerge(workID: destination, fromEntryID: id, toEntryID: plan.survivorID)+ }+ case .work:+ return plan.loserIDs.map { .workMerge(fromWorkID: $0, toWorkID: plan.survivorID) }+ default: return []+ }+ }+ /// Deletes Entry rows, detaching them from their Site in **one rewrite of /// that inverse per Site** rather than one removal per row (T-2093). ///@@ -1277,9 +1423,12 @@ enum DuplicateReconciler { creditsByWork: inout [UUID: [WorkCredit]], creators: CreatorDirectory, placeRows: PlaceRepointRows,+ workRecords: WorkRecordRows, doomedEntries: inout [Entry], context: ModelContext,- noteCalendar: Calendar+ noteCalendar: Calendar,+ noteHistory: NoEpisodeWriter.HistorySession,+ entrySources: inout EntrySourceInventory ) throws -> Bool { switch plan.key.recordType { case .entry:@@ -1314,22 +1463,25 @@ enum DuplicateReconciler { rows: placeRows.rows(of: works), suppressions: placeRows.suppressions(of: works), survivors: survivors, timestamp: stamp)- let sourceRows = try context.fetch(FetchDescriptor<EntrySource>())- let retainRedirects = touched.contains { $0.authoredTargetData != nil }- || sourceRows.contains { plan.key.memberIDs.contains($0.entryID) }+ // Lazy, after the same verified fingerprint and citation rewrites.+ // The presence index considers every physical source row.+ let hasSource = try entrySources.contains(any: plan.key.memberIDs, context: context)+ let retainRedirects = touched.contains { $0.authoredTargetData != nil } || hasSource for id in plan.loserIDs { if retainRedirects, let losing = rows.entries[id], let group = LibraryRepository.entryGroup(id: id, rows: losing, canonicalWorkIDs: canonicalWorkIDs) { try EntrySources.combine(loser: group, survivorID: plan.survivorID, timestamp: stamp, context: context)+ // combine may insert/repoint through its wider index. Do not+ // infer its effects or reuse pre-mutation source presence.+ entrySources.invalidate() } else { doomedEntries += rows.entries[id] ?? [] } } let survivingEntries = rows.entries[plan.survivorID] ?? []- try NoEpisodeWriter.recordNoteTransition(+ try noteHistory.record( before: beforeNotes,- after: NoEpisodeWriter.facts(rows: survivingEntries, calendar: noteCalendar),- context: context)+ after: NoEpisodeWriter.facts(rows: survivingEntries, calendar: noteCalendar)) return true case .work: guard workFingerprint(plan.key.memberIDs, rowsByID: rows.works, types: types)@@ -1347,15 +1499,16 @@ enum DuplicateReconciler { let affectedEntries = losers.flatMap { $0.entryValues } let beforeNotes = NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar) repointEntries(from: losers, to: survivor)- try NoEpisodeWriter.recordNoteTransition(+ let stamp = (losers + survivor).map(\.modifiedAt).max() ?? .distantPast+ LibraryRepository.moveCharacters(from: losers, to: survivor, timestamp: stamp)+ workRecords.move(from: Set(losers.map(\.id)), to: survivor, timestamp: stamp)+ try noteHistory.record( before: beforeNotes,- after: NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar),- context: context)+ after: NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar)) let loserIDs = Set(plan.loserIDs)- for action in try context.fetch(FetchDescriptor<NoEpisodeAction>())- where loserIDs.contains(action.workID) {- action.workID = plan.survivorID- }+ // Preserve raw move semantics; decoded state is rebuilt only if a+ // later nonempty transition in this same chunk needs it.+ try noteHistory.repointActions(from: loserIDs, to: plan.survivorID) carrySeries(from: losers, to: survivor) carryThumbnail(from: losers, to: survivor) carryCatchUp(from: losers, to: survivor)@@ -2014,6 +2167,19 @@ enum DuplicateReconciler { } } + /// A set is never split, matching Chunk's physical-row capacity. Planning+ /// boundaries first lets the feature capture once before a chunk mutates.+ private static func convergenceChunks<Element>(_ sets: [Element], batchSize: Int,+ rowCount: (Element) -> Int) -> [[Element]] {+ var result: [[Element]] = [], current: [Element] = [], count = 0+ for set in sets {+ current.append(set); count += rowCount(set)+ if batchSize > 0, count >= batchSize { result.append(current); current = []; count = 0 }+ }+ if !current.isEmpty { result.append(current) }+ return result+ }+ // MARK: - Commit chunking /// Accumulates a chunk's worth of sets and commits them together.
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swiftindex 5f36f054..5803052a 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryProviding.swift@@ -17,6 +17,18 @@ public protocol LibraryProviding: Sendable { func projectEntryCorrection(entryID: UUID, destinationID: UUID?) async throws -> EntryCorrectionContract func commitEntryCorrection(_ contract: EntryCorrectionContract, target: AuthoredEntryTarget, contentChoice: EntryCorrectionContentChoice?) async throws -> EntryCorrectionOutcome+ func recordPendingMentionReviews(_ requests: [AssociationPendingReviewRequest]) async throws -> [AssociationPendingReviewResult]+ func commitRecognisedCharacter(_ request: DecisionRequest) async throws -> DecisionOutcome+ func commitReclassifiedRecognisedCharacter(_ request: DecisionRequest) async throws -> DecisionOutcome+ func skippedCharacterLinks(entryID: UUID) async throws -> [SkippedCharacterLinkSnapshot]+ func restoreCharacterLink(_ captured: SkippedCharacterLinkSnapshot) async throws -> DecisionOutcome+ func recordHistory(workID: UUID, kind: RecordKind, recordID: UUID) async throws -> RecordHistorySnapshot+ func chapterAssociations(entryID: UUID) async throws -> [ChapterAssociationSnapshot]+ func associationNoteBasis(pair: AssociationPair) async throws -> AssociationNoteBasis?+ func saveAssociationNote(basis: AssociationNoteBasis, text: String) async throws -> AssociationNoteWriteOutcome+ func clearAssociationNote(basis: AssociationNoteBasis) async throws -> AssociationNoteWriteOutcome+ func recoverAssociationNotes(basis: AssociationNoteBasis, selectedHeads: [AssociationNoteValue], text: String) async throws -> AssociationNoteWriteOutcome+ func detachedAssociationNotes() async throws -> [DetachedAssociationNoteSnapshot] // MARK: - Read operations func todayPresentation(calendar: Calendar) async throws -> TodayPresentation func works() async throws -> WorksSnapshot@@ -613,6 +625,37 @@ public protocol LibraryProviding: Sendable { } public extension LibraryProviding {+ func recordHistory(workID: UUID, kind: RecordKind, recordID: UUID) async throws -> RecordHistorySnapshot {+ throw LibraryRepositoryError.invalidInput(operation: "reading record history", reason: "unavailable in this library")+ }+ func commitRecognisedCharacter(_ request: DecisionRequest) async throws -> DecisionOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "saving recognised character links", reason: "unavailable in this library")+ }+ func commitReclassifiedRecognisedCharacter(_ request: DecisionRequest) async throws -> DecisionOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "reclassifying recognised character links", reason: "unavailable in this library")+ }+ func skippedCharacterLinks(entryID: UUID) async throws -> [SkippedCharacterLinkSnapshot] {+ throw LibraryRepositoryError.invalidInput(operation: "reading skipped character links", reason: "unavailable in this library")+ }+ func restoreCharacterLink(_ captured: SkippedCharacterLinkSnapshot) async throws -> DecisionOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "restoring a character link", reason: "unavailable in this library")+ }+ func recordPendingMentionReviews(_ requests: [AssociationPendingReviewRequest]) async throws -> [AssociationPendingReviewResult] {+ throw LibraryRepositoryError.invalidInput(operation: "preserving pending mention review", reason: "unavailable in this library")+ }+ func chapterAssociations(entryID: UUID) async throws -> [ChapterAssociationSnapshot] { [] }+ func associationNoteBasis(pair: AssociationPair) async throws -> AssociationNoteBasis? { nil }+ func detachedAssociationNotes() async throws -> [DetachedAssociationNoteSnapshot] { [] }+ func saveAssociationNote(basis: AssociationNoteBasis, text: String) async throws -> AssociationNoteWriteOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "saving association note", reason: "unavailable in this library")+ }+ func clearAssociationNote(basis: AssociationNoteBasis) async throws -> AssociationNoteWriteOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "clearing association note", reason: "unavailable in this library")+ }+ func recoverAssociationNotes(basis: AssociationNoteBasis, selectedHeads: [AssociationNoteValue], text: String) async throws -> AssociationNoteWriteOutcome {+ throw LibraryRepositoryError.invalidInput(operation: "recovering association note", reason: "unavailable in this library")+ }+ func updateManualNote(id: UUID, basis: EntrySnapshot, title: String?, sourceURL: String?, note: String, rating: Rating?) async throws -> LibraryWriteOutcome { throw LibraryRepositoryError.invalidInput(operation: "editing manual note", reason: "Manual note metadata editing is unavailable")
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+AssociationNotes.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+AssociationNotes.swiftnew file mode 100644index 00000000..4b333e4f--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+AssociationNotes.swift@@ -0,0 +1,144 @@+import Foundation+import SwiftData++public struct AssociationNoteBasis: Sendable, Equatable {+ public var pair: AssociationPair+ public var acceptanceIDs: Set<UUID>+ public var validationReceipt: AssociationValidationReceipt+ public var heads: [AssociationNoteValue]+ public var originalContext: String+ public var headIDs: Set<UUID> { Set(heads.map(\.id)) }+ public init(pair: AssociationPair, acceptanceIDs: Set<UUID>, validationReceipt: AssociationValidationReceipt,+ heads: [AssociationNoteValue], originalContext: String) {+ self.pair = pair; self.acceptanceIDs = acceptanceIDs; self.validationReceipt = validationReceipt+ self.heads = heads; self.originalContext = originalContext+ }+}++public enum AssociationNoteWriteOutcome: Sendable, Equatable {+ case committed, reviewRequired, inactive, invalidMetadata+}++public struct DetachedAssociationNoteSnapshot: Sendable, Equatable, Identifiable {+ /// Application UUID plus exact complete raw-body digest. Valid head UUIDs+ /// are a distinct selection namespace from contradictory raw variants.+ public var id: String+ public var raw: AssociationRawNote+ public var pair: AssociationPair?+ public var head: AssociationNoteValue?+ public var canRecover: Bool+}++extension LibraryRepository {+ private struct AssociationNoteState {+ var storage: AssociationStorageInventory+ var current: AssociationCurrentPair?+ var acceptanceIDs: Set<UUID>+ var heads: [AssociationNoteValue]+ var invalidMetadata: Bool+ var context: String+ var basis: AssociationNoteBasis? {+ guard !invalidMetadata, !acceptanceIDs.isEmpty, let current else { return nil }+ return .init(pair: current.pair, acceptanceIDs: acceptanceIDs,+ validationReceipt: storage.ledger.receipt(for: current), heads: heads, originalContext: context)+ }+ }+ private static func associationNoteState(pair: AssociationPair, context: ModelContext) throws -> AssociationNoteState {+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [pair.workID])+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: [pair])+ let current = endpoints.current(pair)+ let active = current.map { storage.ledger.activeAcceptanceIDs(for: $0) } ?? []+ let heads = storage.notes.heads(for: pair).filter { !Set($0.attachmentAcceptanceIDs).isDisjoint(with: active) }+ let invalid = storage.rawNotes.contains { raw in+ let origin = try? JSONBlob.decode(AssociationPair.self, from: raw.originPairData)+ guard origin == pair || origin == nil && raw.workID == pair.workID else { return false }+ return raw.value == nil || storage.notes.invalidIDs.contains(raw.id)+ }+ let label = [endpoints.sources[pair.entryID]?.title ?? pair.entryID.uuidString,+ pair.kind.rawValue, endpoints.targets[.init(kind: pair.kind, id: pair.recordID)]?.displayName ?? pair.recordID.uuidString]+ .joined(separator: " • ")+ return .init(storage: storage, current: current, acceptanceIDs: active, heads: heads,+ invalidMetadata: invalid, context: label)+ }++ public func associationNoteBasis(pair: AssociationPair) async throws -> AssociationNoteBasis? {+ try await withLockedContext(mode: .shared, operation: "reading association note") { context in+ try Self.associationNoteState(pair: pair, context: context).basis+ }+ }+ public func saveAssociationNote(basis: AssociationNoteBasis, text: String) async throws -> AssociationNoteWriteOutcome {+ try await writeAssociationNote(basis: basis, text: text, recovering: nil)+ }+ public func clearAssociationNote(basis: AssociationNoteBasis) async throws -> AssociationNoteWriteOutcome {+ try await writeAssociationNote(basis: basis, text: "", recovering: nil)+ }+ public func recoverAssociationNotes(basis: AssociationNoteBasis, selectedHeads: [AssociationNoteValue],+ text: String) async throws -> AssociationNoteWriteOutcome {+ try await writeAssociationNote(basis: basis, text: text, recovering: selectedHeads)+ }+ private func writeAssociationNote(basis: AssociationNoteBasis, text: String,+ recovering: [AssociationNoteValue]?) async throws -> AssociationNoteWriteOutcome {+ try await withLockedContext(mode: .exclusive, operation: "saving association note") { context in+ let state = try Self.associationNoteState(pair: basis.pair, context: context)+ guard !state.invalidMetadata else { return .invalidMetadata }+ guard let current = state.basis else { return .inactive }+ guard basis.acceptanceIDs == current.acceptanceIDs,+ basis.validationReceipt == current.validationReceipt,+ basis.heads == current.heads else { return .reviewRequired }+ var parents = current.headIDs+ if let recovering {+ let detached = Dictionary(uniqueKeysWithValues: state.storage.notes.heads(for: basis.pair).filter {+ !$0.text.isEmpty && Set($0.attachmentAcceptanceIDs).isDisjoint(with: current.acceptanceIDs)+ }.map { ($0.id, $0) })+ guard !recovering.isEmpty, recovering.allSatisfy({ detached[$0.id] == $0 }) else { return .reviewRequired }+ parents.formUnion(recovering.map(\.id))+ }+ let note = AssociationNoteValue(pair: basis.pair, attachmentAcceptanceIDs: Array(current.acceptanceIDs),+ parentHeadIDs: Array(parents), operation: recovering != nil ? .recover : text.isEmpty ? .clear : .text,+ text: text, originalContext: current.originalContext,+ authoredAt: MillisecondInstant.quantize(clock.now()))+ context.insert(try PairNoteVersion(note: note))+ try saveStrategy.save(context)+ return .committed+ }+ }++ public func detachedAssociationNotes() async throws -> [DetachedAssociationNoteSnapshot] {+ try await withLockedContext(mode: .shared, operation: "reading detached association notes") { context in+ // Explicit Settings recovery inventory, once; no normal read or+ // per-pair operation traverses all library note history.+ let workIDs = Set(try context.fetch(FetchDescriptor<PairNoteVersion>()).map(\.workID))+ let storage = try AssociationStorageInventory.read(context: context, workIDs: workIDs)+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: storage.ledger.pairs)+ var activeIDs: Set<UUID> = []+ var activePairs: Set<AssociationPair> = []+ for pair in storage.ledger.pairs {+ guard let current = endpoints.current(pair) else { continue }+ let ids = storage.ledger.activeAcceptanceIDs(for: current)+ activeIDs.formUnion(ids)+ if !ids.isEmpty { activePairs.insert(pair) }+ }+ let detached = Set(storage.notes.detachedTextHeads(activeAcceptanceIDs: activeIDs).map(\.id))+ var blockedPairs: Set<AssociationPair> = [], blockedWorks: Set<UUID> = []+ for raw in storage.rawNotes where raw.value == nil || storage.notes.invalidIDs.contains(raw.id) {+ if let pair = try? JSONBlob.decode(AssociationPair.self, from: raw.originPairData) { blockedPairs.insert(pair) }+ else { blockedWorks.insert(raw.workID) }+ }+ var variants: [String: DetachedAssociationNoteSnapshot] = [:]+ for raw in storage.rawNotes {+ let value = raw.value+ let invalid = value == nil || storage.notes.invalidIDs.contains(raw.id)+ guard invalid || detached.contains(raw.id) else { continue }+ // Validate all physical copies BEFORE deduplicating exact raw+ // display variants. The serializer preserves raw timestamp bits.+ let identity = raw.id.uuidString + "/" + raw.variantIdentity+ let pair = value?.pair ?? (try? JSONBlob.decode(AssociationPair.self, from: raw.originPairData))+ variants[identity] = .init(id: identity, raw: raw, pair: pair, head: invalid ? nil : value,+ canRecover: !invalid && pair.map {+ activePairs.contains($0) && !blockedPairs.contains($0) && !blockedWorks.contains($0.workID)+ } == true)+ }+ return variants.values.sorted { $0.id < $1.id }+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Associations.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Associations.swiftnew file mode 100644index 00000000..ff92cc21--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Associations.swift@@ -0,0 +1,147 @@+import Foundation+import SwiftData++extension LibraryRepository {+ public func chapterAssociations(entryID: UUID) async throws -> [ChapterAssociationSnapshot] {+ try await withLockedContext(mode: .shared, operation: "reading saved chapter associations") { context in+ try Self.chapterAssociations(entryID: entryID, context: context)+ }+ }+ /// Value publication shares the Entry detail read's existing lock/context.+ static func chapterAssociations(entryID: UUID, context: ModelContext) throws -> [ChapterAssociationSnapshot] {+ let entries = try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { $0.id == entryID }))+ let addressed = try context.fetch(FetchDescriptor<AssociationEvent>(predicate: #Predicate { $0.entryID == entryID }))+ let workIDs = Set(entries.compactMap { $0.work?.id }).union(addressed.map(\.workID))+ let storage = try AssociationStorageInventory.read(context: context, workIDs: workIDs)+ let pairs = storage.ledger.pairs.filter { $0.entryID == entryID }+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: pairs)+ let rawByPair = Dictionary(grouping: storage.rawNotes.compactMap { raw in raw.value.map { ($0.pair, raw) } }, by: { $0.0 })+ .mapValues { $0.map(\.1) }+ return pairs.map { pair in+ let current = endpoints.current(pair)+ let receipt = current.map { storage.ledger.receipt(for: $0) }+ let ids = current.map { storage.ledger.activeAcceptanceIDs(for: $0) } ?? []+ return ChapterAssociationSnapshot(pair: pair,+ recordName: endpoints.targets[.init(kind: pair.kind, id: pair.recordID)]?.displayName ?? pair.recordID.uuidString,+ chapterTitle: endpoints.sources[entryID]?.title ?? entryID.uuidString,+ evidence: ids.isEmpty ? [] : receipt?.evidence ?? [], activeAcceptanceIDs: ids,+ validationReceipt: receipt,+ noteHeads: storage.notes.heads(for: pair).filter { !Set($0.attachmentAcceptanceIDs).isDisjoint(with: ids) },+ rawNotes: rawByPair[pair, default: []])+ }.sorted { [$0.pair.kind.rawValue, $0.recordName, $0.pair.recordID.uuidString]+ .lexicographicallyPrecedes([$1.pair.kind.rawValue, $1.recordName, $1.pair.recordID.uuidString]) }+ }+}++extension LibraryRepository {+ static func associationDirectoryDigest(workID: UUID, records: [RecordKind: [MatchTarget]],+ coherentRecordIDs: [RecordKind: Set<UUID>]) -> String {+ let signatures = RecordKind.allCases.flatMap { kind in+ records[kind, default: []].map { record in+ AssociationDigest.of("association/directory-target/v1", [kind.rawValue, record.id.uuidString,+ record.currentNameKey, record.retainedKey, String(record.aliasKeys.count),+ coherentRecordIDs[kind, default: []].contains(record.id) ? "eligible" : "incoherent"] + record.aliasKeys.sorted())+ }+ }.sorted()+ return AssociationDigest.of("association/matching-directory/v1", [workID.uuidString] + signatures)+ }++ static func associationSourceDigest(entry: Entry, workID: UUID, directory: String,+ ledger: AssociationLedgerInventory) -> String {+ ledger.coverageDigest(workID: workID, entryID: entry.id,+ sourceFingerprint: AssociationEndpointInventory.sourceFingerprint(entry), matchingDirectory: directory)+ }++ /// Strict new-link gates precede the existing fact/alias/record write. The+ /// established dangling fact-citation behavior is deliberately unchanged.+ static func associationAcceptanceRefusal(_ request: DecisionRequest, before: AssociationMutation) -> DecisionRefusal? {+ guard request.action == .accept, !request.mentions.isEmpty else { return nil }+ let endpoints = before.endpoints+ let storage = before.storage+ let names: [String]+ if let recordID = request.displayedTargetID {+ let address = AssociationRecordAddress(kind: request.kind, id: recordID)+ guard let target = endpoints.targets[address] else {+ return endpoints.targetStates[address] == nil ? .reRouted(to: nil) : .torn(recordID: recordID)+ }+ guard target.workID == request.workID else { return .reRouted(to: nil) }+ names = target.names + request.proposedAliases+ } else { names = [request.proposedName] + request.proposedAliases }+ for mention in request.mentions {+ guard let source = endpoints.sources[mention.entryID], source.workID == request.workID, source.eligible,+ CharacterCoverageFingerprint.of(source.note) == mention.noteFingerprint else { return .staleSource(.entry(mention.entryID)) }+ if let expected = mention.sourceGuard, expected != storage.ledger.sourceGuard(workID: request.workID,+ entryID: mention.entryID, sourceFingerprint: source.fingerprint) { return .staleSource(.entry(mention.entryID)) }+ let evidence = RecordMentionGrounding.evidence(names: names, in: source.note)+ guard !mention.spellingKeys.isEmpty, Set(mention.spellingKeys).isSubset(of: Set(evidence.map(\.key))) else {+ return .staleSource(.entry(mention.entryID))+ }+ if let recordID = request.displayedTargetID {+ let pair = AssociationPair(workID: request.workID, entryID: mention.entryID, kind: request.kind, recordID: recordID)+ guard Set(storage.ledger.rejectionIDs(pair: pair, spellingKeys: mention.spellingKeys)) == Set(mention.observedRejectionIDs) else {+ return .staleSource(.entry(mention.entryID))+ }+ }+ }+ return nil+ }++ static func associationDecisionEvents(_ request: DecisionRequest, recordID: UUID?,+ before: AssociationMutation) -> [AssociationLedgerEvent] {+ guard let targetID = recordID ?? request.displayedTargetID else { return [] }+ return request.mentions.compactMap { mention in+ let pair = AssociationPair(workID: request.workID, entryID: mention.entryID, kind: request.kind, recordID: targetID)+ switch request.action {+ case .skip:+ return .init(payload: .reject(.init(pair: pair, spellingKeys: mention.spellingKeys)))+ case .accept:+ let needsAcknowledgement = mention.spellingKeys.contains {+ before.storage.ledger.isSuppressed(pair: pair, spellingKey: $0)+ }+ if before.active[pair] != nil && !needsAcknowledgement { return nil }+ return .init(payload: .accept(.init(pair: pair, spellingKeys: mention.spellingKeys,+ reconsideredRejectionIDs: mention.observedRejectionIDs)))+ }+ }+ }+}++extension LibraryRepository {+ static func writeAssociationCoverage(_ sources: [CompletedSource], workID: UUID, works: [Work],+ context: ModelContext, timestamp: Date) throws -> Set<SourceRef> {+ let requested = sources.filter { $0.mentionEligibilityDigest != nil && $0.ref.entryID != nil }+ guard !requested.isEmpty else { return [] }+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [workID], includeNotes: false)+ let records: [RecordKind: [MatchTarget]] = [+ .character: recordGroups(try CharacterRecord.rows(of: works, context: context)).values.map(matchTarget),+ .place: recordGroups(try Place.rows(of: works, context: context)).values.map(matchTarget),+ ]+ let suppressedUnmatched = suppressedUnmatchedCandidateKeys(records: records, suppressions: [+ .character: suppressionIndex(try CharacterSuppression.rows(of: works, context: context)),+ .place: suppressionIndex(try PlaceSuppression.rows(of: works, context: context)),+ ])+ let selectedRecords = Set(records.flatMap { kind, targets in+ targets.map { AssociationRecordAddress(kind: kind, id: $0.id) }+ })+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: storage.ledger.pairs,+ entryIDs: Set(requested.compactMap { $0.ref.entryID }), records: selectedRecords)+ let coherent = Dictionary(grouping: endpoints.targets.values.filter { $0.workID == workID }, by: { $0.address.kind })+ .mapValues { Set($0.map { $0.address.id }) }+ let directory = associationDirectoryDigest(workID: workID, records: records, coherentRecordIDs: coherent)+ let ambiguous = Self.ambiguousReviewSources(storage)+ var written: Set<SourceRef> = []+ for source in requested {+ guard let id = source.ref.entryID, let current = endpoints.sources[id], current.workID == workID, current.eligible,+ CharacterCoverageFingerprint.of(current.note) == source.fingerprint else { continue }+ guard !Self.pendingMentionState(workID: workID, entryID: id, ledger: storage.ledger,+ endpoints: endpoints, ambiguousSources: ambiguous, suppressedUnmatchedKeys: suppressedUnmatched).blocksCoverage else { continue }+ let digest = storage.ledger.coverageDigest(workID: workID, entryID: id,+ sourceFingerprint: current.fingerprint, matchingDirectory: directory)+ guard digest == source.mentionEligibilityDigest,+ !storage.ledger.hasCoverage(workID: workID, entryID: id, digest: digest) else { continue }+ let event = AssociationLedgerEvent(payload: .coverage(.init(workID: workID, entryID: id, eligibilityDigest: digest)))+ context.insert(try AssociationEvent(event: event, recordedAt: timestamp)); written.insert(source.ref)+ }+ return written+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swiftindex 0106913d..76b6e0e4 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImport.swift@@ -175,5 +175,8 @@ extension LibraryRepository { context.insert(row) row.attach(to: worksByID[record.workID], archivedWorkID: record.workID) }+ for raw in payload.associationEvents { context.insert(AssociationEvent(raw: raw)) }+ for raw in payload.pairNoteVersions { context.insert(PairNoteVersion(raw: raw)) }+ } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swiftindex 894c0293..8b99533c 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+BackupImportGates.swift@@ -52,7 +52,7 @@ extension LibraryRepository { // Every one of those is a reason to name the live schema here, and it // must be re-checked on every snapshot freeze — this line has now been // re-checked at the V10 through V15 freezes and moved to V16.- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: true,
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swiftindex 150ce685..c5ac20a7 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Bootstrap.swift@@ -380,7 +380,7 @@ extension LibraryRepository { at storeURL: URL, mirroring cloudKitDatabase: ModelConfiguration.CloudKitDatabase = .none ) throws -> ModelContainer {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let storeConfiguration = ModelConfiguration( // **Frozen persisted state (Req 3.5).** This names the store // configuration *inside* the container, not the file — `url:` below is@@ -394,7 +394,7 @@ extension LibraryRepository { ) return try ModelContainer( for: schema,- migrationPlan: AsterismV20MigrationPlan.self,+ migrationPlan: AsterismV21MigrationPlan.self, configurations: [storeConfiguration] ) }@@ -547,7 +547,7 @@ extension LibraryRepository { /// convert its store anyway; the recovery is the backup archive, as for any /// unrecognised marker. static let appOpenableMarkerVersions: Set<String> = [- laggingOpenableMarkerVersion, "17", "18", "19", extensionOpenableMarkerVersion,+ laggingOpenableMarkerVersion, "17", "18", "19", "20", extensionOpenableMarkerVersion, ] /// The one lagging generation the app still opens: a library certified by a@@ -560,7 +560,7 @@ extension LibraryRepository { /// installed library (Req 3.5). Both generations the app opens are now /// spelled with two characters, which is why nothing anywhere may assume a /// marker is one character long.- static let extensionOpenableMarkerVersion = "20"+ static let extensionOpenableMarkerVersion = "21" // The app-side counterpart of `validateMarkerContentForExtension` stood // here. It restated the acceptance test the classifier performs, and
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swiftindex d7250823..6e022c8c 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Capture.swift@@ -476,6 +476,8 @@ extension LibraryRepository { } // Apply the update (Req 4.3): only note, rating, lastSharedAt, modifiedAt+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(group.rows.compactMap { $0.work?.id }), entryIDs: [group.id]) let calendar = noteCalendar() let before = Self.noteFacts(group, calendar: calendar) let timestamp = MillisecondInstant.quantize(clock.now())@@ -488,6 +490,8 @@ extension LibraryRepository { try NoEpisodeWriter.recordNoteTransition( before: before, after: Self.noteFacts(group, calendar: calendar), context: context) + try associationBefore.finish(context: context, timestamp: timestamp)+ try Self.recordKnownChapterLinks(entryIDs: [group.id], context: context, timestamp: timestamp) // Save (Req 4.11: failure preserves Entry unchanged) do { try saveStrategy.save(context)@@ -593,7 +597,8 @@ extension LibraryRepository { wrote = true } }- guard wrote else { return .committed }+ let linked = try Self.recordKnownChapterLinks(entryIDs: [group.id], context: context, timestamp: timestamp)+ guard wrote || linked else { return .committed } try NoEpisodeWriter.recordNoteTransition( before: before, after: Self.noteFacts(group, calendar: calendar), context: context) try self.saveStrategy.save(context)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ChapterCapture.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ChapterCapture.swiftindex b1460dca..b8a28910 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ChapterCapture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ChapterCapture.swift@@ -246,6 +246,9 @@ extension LibraryRepository { case .chooseChapter(_, let reason): return .reviewRequired(fresh, reason: reason) } }+ let associationEntryID = selectedID ?? draft.entryID ?? UUID()+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: [workID], entryIDs: [associationEntryID]) let stamp = clock.now() do { let work = try Self.fetchWorkGroup(id: workID, context: context)@@ -271,7 +274,7 @@ extension LibraryRepository { row.lastSharedAt = draft.capturedAt ?? stamp; row.modifiedAt = stamp } } else {- let row = Entry(id: draft.entryID ?? UUID(), captureTitle: capture.captureTitle, captureTitleSource: capture.captureTitleSource,+ let row = Entry(id: associationEntryID, captureTitle: capture.captureTitle, captureTitleSource: capture.captureTitleSource, rawURLString: capture.rawURLString, canonicalURLString: capture.canonicalURLString, hostname: hostname, entryIdentityKey: capture.rawURLString, timestamp: stamp, capturedAt: draft.capturedAt, note: contentNote, rating: contentRating)@@ -331,6 +334,8 @@ extension LibraryRepository { try NoEpisodeWriter.recordNoteTransition(before: before, after: Self.noteFacts(group, calendar: noteCalendar()), context: context) let sources = try EntrySourceIndex(context: context).urls(for: group.id)+ try associationBefore.finish(context: context, timestamp: stamp)+ try Self.recordKnownChapterLinks(entryIDs: [group.id], context: context, timestamp: stamp) if let refusal = try self.commitResolution(context: context, hostnames: [hostname], operation: "chapter capture") { if case .invalidated(let reason) = refusal { return .reviewRequired(fresh, reason: reason) } return .reviewRequired(fresh, reason: "Review the chapter capture again")
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swiftindex d959461e..30b0ef7b 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ConfirmImport.swift@@ -131,6 +131,23 @@ extension LibraryRepository { return .committed(counts, report: report) } + /// Shared by the existing writer and selected association projection, so+ /// staging cannot claim a field an older/torn archive is forbidden to write.+ static func applicableImportedEntryGroup(_ record: BackupV18Entry, rows: [Entry],+ hasChapterRecord: Bool,+ canonicalWorkIDs: [UUID: UUID]) -> EntryGroup? {+ guard importedEntryFieldsAllowed(record, rows: rows, hasChapterRecord: hasChapterRecord),+ let group = entryGroup(id: record.id, rows: rows, canonicalWorkIDs: canonicalWorkIDs), !group.isTorn+ else { return nil }+ return group+ }++ static func importedEntryFieldsAllowed(_ record: BackupV18Entry, rows: [Entry], hasChapterRecord: Bool) -> Bool {+ record.modifiedAt >= (rows.map(\.modifiedAt).max() ?? .distantPast)+ && !rows.contains(where: { $0.mergedIntoEntryID != nil && !$0.isResolvedRedirect })+ && (hasChapterRecord || rows.allSatisfy({ $0.authoredTargetData == nil && $0.mergedIntoEntryID == nil }))+ }+ /// The report an interrupted import left, or nil. Read at open or from /// Settings, **however old** — a sidecar from a month ago still means that /// import did not finish, and time does not make that untrue.@@ -178,8 +195,12 @@ extension LibraryRepository { context: ModelContext, batchSize: Int, saveStrategy: any RepositorySaveStrategy,- noteCalendar: Calendar = .current+ noteCalendar: Calendar = .current,+ noteHistorySessionFactory: (ModelContext) -> NoEpisodeWriter.HistorySession = {+ NoEpisodeWriter.HistorySession(context: $0)+ } ) throws -> (counts: LibraryRecordCounts, report: BackupImportReport) {+ let associations = try AssociationImportPreparation.prepare(payload, context: context, timestamp: importedAt) // Validate and union action history before any note-bearing Entry write. // The caller's existing save boundaries commit these insertions. _ = try NoEpisodeWriter.insertMissing(@@ -397,50 +418,44 @@ extension LibraryRepository { let importCanonicalWorkIDs = try Self.canonicalWorkIDs( normalising: entryRows.values.flatMap { $0 }, context: context) for chunk in chunks(of: payload.entries, size: batchSize) {- for record in chunk {- let site = sitesByHostname[record.hostname]- let work = record.workID.flatMap { workTargets[$0] }- if let rows = entryRows[record.id], !rows.isEmpty {- // Import is a bulk path with the whole store in `entryRows`, so the- // normalisation is derived once for it above rather than per record.- guard let group = entryGroup(- id: record.id, rows: rows, canonicalWorkIDs: importCanonicalWorkIDs),- !group.isTorn- else {- continue- }- // The group's modification time, not each row's — see the- // Works step above for why all-or-none is the requirement.- guard record.modifiedAt >= group.modifiedAt,- !group.rows.contains(where: { $0.mergedIntoEntryID != nil && !$0.isResolvedRedirect }),- payload.chapterEntries[record.id] != nil || group.rows.allSatisfy({ $0.authoredTargetData == nil && $0.mergedIntoEntryID == nil })- else { continue }- let beforeNoteFacts = NoEpisodeWriter.facts(- rows: group.rows, calendar: noteCalendar)- for existing in group.rows {- apply(record, to: existing)- if let value = payload.chapterEntries[record.id] { applyChapterArchive(value, to: existing) }- // Value-guarded (T-2334): assigning the same Site/Work- // reference back still dirties a SwiftData relationship,- // so compare by identity before writing.- if existing.site !== site { existing.site = site }- if existing.work !== work { existing.work = work }+ // History is owned only by this Entry save chunk. Drop it before+ // save (and on any throw), so the next chunk/retry sees new arrivals.+ do {+ let noteHistory = noteHistorySessionFactory(context)+ for record in chunk {+ let site = sitesByHostname[record.hostname]+ let work = record.workID.flatMap { workTargets[$0] }+ if let rows = entryRows[record.id], !rows.isEmpty {+ // Import is a bulk path with the whole store in `entryRows`, so the+ // normalisation is derived once for it above rather than per record.+ guard let group = applicableImportedEntryGroup(record, rows: rows,+ hasChapterRecord: payload.chapterEntries[record.id] != nil,+ canonicalWorkIDs: importCanonicalWorkIDs) else { continue }+ let beforeNoteFacts = NoEpisodeWriter.facts(+ rows: group.rows, calendar: noteCalendar)+ for existing in group.rows {+ apply(record, to: existing)+ if let value = payload.chapterEntries[record.id] { applyChapterArchive(value, to: existing) }+ // Value-guarded (T-2334): assigning the same Site/Work+ // reference back still dirties a SwiftData relationship,+ // so compare by identity before writing.+ if existing.site !== site { existing.site = site }+ if existing.work !== work { existing.work = work }+ }+ try noteHistory.record(+ before: beforeNoteFacts,+ after: NoEpisodeWriter.facts(rows: group.rows, calendar: noteCalendar))+ } else {+ let entry = ArchiveRecordBuilders.makeEntry(record)+ if let value = payload.chapterEntries[record.id] { applyChapterArchive(value, to: entry) }+ context.insert(entry)+ entry.site = site+ entry.work = work+ entryRows[record.id] = [entry]+ try noteHistory.record(+ before: [],+ after: NoEpisodeWriter.facts(rows: [entry], calendar: noteCalendar)) }- try NoEpisodeWriter.recordNoteTransition(- before: beforeNoteFacts,- after: NoEpisodeWriter.facts(rows: group.rows, calendar: noteCalendar),- context: context)- } else {- let entry = ArchiveRecordBuilders.makeEntry(record)- if let value = payload.chapterEntries[record.id] { applyChapterArchive(value, to: entry) }- context.insert(entry)- entry.site = site- entry.work = work- entryRows[record.id] = [entry]- try NoEpisodeWriter.recordNoteTransition(- before: [],- after: NoEpisodeWriter.facts(rows: [entry], calendar: noteCalendar),- context: context) } } try saveStrategy.save(context)@@ -457,10 +472,12 @@ extension LibraryRepository { // type merge above. if !payload.characters.isEmpty || !payload.suppressions.isEmpty || !payload.places.isEmpty || !payload.placeSuppressions.isEmpty- || payload.carriesCoverage {+ || payload.carriesCoverage || !payload.associationEvents.isEmpty || !payload.pairNoteVersions.isEmpty+ || !associations.before.active.isEmpty { try mergeImportedRecords( payload, workTargets: workTargets, workRows: workRows, entryRows: entryRows, context: context)+ try associations.finish(context: context, timestamp: importedAt) try saveStrategy.save(context) } @@ -849,7 +866,7 @@ extension LibraryRepository { /// Whether `commitMemberships` will write this record's values onto the /// library — the insert branch, which is unconditional, or the update /// branch, which is gated on the Work's record having been applied.- private static func willWriteMembership(+ internal static func willWriteMembership( _ record: BackupV18Membership, existingMembershipIDs: Set<UUID>, appliedWorkIDs: Set<UUID>
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Creators.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Creators.swiftindex cea0590a..69a1e0d7 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Creators.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+Creators.swift@@ -196,7 +196,10 @@ extension LibraryRepository { } let workIDs = roleIDsByWork.keys.sorted { $0.uuidString < $1.uuidString } let groups = try Self.workGroups(ofIDs: workIDs, context: context, types: types)- let noEpisode = try NoEpisodeIndex(context: context)+ // Only these current Work groups are read below. Unrelated payloads+ // were already lazy; the scoped fetch also narrows storage-error reach.+ let noEpisode = try SelectedWorkNoEpisodeReader(+ context: context, workIDs: Set(groups.values.map(\.id))) let works = try workIDs.compactMap { workID -> CreatorWorkCredit? in guard let group = groups[workID] else { return nil }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swiftindex 6b0a1b6b..1ac333c4 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+DuplicateResolution.swift@@ -609,6 +609,8 @@ extension LibraryRepository { return (.invalidated(reason: "The chosen copy is not one of this set's."), [], nil) } let allRows = rowsByID.values.flatMap { $0 }+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(allRows.compactMap { $0.work?.id }), entryIDs: Set(set.key.memberIDs)) let noteCalendar = self.noteCalendar() let beforeNoteFacts = NoEpisodeWriter.facts(rows: allRows, calendar: noteCalendar) // Q84: the outcome content is copied off the row that carries it, so a@@ -681,6 +683,16 @@ extension LibraryRepository { after: NoEpisodeWriter.facts(rows: survivorRows, calendar: noteCalendar), context: context) + var associationRebinds: [AssociationRebindOperation] = []+ for pair in associationBefore.pairs.sorted(by: { AssociationDigest.pairToken($0).lexicographicallyPrecedes(AssociationDigest.pairToken($1)) })+ where losers.contains(pair.entryID) {+ let operation = AssociationRebindOperation.entryMerge(workID: pair.workID,+ fromEntryID: pair.entryID, toEntryID: survivorID)+ if !associationRebinds.contains(operation) { associationRebinds.append(operation) }+ }+ try associationBefore.finish(context: context, timestamp: timestamp, rebinds: associationRebinds)+ try Self.recordKnownChapterLinks(entryIDs: [survivorID], context: context, timestamp: timestamp)+ if let refusal = try commitResolution( context: context, hostnames: [carrier.hostname], operation: "resolution") { return (refusal, [], nil)@@ -791,6 +803,11 @@ extension LibraryRepository { return (.invalidated(reason: "The chosen copy is not one of this set's."), [], nil) } let allRows = rowsByID.values.flatMap { $0 }+ let associationRecords = Set(try CharacterRecord.rows(of: allRows, context: context)+ .map { AssociationRecordAddress(kind: .character, id: $0.recordID) }+ + Place.rows(of: allRows, context: context).map { AssociationRecordAddress(kind: .place, id: $0.recordID) })+ let associationBefore = try AssociationMutation.capture(context: context, workIDs: Set(set.key.memberIDs),+ entryIDs: Set(allRows.flatMap { $0.entryValues.map(\.id) }), records: associationRecords, allPairs: true) let electedCatchUp = CatchUpFold.elect(allRows.map(\.catchUpRecord)) let types = try Self.workTypeDirectory(context: context) guard let carrier = GroupOrdering.sortedWorkRows(allRows).first(@@ -924,6 +941,9 @@ extension LibraryRepository { let survivors = GroupOrdering.sortedWorkRows(survivorRows) CatchUpWriter.apply(electedCatchUp, to: survivors) DuplicateReconciler.repointEntries(from: losingRows, to: survivors)+ Self.moveCharacters(from: losingRows, to: survivors, timestamp: timestamp)+ Self.movePlaces(rows: try Place.rows(of: losingRows, context: context),+ suppressions: try PlaceSuppression.rows(of: losingRows, context: context), to: survivors, timestamp: timestamp) try NoEpisodeWriter.recordNoteTransition( before: beforeNoteFacts, after: NoEpisodeWriter.facts(rows: affectedEntries, calendar: noteCalendar),@@ -956,6 +976,9 @@ extension LibraryRepository { context: context) for row in losingRows { context.delete(row) } + try associationBefore.finish(context: context, timestamp: timestamp,+ rebinds: losers.map { .workMerge(fromWorkID: $0, toWorkID: survivorID) })+ if let refusal = try commitResolution( context: context, hostnames: hostnames, operation: "resolution") { return (refusal, [], nil)@@ -1002,6 +1025,8 @@ extension LibraryRepository { guard let chosenVariant = set.variants.first(where: { $0.id == chosen }) else { return (.invalidated(reason: "The chosen copy is not one of this set's."), [], nil) }+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(rows.compactMap(\.ownerWorkID)), records: [.init(kind: Row.kind, id: id)]) let content = chosenVariant.content let timestamp = MillisecondInstant.quantize(clock.now()) for row in rows {@@ -1030,6 +1055,7 @@ extension LibraryRepository { let hostname = ownerIDs.lazy .compactMap { id in works.first(where: { $0.id == id })?.primaryMembership?.hostname } .first ?? ""+ try associationBefore.finish(context: context, timestamp: timestamp) if let refusal = try commitResolution( context: context, hostnames: [hostname], operation: "resolution") { return (refusal, [], nil)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swiftindex 4c18e7f0..4d18af5f 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EmptyLibrary.swift@@ -169,6 +169,7 @@ extension LibraryRepository { entity(Place.self), entity(PlaceSuppression.self), entity(WorkLink.self), entity(WorkCredit.self), entity(WorkDistinctPair.self), entity(NoEpisodeAction.self), entity(EntrySource.self),+ entity(AssociationEvent.self), entity(PairNoteVersion.self), ]), EmptyLibraryPhase(name: "5 works", entities: [entity(Work.self)]), EmptyLibraryPhase(
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryCorrection.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryCorrection.swiftindex 5e230686..716f11e4 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryCorrection.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryCorrection.swift@@ -66,6 +66,9 @@ extension LibraryRepository { return .reviewRequired(reason: "The destination chapter changed") } }+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set((source.rows + (destination?.rows ?? [])).compactMap { $0.work?.id }),+ entryIDs: Set([source.id] + (destination.map { [$0.id] } ?? []))) let stamp = clock.now() let before = Self.noteFacts(source, calendar: self.noteCalendar()) .union(destination.map { Self.noteFacts($0, calendar: self.noteCalendar()) } ?? [])@@ -98,6 +101,11 @@ extension LibraryRepository { } try NoEpisodeWriter.recordNoteTransition(before: before, after: Self.noteFacts(destination ?? source, calendar: self.noteCalendar()), context: context)+ let rebinds: [AssociationRebindOperation] = destination.flatMap { target in+ source.carrier.work.map { [.entryMerge(workID: $0.id, fromEntryID: source.id, toEntryID: target.id)] }+ } ?? []+ try associationBefore.finish(context: context, timestamp: stamp, rebinds: rebinds)+ try Self.recordKnownChapterLinks(entryIDs: [destination?.id ?? source.id], context: context, timestamp: stamp) let hostnames = source.rows.map(\.hostname) + (destination?.rows.map(\.hostname) ?? []) if let refusal = try self.commitResolution(context: context, hostnames: hostnames, operation: "chapter correction") { switch refusal {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryDetail.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryDetail.swiftindex 2c6da8ed..3dead90d 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryDetail.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+EntryDetail.swift@@ -278,7 +278,8 @@ extension LibraryRepository { hasCurrentURLRule: legalSite?.currentURLRule != nil, groupState: group.state, citingCharacters: citingCharacters,- citingPlaces: citingPlaces+ citingPlaces: citingPlaces,+ chapterAssociations: try Self.chapterAssociations(entryID: group.id, context: context) ) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ManualEntry.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ManualEntry.swiftindex dbefc3e1..3b130a8f 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ManualEntry.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ManualEntry.swift@@ -67,6 +67,8 @@ extension LibraryRepository { throw LibraryRepositoryError.invalidInput(operation: "editing manual note", reason: "This source carries chapter matching history. Keep it and use the correction review") }+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(group.rows.compactMap { $0.work?.id }), entryIDs: [group.id]) do { let before = Self.noteFacts(group, calendar: self.noteCalendar()) let stamp = MillisecondInstant.quantize(self.clock.now())@@ -82,6 +84,8 @@ extension LibraryRepository { } try NoEpisodeWriter.recordNoteTransition(before: before, after: Self.noteFacts(group, calendar: self.noteCalendar()), context: context)+ try associationBefore.finish(context: context, timestamp: stamp)+ try Self.recordKnownChapterLinks(entryIDs: [group.id], context: context, timestamp: stamp) if let refusal = try self.commitResolution(context: context, hostnames: [], operation: "manual note edit") { if case .invalidated = refusal { return .conflict(.recordChanged(recordID: group.id)) } return .conflict(.recordChanged(recordID: group.id))@@ -141,6 +145,9 @@ extension LibraryRepository { } chosen = nil }+ let associationEntryID = chosen?.id ?? UUID()+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: [workID], entryIDs: [associationEntryID]) do { let stamp = MillisecondInstant.quantize(self.clock.now()) let group: EntryGroup@@ -162,7 +169,7 @@ extension LibraryRepository { row.note = draft.note; row.rating = draft.rating; row.modifiedAt = stamp } } else {- let row = Entry(captureTitle: "", captureTitleSource: .manual, rawURLString: "",+ let row = Entry(id: associationEntryID, captureTitle: "", captureTitleSource: .manual, rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: stamp, note: draft.note, rating: draft.rating) try row.authorTarget(draft.target) context.insert(row)@@ -179,6 +186,8 @@ extension LibraryRepository { try NoEpisodeWriter.recordNoteTransition(before: before, after: Self.noteFacts(group, calendar: self.noteCalendar()), context: context) let sources = try EntrySourceIndex(context: context).urls(for: group.id)+ try associationBefore.finish(context: context, timestamp: stamp)+ try Self.recordKnownChapterLinks(entryIDs: [group.id], context: context, timestamp: stamp) if let refusal = try self.commitResolution(context: context, hostnames: [], operation: "manual note") { if case .invalidated(let reason) = refusal { return .reviewRequired(fresh, reason: reason) } return .reviewRequired(fresh, reason: "Review your manual note again")
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+PendingMentionReviews.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+PendingMentionReviews.swiftnew file mode 100644index 00000000..f58aefa1--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+PendingMentionReviews.swift@@ -0,0 +1,192 @@+import Foundation+import SwiftData++extension LibraryRepository {+ struct PendingMentionState {+ var references: [AssociationReviewReference] = []+ var blocksCoverage = false+ }+ static func ambiguousReviewSources(_ storage: AssociationStorageInventory) -> Set<AssociationReviewSource> {+ let invalid = storage.ledger.invalidIDs.union(storage.ledger.pendingReviews.invalidIDs)+ return Set(storage.rawEvents.compactMap { raw in+ guard invalid.contains(raw.id), let entry = raw.entryID else { return nil }+ return .init(workID: raw.workID, entryID: entry)+ })+ }+ /// Candidate rejection is a creation-only policy. Consult the full typed+ /// directory, including torn/ambiguous matches, before making a targetless+ /// pending key irrelevant; missing endpoints alone cannot prove no match.+ static func suppressedUnmatchedCandidateKeys(records: [RecordKind: [MatchTarget]],+ suppressions: [RecordKind: SuppressionIndex]) -> Set<AssociationReviewKey> {+ Set(RecordKind.allCases.flatMap { kind in+ suppressions[kind, default: .empty].candidateKeys.compactMap { key in+ RecordMatching.match(nameKey: key, among: records[kind, default: []]) == nil+ ? AssociationReviewKey(kind: kind, nameKey: key) : nil+ }+ })+ }++ /// Relevance is source revision + original grounded identity, never the+ /// global directory digest. Missing/torn targets remain review-needed.+ static func pendingMentionState(workID: UUID, entryID: UUID, ledger: AssociationLedgerInventory,+ endpoints: AssociationEndpointInventory,+ ambiguousSources: Set<AssociationReviewSource> = [],+ suppressedUnmatchedKeys: Set<AssociationReviewKey> = []) -> PendingMentionState {+ let address = AssociationReviewSource(workID: workID, entryID: entryID)+ var result = PendingMentionState(blocksCoverage: ambiguousSources.contains(address))+ let source = endpoints.sources[entryID]+ for (id, marker) in ledger.pendingReviews.markersBySource[address, default: []] {+ if ledger.pendingReviews.invalidIDs.contains(id) { result.blocksCoverage = true; continue }+ guard let source, source.workID == workID, source.eligible else {+ result.blocksCoverage = true; continue+ }+ let guardValue = ledger.sourceGuard(workID: workID, entryID: entryID, sourceFingerprint: source.fingerprint)+ guard guardValue == marker.sourceGuard else { continue }+ for item in marker.items {+ let reference = AssociationReviewReference(markerID: id, key: item.key)+ if ledger.pendingReviews.isAcknowledged(reference) { continue }+ if item.targetID == nil, suppressedUnmatchedKeys.contains(item.key) { continue }+ let identity = AssociationReviewWitnessIdentity(sourceGuard: marker.sourceGuard, item: item)+ let redundantKeep = ledger.pendingReviews.keepWitnesses[address]?[identity]?.contains { witness in+ let pair = AssociationPair(workID: workID, entryID: entryID, kind: witness.kind, recordID: witness.recordID)+ guard let current = endpoints.current(pair), !ledger.activeAcceptanceIDs(for: current).isEmpty else { return false }+ return Set(item.spellingKeys).isSubset(of: Set(ledger.receipt(for: current).evidence.map(\.key)))+ } ?? false+ if redundantKeep { continue }+ let names: [String]+ if let targetID = item.targetID {+ if let target = endpoints.targets[.init(kind: item.key.kind, id: targetID)], target.workID == workID {+ names = target.names+ } else {+ result.blocksCoverage = true; result.references.append(reference); continue+ }+ } else { names = item.spellingKeys }+ let supported = Set(RecordMentionGrounding.evidence(names: names, in: source.note).map(\.key))+ guard !supported.isDisjoint(with: item.spellingKeys) else { continue }+ result.blocksCoverage = true; result.references.append(reference)+ }+ }+ result.references = Array(Set(result.references)).sorted {+ [$0.markerID.uuidString, $0.key.kind.rawValue, $0.key.nameKey]+ .lexicographicallyPrecedes([$1.markerID.uuidString, $1.key.kind.rawValue, $1.key.nameKey])+ }+ return result+ }++ /// The existing coverage lane saves minimal undecided keys BEFORE they are+ /// published in RAM. Caller-owned marker IDs make retry idempotent.+ public func recordPendingMentionReviews(_ requests: [AssociationPendingReviewRequest]) async throws -> [AssociationPendingReviewResult] {+ guard !requests.isEmpty else { return [] }+ return try await withLockedContext(mode: .exclusive, operation: "preserving pending mention review") { context in+ let workIDs = Set(requests.map { $0.marker.workID })+ let entries = Set(requests.map { $0.marker.entryID })+ let before = try AssociationStorageInventory.read(context: context, workIDs: workIDs,+ includeNotes: false, eventIDs: Set(requests.map(\.markerID)))+ let existing = Dictionary(grouping: before.eventRows, by: \.id)+ let values = before.eventRows.compactMap(\.ledgerValue)+ var additions: [AssociationLedgerEvent] = []+ var staged: [UUID: AssociationLedgerEvent] = [:]+ for request in requests {+ let event = AssociationLedgerEvent(id: request.markerID, payload: .pendingReview(request.marker))+ let validation = AssociationPendingReviewInventory(events: [event])+ guard !validation.invalidIDs.contains(event.id) else {+ throw LibraryRepositoryError.invalidInput(operation: "preserving pending mention review", reason: "invalid pending review identity")+ }+ if let previous = staged[event.id] {+ guard previous.payload == event.payload else {+ throw LibraryRepositoryError.invalidInput(operation: "preserving pending mention review", reason: "contradictory pending review batch")+ }+ continue+ }+ staged[event.id] = event+ if let rows = existing[event.id] {+ guard !before.ledger.pendingReviews.invalidIDs.contains(event.id),+ rows.allSatisfy({ $0.ledgerValue?.payload == event.payload }) else {+ throw LibraryRepositoryError.invalidInput(operation: "preserving pending mention review", reason: "pending review identity changed")+ }+ } else {+ additions.append(event)+ }+ }+ let ledger = AssociationLedgerInventory(events: values + additions, quarantinedIDs: before.quarantinedEventIDs)+ let ids = Array(workIDs)+ let works = try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { ids.contains($0.id) }))+ let characters = Dictionary(grouping: try CharacterRecord.rows(of: works, context: context), by: { $0.work?.id })+ let places = Dictionary(grouping: try Place.rows(of: works, context: context), by: \.workID)+ let records = Dictionary(uniqueKeysWithValues: workIDs.map { workID in+ (workID, [RecordKind.character: Self.recordGroups(characters[workID] ?? []).values.map(Self.matchTarget),+ .place: Self.recordGroups(places[workID] ?? []).values.map(Self.matchTarget)])+ })+ let characterSuppressions = Dictionary(grouping: try CharacterSuppression.rows(of: works, context: context), by: { $0.work?.id })+ let placeSuppressions = Dictionary(grouping: try PlaceSuppression.rows(of: works, context: context), by: \.workID)+ let suppressedUnmatchedByWork = Dictionary(uniqueKeysWithValues: workIDs.map { workID in+ (workID, Self.suppressedUnmatchedCandidateKeys(records: records[workID, default: [:]], suppressions: [+ .character: Self.suppressionIndex(characterSuppressions[workID] ?? []),+ .place: Self.suppressionIndex(placeSuppressions[workID] ?? []),+ ]))+ })+ let selected = Set(records.values.flatMap { $0.flatMap { kind, targets in+ targets.map { AssociationRecordAddress(kind: kind, id: $0.id) }+ } })+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: ledger.pairs, entryIDs: entries, records: selected)+ let coherentByWork = Dictionary(grouping: endpoints.targets.values, by: \.workID).mapValues {+ Dictionary(grouping: $0, by: { $0.address.kind }).mapValues { Set($0.map { $0.address.id }) }+ }+ let coherentWorks = Set(Self.workGroups(works, types: try Self.workTypeDirectory(context: context)).values.filter { !$0.isTorn }.map(\.id))+ let ambiguous = Self.ambiguousReviewSources(before)+ var results: [AssociationPendingReviewResult] = []+ for request in requests {+ let marker = request.marker+ let state = Self.pendingMentionState(workID: marker.workID, entryID: marker.entryID,+ ledger: ledger, endpoints: endpoints, ambiguousSources: ambiguous,+ suppressedUnmatchedKeys: suppressedUnmatchedByWork[marker.workID, default: []])+ var digest: String?+ if coherentWorks.contains(marker.workID), let source = endpoints.sources[marker.entryID],+ source.workID == marker.workID, source.eligible,+ before.ledger.sourceGuard(workID: marker.workID, entryID: marker.entryID, sourceFingerprint: source.fingerprint) == marker.sourceGuard {+ let directory = Self.associationDirectoryDigest(workID: marker.workID,+ records: records[marker.workID, default: [:]], coherentRecordIDs: coherentByWork[marker.workID, default: [:]])+ let base = before.ledger.coverageBaseDigest(workID: marker.workID, entryID: marker.entryID,+ sourceFingerprint: source.fingerprint, matchingDirectory: directory)+ if base == request.originalEligibilityBase {+ digest = ledger.coverageDigest(workID: marker.workID, entryID: marker.entryID,+ sourceFingerprint: source.fingerprint, matchingDirectory: directory)+ }+ }+ results.append(.init(workID: marker.workID, entryID: marker.entryID,+ completionDigest: digest, references: state.references))+ }+ do {+ if !additions.isEmpty {+ let timestamp = MillisecondInstant.quantize(self.clock.now())+ for event in additions { context.insert(try AssociationEvent(event: event, recordedAt: timestamp)) }+ try self.saveStrategy.save(context)+ }+ }+ catch { context.rollback(); throw error }+ return results+ }+ }+}++extension LibraryRepository {+ static func pendingReviewDecisionEvents(_ request: DecisionRequest, recordID: UUID?, ledger: AssociationLedgerInventory) -> [AssociationLedgerEvent] {+ guard let key = request.reviewedKey, key.nameKey == RecordNameKey.normalize(request.proposedName) else { return [] }+ let citedEntries = Set(request.sourceAuthority.compactMap { $0.ref.entryID })+ return request.reviewAcknowledgements.compactMap { captured in+ guard captured.workID == request.workID, citedEntries.contains(captured.entryID) else { return nil }+ let references = captured.references.filter { reference in+ reference.key == key && !ledger.pendingReviews.invalidIDs.contains(reference.markerID)+ && !ledger.pendingReviews.isAcknowledged(reference)+ && ledger.pendingReviews.markers[reference.markerID]?.contains(where: {+ $0.workID == captured.workID && $0.entryID == captured.entryID+ && $0.items.contains(where: { $0.key == key })+ }) == true+ }+ guard !references.isEmpty else { return nil }+ return .init(payload: .reviewAcknowledgement(.init(workID: captured.workID,+ entryID: captured.entryID, references: references,+ outcome: request.action == .accept ? recordID.map { .kept(kind: request.kind, recordID: $0) } : .skipped)))+ }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecognisedCharacters.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecognisedCharacters.swiftnew file mode 100644index 00000000..ef97a2b2--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecognisedCharacters.swift@@ -0,0 +1,214 @@+import Foundation+import SwiftData++extension LibraryRepository {+ /// Unattended recognition confers authority only to save supported links and+ /// settle captured original keys. It never invokes human Keep's enrichment+ /// or suppression-clearing writes.+ public func commitRecognisedCharacter(_ request: DecisionRequest) async throws -> DecisionOutcome {+ try Self.validateRecognisedCharacterAuthority(request, originalKind: .character)+ return try await commitRecognisedCharacter(request, restoration: nil)+ }++ /// Only the reader's explicit kind-switch action may settle an original+ /// place decision as a known character. Ordinary background routing cannot.+ public func commitReclassifiedRecognisedCharacter(_ request: DecisionRequest) async throws -> DecisionOutcome {+ try Self.validateRecognisedCharacterAuthority(request, originalKind: .place)+ return try await commitRecognisedCharacter(request, restoration: nil)+ }++ private static func validateRecognisedCharacterAuthority(_ request: DecisionRequest, originalKind: RecordKind) throws {+ guard request.kind == .character, request.action == .accept,+ request.displayedTargetID != nil, !request.sourceAuthority.isEmpty,+ request.proposedAliases.isEmpty, request.facts.isEmpty, request.untickedFacts.isEmpty,+ let key = request.reviewedKey, key.kind == originalKind, key.nameKey == RecordNameKey.normalize(request.proposedName) else {+ throw LibraryRepositoryError.invalidInput(operation: "saving recognised character links", reason: "invalid automatic character authority")+ }+ }++ private func commitRecognisedCharacter(_ request: DecisionRequest, restoration: SkippedCharacterLinkSnapshot?) async throws -> DecisionOutcome {+ guard let key = request.reviewedKey else {+ throw LibraryRepositoryError.invalidInput(operation: "saving recognised character links", reason: "missing original key")+ }+ return try await withLockedContext(mode: .exclusive, operation: "saving recognised character links") { context in+ let workID = request.workID+ let works = try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { $0.id == workID }))+ guard let work = Self.workGroup(id: workID, rows: works, types: try Self.workTypeDirectory(context: context)) else {+ return .refused(.workGone)+ }+ guard !work.isTorn else { return .refused(.torn(recordID: nil)) }+ let targets = Self.recordGroups(try CharacterRecord.rows(of: works, context: context)).values.map(Self.matchTarget)+ guard case .unique(let targetID) = RecordMatching.recognition(nameKey: key.nameKey, among: targets),+ targetID == request.displayedTargetID else { return .refused(.reRouted(to: nil)) }+ let address = AssociationRecordAddress(kind: .character, id: targetID)+ let before = try AssociationMutation.capture(context: context, workIDs: [workID],+ entryIDs: Set(request.sourceAuthority.compactMap { $0.ref.entryID }).union(request.mentions.map(\.entryID)),+ records: [address])+ guard let target = before.endpoints.targets[address], target.workID == workID else {+ return .refused(.torn(recordID: targetID))+ }+ if let restoration, target.fingerprint != restoration.targetFingerprint {+ return .refused(.reRouted(to: nil))+ }+ if let refusal = Self.strictSourceRefusal(request, workRows: works, before: before) { return .refused(refusal) }+ for source in request.sourceAuthority {+ let text: String+ switch source.ref {+ case .genericNotes: text = work.carrier.genericNotes+ case .entry(let id): text = before.endpoints.sources[id]?.note ?? ""+ }+ guard !RecordMentionGrounding.evidence(names: target.names, in: text).isEmpty else {+ return .refused(.staleSource(source.ref))+ }+ guard let id = source.ref.entryID, let current = before.endpoints.sources[id], current.eligible else { continue }+ guard request.mentions.contains(where: { $0.entryID == id && $0.noteFingerprint == source.fingerprint }) else {+ return .refused(.staleSource(source.ref))+ }+ }+ for mention in request.mentions {+ guard mention.sourceGuard != nil,+ request.sourceAuthority.contains(where: { $0.ref == .entry(mention.entryID) && $0.fingerprint == mention.noteFingerprint }) else {+ return .refused(.staleSource(.entry(mention.entryID)))+ }+ let pair = AssociationPair(workID: workID, entryID: mention.entryID, kind: .character, recordID: targetID)+ let rejections = before.storage.ledger.rejectionIDs(pair: pair, spellingKeys: mention.spellingKeys)+ if restoration != nil {+ guard !rejections.isEmpty, Set(rejections) == Set(mention.observedRejectionIDs),+ mention.spellingKeys.allSatisfy({ before.storage.ledger.isSuppressed(pair: pair, spellingKey: $0) }) else {+ return .refused(.staleSource(.entry(mention.entryID)))+ }+ } else {+ guard Set(rejections) == Set(mention.observedRejectionIDs),+ !mention.spellingKeys.contains(where: { before.storage.ledger.isSuppressed(pair: pair, spellingKey: $0) }) else {+ return .refused(.staleSource(.entry(mention.entryID)))+ }+ }+ }+ if let refusal = Self.associationAcceptanceRefusal(request, before: before) { return .refused(refusal) }+ for captured in request.reviewAcknowledgements {+ guard captured.workID == workID,+ let source = before.endpoints.sources[captured.entryID] else {+ return .refused(.staleSource(.entry(captured.entryID)))+ }+ let guardValue = before.storage.ledger.sourceGuard(workID: workID, entryID: captured.entryID, sourceFingerprint: source.fingerprint)+ for reference in captured.references where reference.key == request.reviewedKey {+ let acceptedKeys = Set(request.mentions.filter { $0.entryID == captured.entryID }.flatMap(\.spellingKeys))+ guard before.storage.ledger.pendingReviews.markers[reference.markerID]?.contains(where: {+ $0.workID == workID && $0.entryID == captured.entryID && $0.sourceGuard == guardValue+ && $0.items.contains(where: { item in+ item.key == key && (item.targetID == nil || item.targetID == targetID)+ && Set(item.spellingKeys).isSubset(of: acceptedKeys)+ })+ }) == true else { return .refused(.staleSource(.entry(captured.entryID))) }+ }+ }+ let timestamp = MillisecondInstant.quantize(self.clock.now())+ var eventRequest = request+ if restoration == nil {+ eventRequest.mentions = request.mentions.map { mention in+ var value = mention; value.observedRejectionIDs = []; return value+ }+ }+ let events = Self.associationDecisionEvents(eventRequest, recordID: targetID, before: before)+ + Self.pendingReviewDecisionEvents(request, recordID: targetID, ledger: before.storage.ledger)+ var inserted: [(AssociationLedgerEvent, AssociationEvent)] = []+ for event in events {+ let row = try AssociationEvent(event: event, recordedAt: timestamp)+ context.insert(row); inserted.append((event, row))+ }+ let after = try before.finish(context: context, timestamp: timestamp, additionalEvents: events)+ for (event, row) in inserted {+ if case .accept(let core) = event.payload, let current = after.endpoints.current(core.pair) {+ row.validationData = try JSONBlob.encode(after.validationBasis.receipt(for: current))+ }+ }+ // Guarded provenance is not whole-source completion authority.+ // Non-chapter sources have no durable per-key marker; only the+ // coordinator's all-results-settled path may cover those revisions.+ let chapterSources = request.completedSources.filter { source in+ source.ref.entryID.flatMap { before.endpoints.sources[$0]?.eligible } == true+ }+ Self.writeCoverage(chapterSources, works: works)+ _ = try Self.writeAssociationCoverage(request.completedSources, workID: workID, works: works, context: context, timestamp: timestamp)+ do { try self.saveStrategy.save(context) }+ catch { context.rollback(); throw error }+ return .committed(recordID: targetID)+ }+ }++ static func strictSourceRefusal(_ request: DecisionRequest, workRows: [Work], before: AssociationMutation) -> DecisionRefusal? {+ for source in request.sourceAuthority {+ guard Self.strictlyHolds(source, works: workRows) else { return .staleSource(source.ref) }+ if let id = source.ref.entryID {+ guard let current = before.endpoints.sources[id], current.workID == request.workID,+ CharacterCoverageFingerprint.of(current.note) == source.fingerprint else { return .staleSource(source.ref) }+ }+ }+ return nil+ }+}+++/// Captured authority for an optional explicit restoration, never an automatic+/// reconsideration token. It addresses one chapter/character and observed spellings.+public struct SkippedCharacterLinkSnapshot: Sendable, Equatable, Identifiable {+ public var id: AssociationPair { pair }+ public let pair: AssociationPair+ public let recordName: String+ public let matchingName: String+ public let spellingKeys: [String]+ public let observedRejectionIDs: [UUID]+ public let noteFingerprint: String+ public let sourceGuard: String+ public let targetFingerprint: String++ public init(pair: AssociationPair, recordName: String, matchingName: String, spellingKeys: [String],+ observedRejectionIDs: [UUID], noteFingerprint: String, sourceGuard: String, targetFingerprint: String) {+ self.pair = pair; self.recordName = recordName; self.matchingName = matchingName+ self.spellingKeys = spellingKeys; self.observedRejectionIDs = observedRejectionIDs+ self.noteFingerprint = noteFingerprint; self.sourceGuard = sourceGuard; self.targetFingerprint = targetFingerprint+ }+}++extension LibraryRepository {+ public func skippedCharacterLinks(entryID: UUID) async throws -> [SkippedCharacterLinkSnapshot] {+ try await withLockedContext(mode: .shared, operation: "reading skipped character links") { context in+ let entries = try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { $0.id == entryID }))+ let workIDs = Set(entries.compactMap { $0.work?.id })+ let storage = try AssociationStorageInventory.read(context: context, workIDs: workIDs, includeNotes: false)+ let pairs = Set(storage.ledger.spellingDecisions.keys).filter { $0.entryID == entryID && $0.kind == .character }+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: pairs, entryIDs: [entryID])+ let ids = Array(workIDs)+ let works = try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { ids.contains($0.id) }))+ let recordsByWork = Dictionary(grouping: try CharacterRecord.rows(of: works, context: context), by: { $0.work?.id })+ return pairs.compactMap { pair -> SkippedCharacterLinkSnapshot? in+ guard let current = endpoints.current(pair), let target = endpoints.targets[.init(kind: .character, id: pair.recordID)],+ let source = endpoints.sources[entryID] else { return nil }+ let targets = Self.recordGroups(recordsByWork[pair.workID] ?? []).values.map(Self.matchTarget)+ guard let matchingName = target.names.first(where: {+ RecordMatching.recognition(nameKey: RecordNameKey.normalize($0), among: targets) == .unique(pair.recordID)+ }) else { return nil }+ let keys = current.evidence.map(\.key).filter { storage.ledger.isSuppressed(pair: pair, spellingKey: $0) }+ let rejections = storage.ledger.rejectionIDs(pair: pair, spellingKeys: keys)+ guard !keys.isEmpty, !rejections.isEmpty else { return nil }+ return .init(pair: pair, recordName: target.displayName, matchingName: matchingName, spellingKeys: keys,+ observedRejectionIDs: rejections, noteFingerprint: CharacterCoverageFingerprint.of(source.note),+ sourceGuard: storage.ledger.sourceGuard(workID: pair.workID, entryID: entryID, sourceFingerprint: source.fingerprint),+ targetFingerprint: target.fingerprint)+ }.sorted { [$0.recordName, $0.pair.recordID.uuidString].lexicographicallyPrecedes([$1.recordName, $1.pair.recordID.uuidString]) }+ }+ }++ public func restoreCharacterLink(_ captured: SkippedCharacterLinkSnapshot) async throws -> DecisionOutcome {+ guard captured.pair.kind == .character, !captured.spellingKeys.isEmpty, !captured.observedRejectionIDs.isEmpty else {+ throw LibraryRepositoryError.invalidInput(operation: "restoring a character link", reason: "invalid restoration authority")+ }+ let request = DecisionRequest(workID: captured.pair.workID, action: .accept,+ displayedKeys: captured.spellingKeys, displayedTargetID: captured.pair.recordID, proposedName: captured.matchingName,+ completedSources: [.init(ref: .entry(captured.pair.entryID), fingerprint: captured.noteFingerprint)],+ mentions: [.init(entryID: captured.pair.entryID, noteFingerprint: captured.noteFingerprint,+ spellingKeys: captured.spellingKeys, observedRejectionIDs: captured.observedRejectionIDs, sourceGuard: captured.sourceGuard)],+ reviewedKey: .init(kind: .character, nameKey: RecordNameKey.normalize(captured.matchingName)), requiresCurrentSources: true)+ return try await commitRecognisedCharacter(request, restoration: captured)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordCopy.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordCopy.swiftindex b7c86be7..c20d2d21 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordCopy.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordCopy.swift@@ -128,7 +128,8 @@ extension LibraryRepository { let groups = recordGroups(try Row.rows(ids: ids, context: context)) let index = StoryPositionIndex( entries: storyPositionInputs(rows: work.rows.flatMap(\.entryValues)))- return RecordRanking.rankGroups(groups, index: index).map { group in+ let chapterSupport = Row.kind == .character && !groups.isEmpty ? try characterChapterSupport(workID: work.id, context: context) : [:]+ return RecordRanking.rankGroups(groups, index: index, chapterSupport: chapterSupport).map { group in let content = group.presentedContent let keys = Set(group.rows.map(\.nameKey)) let validIdentity = group.rows.allSatisfy { $0.ownerWorkID == work.id } && keys.count == 1
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordEditing.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordEditing.swiftindex 1d117c39..5b474d75 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordEditing.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordEditing.swift@@ -245,6 +245,18 @@ extension LibraryRepository { placeSuppressions = try PlaceSuppression.rows(of: workRows, context: context) } + let selectedRecords = Set(operations.flatMap { operation -> [AssociationRecordAddress] in+ switch operation {+ case .create: return []+ case .update(let basis, _), .delete(let basis), .convert(let basis, _, _):+ return [.init(kind: basis.kind, id: basis.recordID)]+ case .combine(let source, let target):+ return [.init(kind: source.kind, id: source.recordID), .init(kind: target.kind, id: target.recordID)]+ }+ })+ let associationBefore = try AssociationMutation.capture(context: context, workIDs: [workID], records: selectedRecords)+ var associationRebinds: [AssociationRebindOperation] = []+ var additionalRecords: Set<AssociationRecordAddress> = [] let timestamp = MillisecondInstant.quantize(self.clock.now()) var written: [UUID] = [] // Q108: which records this step has already written to, per kind. A@@ -305,9 +317,25 @@ extension LibraryRepository { return .refused(refusal) case .committed(let ids): written += ids+ switch operation {+ case .combine(let source, let target):+ associationRebinds.append(.recordMerge(workID: workID, kind: source.kind,+ fromRecordID: source.recordID, toRecordID: target.recordID))+ case .convert(let basis, let kind, _):+ if let id = ids.last {+ associationRebinds.append(.conversion(workID: workID, fromKind: basis.kind,+ fromRecordID: basis.recordID, toRecordID: id))+ additionalRecords.insert(.init(kind: kind, id: id))+ }+ case .create(let draft):+ for id in ids { additionalRecords.insert(.init(kind: draft.kind, id: id)) }+ case .update, .delete: break+ } } } + try associationBefore.finish(context: context, timestamp: timestamp,+ rebinds: associationRebinds, additionalRecords: additionalRecords) try self.saveStrategy.save(context) return .committed(recordIDs: written) }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swiftindex ee45ac4a..8fe948a8 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordExtraction.swift@@ -87,6 +87,29 @@ extension LibraryRepository { : try PlaceSuppression.rows(of: works, context: context), by: \.workID) + let associationStorage = try AssociationStorageInventory.read(context: context,+ workIDs: Set(works.map(\.id)), includeNotes: false)+ let selectedEntries = Set(works.flatMap { $0.entryValues }.filter { !$0.note.isEmpty }.map(\.id))+ let selectedRecords = Set(charactersByWork.values.flatMap { $0 }.map {+ AssociationRecordAddress(kind: .character, id: $0.id)+ }).union(placesByWork.values.flatMap { $0 }.map { .init(kind: .place, id: $0.id) })+ let associationEndpoints = try AssociationEndpointInventory.read(context: context,+ pairs: associationStorage.ledger.pairs, entryIDs: selectedEntries, records: selectedRecords)+ var activePairsByWork: [UUID: Set<AssociationPair>] = [:]+ for pair in associationStorage.ledger.pairs {+ if let current = associationEndpoints.current(pair), !associationStorage.ledger.activeAcceptanceIDs(for: current).isEmpty {+ activePairsByWork[pair.workID, default: []].insert(pair)+ }+ }+ let decisionsByWork = Dictionary(grouping: associationStorage.ledger.spellingDecisions.map { ($0.key, $0.value) },+ by: { $0.0.workID }).mapValues { Dictionary(uniqueKeysWithValues: $0) }++ let ambiguousPendingSources = Self.ambiguousReviewSources(associationStorage)+ let coherentRecordsByWork = Dictionary(grouping: associationEndpoints.targets.values, by: \.workID)+ .mapValues { targets in+ Dictionary(grouping: targets, by: { $0.address.kind }).mapValues { Set($0.map { $0.address.id }) }+ }+ return Self.workGroups(works, types: types).values .compactMap { group -> ExtractionCandidate? in guard !group.isTorn else { return nil }@@ -95,7 +118,10 @@ extension LibraryRepository { characters: charactersByWork[group.id] ?? [], characterSuppressions: characterSuppressionsByWork[group.id] ?? [], places: placesByWork[group.id] ?? [],- placeSuppressions: placeSuppressionsByWork[group.id] ?? [])+ placeSuppressions: placeSuppressionsByWork[group.id] ?? [],+ ledger: associationStorage.ledger, activePairs: activePairsByWork[group.id, default: []],+ decisions: decisionsByWork[group.id, default: [:]], endpoints: associationEndpoints,+ coherentRecordIDs: coherentRecordsByWork[group.id, default: [:]], ambiguousPendingSources: ambiguousPendingSources) } // Newest activity first, UUID as the tie-break so two devices // examine the same works in the same order.@@ -114,12 +140,24 @@ extension LibraryRepository { characters: [CharacterRecord], characterSuppressions: [CharacterSuppression], places: [Place],- placeSuppressions: [PlaceSuppression]+ placeSuppressions: [PlaceSuppression],+ ledger: AssociationLedgerInventory, activePairs: Set<AssociationPair>,+ decisions: [AssociationPair: [String: AssociationSpellingDecision]], endpoints: AssociationEndpointInventory,+ coherentRecordIDs: [RecordKind: Set<UUID>], ambiguousPendingSources: Set<AssociationReviewSource> ) -> ExtractionCandidate? { let carrier = group.carrier let genericNotes = carrier.genericNotes var sources: [CharacterExtractionSource] = [] var recency = Date.distantPast+ let characterHalf = recordHalf(characters)+ let placeHalf = recordHalf(places)+ let records: [RecordKind: [MatchTarget]] = [.character: characterHalf.targets, .place: placeHalf.targets]+ let suppressions: [RecordKind: SuppressionIndex] = [+ .character: suppressionIndex(characterSuppressions), .place: suppressionIndex(placeSuppressions),+ ]+ let suppressedUnmatched = suppressedUnmatchedCandidateKeys(records: records, suppressions: suppressions)+ let directory = associationDirectoryDigest(workID: group.id, records: records, coherentRecordIDs: coherentRecordIDs)+ var eligibleEntries: Set<UUID> = [], eligibilityByEntry: [UUID: String] = [:] // Generic notes first — the display order Q88 pins, and the order the // sweep processes them in.@@ -129,7 +167,7 @@ extension LibraryRepository { ref: .genericNotes, text: genericNotes, fingerprint: CharacterCoverageFingerprint.of(genericNotes),- coveredFingerprint: carrier.genericNotesExtractionFingerprint))+ coveredFingerprint: carrier.genericNotesExtractionFingerprint, displayTitle: "Work note — no chapter")) // Q84: a generic-notes edit moves no entry timestamp, so the work's // own clock has to count or such a work never surfaces at all. recency = max(recency, group.modifiedAt)@@ -141,15 +179,37 @@ extension LibraryRepository { let noted = group.rows .flatMap { $0.entryValues } .filter { !$0.note.isEmpty && !($0.mergedIntoEntryID != nil && $0.isResolvedRedirect) }+ var sourceGuards: [UUID: String] = [:]+ var coverageBases: [UUID: String] = [:]+ var pendingReferences: [UUID: [AssociationReviewReference]] = [:] var seen: Set<UUID> = [] for entry in noted.sorted(by: { $0.firstCapturedAt < $1.firstCapturedAt }) where seen.insert(entry.id).inserted {+ let eligible = endpoints.sources[entry.id].map {+ $0.eligible && $0.workID == group.id && CharacterCoverageFingerprint.of($0.note) == CharacterCoverageFingerprint.of(entry.note)+ } ?? false+ let digest = eligible ? associationSourceDigest(entry: entry, workID: group.id, directory: directory, ledger: ledger) : nil+ let pending = Self.pendingMentionState(workID: group.id, entryID: entry.id, ledger: ledger,+ endpoints: endpoints, ambiguousSources: ambiguousPendingSources, suppressedUnmatchedKeys: suppressedUnmatched)+ pendingReferences[entry.id] = pending.references+ if let digest {+ coverageBases[entry.id] = ledger.coverageBaseDigest(workID: group.id, entryID: entry.id,+ sourceFingerprint: AssociationEndpointInventory.sourceFingerprint(entry), matchingDirectory: directory)+ eligibleEntries.insert(entry.id); eligibilityByEntry[entry.id] = digest+ sourceGuards[entry.id] = ledger.sourceGuard(workID: group.id, entryID: entry.id,+ sourceFingerprint: AssociationEndpointInventory.sourceFingerprint(entry))+ } sources.append( CharacterExtractionSource( ref: .entry(entry.id), text: entry.note, fingerprint: CharacterCoverageFingerprint.of(entry.note),- coveredFingerprint: entry.characterExtractionFingerprint))+ coveredFingerprint: entry.characterExtractionFingerprint,+ mentionEligibilityDigest: digest,+ coveredMentionEligibilityDigest: digest.flatMap {+ !pending.blocksCoverage && ledger.hasCoverage(workID: group.id, entryID: entry.id, digest: $0) ? $0 : nil+ }, displayTitle: entry.effectiveChapterTitle ?? entry.captureTitle, capturedAt: entry.firstCapturedAt,+ isChapter: eligible, stableOrder: sources.count)) // Q71: a note edit bumps `modifiedAt` and is exactly the event that // uncovers a revision; `lastSharedAt` covers a re-share. recency = max(recency, max(entry.modifiedAt, entry.lastSharedAt))@@ -157,21 +217,24 @@ extension LibraryRepository { guard !sources.isEmpty else { return nil } - let characterHalf = recordHalf(characters)- let placeHalf = recordHalf(places) return ExtractionCandidate( workID: group.id, displayTitle: carrier.displayTitle, recency: recency, sources: sources,- records: [.character: characterHalf.targets, .place: placeHalf.targets],+ records: [.character: characterHalf.targets.map { target in+ MatchTarget(id: target.id, currentNameKey: target.currentNameKey, retainedKey: target.retainedKey,+ aliasKeys: target.aliasKeys, isTorn: target.isTorn || !coherentRecordIDs[.character, default: []].contains(target.id))+ }, .place: placeHalf.targets], acceptedFacts: [ .character: characterHalf.accepted, .place: placeHalf.accepted, ], suppressions: [ .character: suppressionIndex(characterSuppressions), .place: suppressionIndex(placeSuppressions),- ])+ ], mentionIndex: .init(workID: group.id, eligibleEntries: eligibleEntries, eligibilityByEntry: eligibilityByEntry,+ activePairs: activePairs, decisions: decisions, sourceGuards: sourceGuards,+ coherentRecordIDs: coherentRecordIDs, coverageBases: coverageBases, pendingReviewReferences: pendingReferences)) } /// One kind's match targets and accepted fact triples, from its rows.@@ -306,7 +369,7 @@ extension LibraryRepository { return candidate.recordID.uuidString < current.recordID.uuidString } - private static func suppressionIndex<Row: SuppressionRow>(+ static func suppressionIndex<Row: SuppressionRow>( _ rows: [Row] ) -> SuppressionIndex { var candidateKeys: Set<String> = []@@ -352,16 +415,26 @@ extension LibraryRepository { let works = try context.fetch( FetchDescriptor<Work>(predicate: #Predicate { $0.id == workID })) guard !works.isEmpty else { return 0 }+ let entries = Dictionary(grouping: works.flatMap { $0.entryValues }, by: \.id)+ let legacyChanges = Set(sources.filter { source in+ guard Self.currentlyHolds(source, works: works) else { return false }+ switch source.ref {+ case .genericNotes: return works.contains { $0.genericNotesExtractionFingerprint != source.fingerprint }+ case .entry(let id): return entries[id, default: []].contains { $0.characterExtractionFingerprint != source.fingerprint }+ }+ }.map(\.ref)) let written = Self.writeCoverage(sources, works: works)- if written > 0 { try self.saveStrategy.save(context) }- return written+ let associationWrites = try Self.writeAssociationCoverage(sources, workID: workID, works: works,+ context: context, timestamp: MillisecondInstant.quantize(self.clock.now()))+ if written > 0 || !associationWrites.isEmpty { try self.saveStrategy.save(context) }+ return sources.contains { $0.mentionEligibilityDigest != nil } ? legacyChanges.union(associationWrites).count : written } } /// Writes coverage for the sources whose fingerprint still describes the /// text, across every row of the work group. @discardableResult- private static func writeCoverage(+ static func writeCoverage( _ sources: [CompletedSource], works: [Work] ) -> Int { guard !works.isEmpty else { return 0 }@@ -432,18 +505,25 @@ extension LibraryRepository { else { return .refused(.workGone) } let timestamp = MillisecondInstant.quantize(self.clock.now()) + let selectedRecords: Set<AssociationRecordAddress> = request.displayedTargetID.map { [.init(kind: request.kind, id: $0)] } ?? []+ let associationBefore = try AssociationMutation.capture(context: context, workIDs: [workID],+ entryIDs: Set(request.mentions.map(\.entryID)).union(request.requiresCurrentSources ? request.sourceAuthority.compactMap { $0.ref.entryID } : []), records: selectedRecords)+ if request.action == .accept, request.requiresCurrentSources,+ let refusal = Self.strictSourceRefusal(request, workRows: workRows, before: associationBefore) {+ return .refused(refusal)+ } let outcome: DecisionOutcome switch request.kind { case .character: outcome = try Self.apply( request, CharacterRecord.self, CharacterSuppression.self, workGroup: workGroup, workRows: workRows, timestamp: timestamp,- context: context)+ associationBefore: associationBefore, context: context) case .place: outcome = try Self.apply( request, Place.self, PlaceSuppression.self, workGroup: workGroup, workRows: workRows, timestamp: timestamp,- context: context)+ associationBefore: associationBefore, context: context) } // A refusal wrote nothing, so there is nothing to save and nothing // to cover: the gates all run before the first write.@@ -456,8 +536,25 @@ extension LibraryRepository { try Self.suppressUnderOtherKinds( request, workRows: workRows, timestamp: timestamp, context: context) + let recordID: UUID? = if case .committed(let id) = outcome { id } else { nil }+ let associationEvents = Self.associationDecisionEvents(request, recordID: recordID, before: associationBefore)+ + Self.pendingReviewDecisionEvents(request, recordID: recordID, ledger: associationBefore.storage.ledger)+ var insertedEvents: [(AssociationLedgerEvent, AssociationEvent)] = []+ for event in associationEvents {+ let row = try AssociationEvent(event: event, recordedAt: timestamp)+ context.insert(row); insertedEvents.append((event, row))+ }+ let additionalRecords: Set<AssociationRecordAddress> = recordID.map { [.init(kind: request.kind, id: $0)] } ?? []+ let associationAfter = try associationBefore.finish(context: context, timestamp: timestamp,+ additionalRecords: additionalRecords, additionalEvents: associationEvents)+ for (event, row) in insertedEvents {+ if case .accept(let core) = event.payload, let current = associationAfter.endpoints.current(core.pair) {+ row.validationData = try JSONBlob.encode(associationAfter.validationBasis.receipt(for: current))+ }+ } // Coverage rides the same save (Q65). Self.writeCoverage(request.completedSources, works: workRows)+ _ = try Self.writeAssociationCoverage(request.completedSources, workID: workID, works: workRows, context: context, timestamp: timestamp) try self.saveStrategy.save(context) return outcome }@@ -475,6 +572,7 @@ extension LibraryRepository { workGroup: WorkGroup, workRows: [Work], timestamp: Date,+ associationBefore: AssociationMutation, context: ModelContext ) throws -> DecisionOutcome { let records = try Row.rows(of: workRows, context: context)@@ -492,6 +590,7 @@ extension LibraryRepository { request, workGroup: workGroup, resolved: target, workRows: workRows) { return .refused(refusal) }+ if let refusal = associationAcceptanceRefusal(request, before: associationBefore) { return .refused(refusal) } committedID = applyAcceptance( request, target: target, workRows: workRows, suppressionRows: suppressionRows, timestamp: timestamp, context: context)@@ -564,7 +663,8 @@ extension LibraryRepository { workRows: [Work] ) -> DecisionRefusal? { if workGroup.isTorn { return .torn(recordID: nil) }- for source in request.completedSources where !currentlyHolds(source, works: workRows) {+ for source in request.requiresCurrentSources ? request.sourceAuthority : request.completedSources+ where !(request.requiresCurrentSources ? strictlyHolds(source, works: workRows) : currentlyHolds(source, works: workRows)) { return .staleSource(source.ref) } guard resolved?.id == request.displayedTargetID else {@@ -575,7 +675,7 @@ extension LibraryRepository { } /// Whether a cited revision still holds the text it was proposed from.- private static func currentlyHolds(+ static func currentlyHolds( _ source: CompletedSource, works: [Work] ) -> Bool { switch source.ref {@@ -596,6 +696,23 @@ extension LibraryRepository { } } + /// Strict transient names-only source authority; legacy fact citations retain their tolerance.+ static func strictlyHolds(_ source: CompletedSource, works: [Work]) -> Bool {+ switch source.ref {+ case .genericNotes:+ return !works.isEmpty && works.allSatisfy {+ CharacterCoverageFingerprint.of($0.genericNotes) == source.fingerprint+ }+ case .entry(let id):+ let entries = works.flatMap { $0.entryValues }.filter { $0.id == id }+ guard !entries.isEmpty, Set(entries.map(AssociationEndpointInventory.sourceFingerprint)).count == 1 else { return false }+ return entries.allSatisfy {+ !($0.mergedIntoEntryID != nil && $0.isResolvedRedirect)+ && CharacterCoverageFingerprint.of($0.note) == source.fingerprint+ }+ }+ }+ /// Req 2.3's tiers over the work's current records **of the request's /// kind**. ///
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordHistory.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordHistory.swiftnew file mode 100644index 00000000..912903d7--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordHistory.swift@@ -0,0 +1,118 @@+import Foundation+import SwiftData++struct RecordHistoryReadDiagnostics: Sendable {+ let eventFetchCount: Int+ let noteFetchCount: Int+ let endpointFetchCount: Int+ let ledgerFoldCount: Int+}++extension LibraryRepository {+ public func recordHistory(workID: UUID, kind: RecordKind, recordID: UUID) async throws -> RecordHistorySnapshot {+ try await withLockedContext(mode: .shared, operation: "reading record chapter history") { context in+ try Self.recordHistory(selection: .init(workID: workID, kind: kind, recordID: recordID), context: context).snapshot+ }+ }++ /// One Work fold and one globally complete endpoint batch; never a read per row.+ static func recordHistory(selection: RecordHistorySelection, context: ModelContext) throws+ -> (snapshot: RecordHistorySnapshot, diagnostics: RecordHistoryReadDiagnostics) {+ let workID = selection.workID+ let works = try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { $0.id == workID }))+ let group = Self.workGroup(id: workID, rows: works, types: try Self.workTypeDirectory(context: context))+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [workID])+ let pairs = storage.ledger.pairs.filter {+ $0.workID == workID && $0.kind == selection.kind && $0.recordID == selection.recordID+ }+ let address = AssociationRecordAddress(kind: selection.kind, id: selection.recordID)+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: pairs, records: [address])+ let diagnostics = RecordHistoryReadDiagnostics(eventFetchCount: storage.eventFetchCount,+ noteFetchCount: storage.noteFetchCount, endpointFetchCount: endpoints.endpointFetchCount, ledgerFoldCount: 1)+ var signatures = [workID.uuidString, selection.kind.rawValue, selection.recordID.uuidString,+ group == nil ? "work-missing" : group!.isTorn ? "work-torn" : "work-coherent"]+ signatures += storage.rawEvents.map(\.variantIdentity).sorted()+ signatures += storage.rawNotes.map(\.variantIdentity).sorted()+ signatures += endpoints.sourceStates.map { $0.key.uuidString + $0.value }.sorted()+ signatures += endpoints.targetStates.map { $0.key.kind.rawValue + $0.key.id.uuidString + $0.value }.sorted()++ let entryIDs = Array(Set(pairs.map(\.entryID)))+ let physicalEntries = entryIDs.isEmpty ? [] : try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { entryIDs.contains($0.id) }))+ let entries = try Self.entryGroups(physicalEntries, canonicalWorkIDs: [:]).values.map { try Self.snapshot($0) }+ .sorted(by: Self.entryActivityOrder)+ let chapterRows = WorkChapterRow.inChapterOrder(try Self.workChapterRows(entries, context: context))+ let labels = Dictionary(chapterRows.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })+ let potential = Dictionary(grouping: storage.rawEvents.compactMap { raw -> (AssociationPair, UUID)? in+ guard let event = raw.value, case .accept(let core) = event.payload,+ pairs.contains(core.pair), storage.ledger.canRevalidateAcceptance(event.id, pair: core.pair) else { return nil }+ return (core.pair, event.id)+ }, by: { $0.0 })+ let heads = Dictionary(grouping: storage.notes.allHeads, by: \.pair)+ var invalidNotes: Set<AssociationPair> = []+ var opaqueNotes = false+ for raw in storage.rawNotes where raw.value == nil || storage.notes.invalidIDs.contains(raw.id) {+ if let pair = try? JSONBlob.decode(AssociationPair.self, from: raw.originPairData) { invalidNotes.insert(pair) }+ else if raw.workID == workID { opaqueNotes = true }+ }+ var rowsByEntry: [UUID: RecordHistoryRow] = [:]+ var details: [RecordHistoryDetail] = []+ var unavailable: Set<UUID> = []+ var review = group?.isTorn == true || opaqueNotes+ let target = endpoints.targets[address]+ let targetAvailable = group != nil && target?.workID == workID+ if !targetAvailable { review = review || endpoints.targetStates[address] != nil || !pairs.isEmpty }+ let invalidEvent = storage.rawEvents.contains { raw in+ guard storage.ledger.invalidIDs.contains(raw.id) else { return false }+ return raw.workID == workID && (raw.recordID == nil || raw.recordID == selection.recordID)+ }+ review = review || invalidEvent+ for pair in pairs {+ guard let current = endpoints.current(pair) else {+ // Missing/torn endpoints cannot prove deliberate removal. A+ // coherent present source with no literal support can.+ if potential[pair] != nil {+ let source = endpoints.sources[pair.entryID]+ let knownInactive = source.map { $0.workID != workID || !$0.eligible } == true+ || (source != nil && target?.workID == workID+ && RecordMentionGrounding.evidence(names: target!.names, in: source!.note).isEmpty)+ if !knownInactive { unavailable.insert(pair.entryID); review = true }+ }+ continue+ }+ let ids = storage.ledger.activeAcceptanceIDs(for: current)+ guard !ids.isEmpty else {+ // Suppressed literal support is a known inactive state; an+ // unretired receipt that cannot validate is incomplete history.+ if potential[pair] != nil, !storage.ledger.receipt(for: current).evidence.isEmpty {+ unavailable.insert(pair.entryID); review = true+ }+ continue+ }+ guard let source = endpoints.sources[pair.entryID], let label = labels[pair.entryID] else {+ unavailable.insert(pair.entryID); review = true; continue+ }+ let activeHeads = heads[pair, default: []].filter { !Set($0.attachmentAcceptanceIDs).isDisjoint(with: ids) }+ .sorted { $0.id.uuidString < $1.id.uuidString }+ let noteInvalid = invalidNotes.contains(pair) || opaqueNotes+ review = review || noteInvalid+ let title = label.displayTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "Unnumbered chapter" : label.displayTitle+ let row = RecordHistoryRow(id: pair, displayTitle: title, chapterKey: label.gutterChapterKey,+ notedAt: label.lastSharedAt, sourcePreview: String(source.note.prefix(160)), sourceFingerprint: source.fingerprint,+ hasAnnotation: activeHeads.contains { !$0.text.isEmpty }, hasConflictingAnnotations: activeHeads.count > 1)+ rowsByEntry[pair.entryID] = row+ details.append(.init(pair: pair, sourceText: source.note, annotationHeads: activeHeads, annotationMetadataNeedsReview: noteInvalid))+ }+ // Preserve the shared spine order; signatures follow this same stable order.+ let rows = chapterRows.compactMap { rowsByEntry[$0.id] }+ for row in rows {+ let label = labels[row.id.entryID]!+ signatures += [row.id.entryID.uuidString, row.displayTitle, label.chapterKey?.label ?? "", label.sequencePosition?.label ?? "",+ String(label.lastSharedAt.timeIntervalSinceReferenceDate.bitPattern)]+ }+ let generation = AssociationDigest.of("association/record-history/v1", signatures)+ let status: RecordHistoryAvailability = !targetAvailable ? (review ? .reviewRequired : .unavailable) : review ? .reviewRequired : .available+ let incompleteMembership = !targetAvailable || group?.isTorn == true || invalidEvent || !unavailable.isEmpty+ return (.init(selection: selection, generation: generation, availability: status,+ activeChapterCount: incompleteMembership ? nil : rows.count, rows: rows, unavailableEntryIDs: unavailable, details: details), diagnostics)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordRanking.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordRanking.swiftnew file mode 100644index 00000000..ee10c5f1--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+RecordRanking.swift@@ -0,0 +1,24 @@+import Foundation+import SwiftData++extension LibraryRepository {+ /// Saved chapter membership for ranking, read once for a Work. Annotation+ /// bodies play no part. The endpoint batch reads every physical copy of+ /// each selected application UUID before trusting a current link.+ ///+ /// This narrowly supersedes character-ranking's original no-added-fetch+ /// promise: names-only extraction stores link evidence outside fact blobs.+ /// It does not mine a note to mint a link, and does not persist a score.+ static func characterChapterSupport(workID: UUID, context: ModelContext) throws -> [UUID: Set<UUID>] {+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [workID], includeNotes: false)+ let pairs = storage.ledger.pairs.filter { $0.workID == workID && $0.kind == .character }+ guard !pairs.isEmpty else { return [:] }+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: pairs)+ var support: [UUID: Set<UUID>] = [:]+ for pair in pairs {+ guard let current = endpoints.current(pair), !storage.ledger.activeAcceptanceIDs(for: current).isEmpty else { continue }+ support[pair.recordID, default: []].insert(pair.entryID)+ }+ return support+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swiftindex 57ae73ec..a4fbf1ca 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+ReparseCapture.swift@@ -159,6 +159,8 @@ extension LibraryRepository { } // 4. Apply — allocate IDs/time AFTER equality+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(group.rows.compactMap { $0.work?.id }), entryIDs: [group.id]) let timestamp = self.clock.now() let noteCalendar = self.noteCalendar() let beforeNoteFacts = Self.noteFacts(group, calendar: noteCalendar)@@ -220,6 +222,8 @@ extension LibraryRepository { } } + try associationBefore.finish(context: context, timestamp: timestamp)+ try Self.recordKnownChapterLinks(entryIDs: [group.id], context: context, timestamp: timestamp) do { try self.saveStrategy.save(context) } catch { throw LibraryRepositoryError.libraryUnavailable(@@ -472,6 +476,7 @@ extension LibraryRepository { after: NoEpisodeWriter.facts(rows: [entry], calendar: noteCalendar()), context: context) + try Self.recordKnownChapterLinks(entryIDs: [entry.id], context: context, timestamp: timestamp) do { try self.saveStrategy.save(context) } catch { // One capture's save failing is not the library going away@@ -641,11 +646,19 @@ extension LibraryRepository { // authored content comes off the carrier and its derived fields off the // representative, which is the split the seam states. let onHostname = try Self.hostnameWorks(hostname: hostname, context: context)- let siteWorks = Self.workGroups(- onHostname.works,- types: try Self.workTypeDirectory(context: context))- .values- .sorted { $0.id.uuidString < $1.id.uuidString }+ // Keep the directory fetch here even when all Works have one row:+ // its storage errors must still reach this basis read as before.+ let types = try Self.workTypeDirectory(context: context)+ var buckets: [UUID: [Work]] = [:]+ for row in onHostname.works { buckets[row.id, default: []].append(row) }+ let siteWorks = buckets.compactMap { id, rows -> (id: UUID, carrier: Work, representative: Work)? in+ // A sole physical row is necessarily both carrier and representative.+ // This basis never consumes the group's authored variants; constructing+ // them would fault primary membership and canonicalize unused content.+ if rows.count == 1 { return (id, rows[0], rows[0]) }+ guard let group = Self.workGroup(id: id, rows: rows, types: types) else { return nil }+ return (group.id, group.carrier, group.representative)+ }.sorted { $0.id.uuidString < $1.id.uuidString } let siteRules = site?.urlRuleValues ?? [] let worksBasis = siteWorks.map { group -> WorkBasisEntry in Self.workBasisEntry(
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+SaveTimeKnownLinks.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+SaveTimeKnownLinks.swiftnew file mode 100644index 00000000..f0d3d1ef--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+SaveTimeKnownLinks.swift@@ -0,0 +1,92 @@+import Foundation+import SwiftData++extension LibraryRepository {+ /// Called after existing association maintenance and before the caller's+ /// one Save. Final content/ownership and refreshed or retired receipts are+ /// read in this same locked context; no draft or model output is authority.+ @discardableResult+ static func recordKnownChapterLinks(entryIDs: Set<UUID>, context: ModelContext, timestamp: Date) throws -> Bool {+ guard !entryIDs.isEmpty else { return false }+ let sources = try AssociationEndpointInventory.read(context: context, pairs: [], entryIDs: entryIDs).sources.values+ .filter { $0.eligible && $0.workID != nil && !$0.note.isEmpty }+ let workIDs = Array(Set(sources.compactMap(\.workID)))+ guard !workIDs.isEmpty else { return false }+ let works = try context.fetch(FetchDescriptor<Work>(predicate: #Predicate { workIDs.contains($0.id) }))+ let groups = workGroups(works, types: try workTypeDirectory(context: context)).filter { !$0.value.isTorn }+ var candidates: [AssociationPair: Set<String>] = [:]+ for (workID, work) in groups {+ struct Directory {+ let targets: [MatchTarget]+ let names: [String]+ let claimedKeys: Set<String>+ }+ func directory<Row: RecordRow>(_ type: Row.Type) throws -> Directory {+ let scoped = try Row.rows(of: work.rows, context: context)+ let ids = Array(Set(scoped.map(\.recordID)))+ guard !ids.isEmpty else { return .init(targets: [], names: [], claimedKeys: []) }+ // Keep every observed physical spelling claim: a torn opposite+ // kind cannot confer literal kind authority by hiding a variant.+ let records = recordGroups(try Row.rows(ids: ids, context: context))+ let targets = records.values.flatMap { group -> [MatchTarget] in+ let target = matchTarget(group)+ guard target.isTorn || !group.rows.allSatisfy({ $0.ownerWorkID == workID }) else { return [target] }+ // Unsafe copies retain each observed claim at its actual+ // tier; a non-carrier winning claim must refuse inference.+ return group.rows.map { row in+ .init(id: target.id, currentNameKey: RecordNameKey.normalize(row.name), retainedKey: row.nameKey,+ aliasKeys: row.aliases.map(RecordNameKey.normalize), isTorn: true)+ }+ }+ let names = records.values.flatMap { $0.rows.flatMap { [$0.name, $0.nameKey] + $0.aliases } }+ return .init(targets: targets, names: names, claimedKeys: Set(names.map(RecordNameKey.normalize)))+ }+ let characters = try directory(CharacterRecord.self), places = try directory(Place.self)+ for source in sources where source.workID == workID {+ for evidence in RecordMentionGrounding.completeNameEvidence(names: characters.names + places.names, in: source.note) {+ let characterClaim = characters.claimedKeys.contains(evidence.key)+ let placeClaim = places.claimedKeys.contains(evidence.key)+ // Literal text supplies no character-versus-place authority.+ // Rejections are applied below, after this identity decision.+ guard characterClaim != placeClaim else { continue }+ let kind: RecordKind = characterClaim ? .character : .place+ let targets = characterClaim ? characters.targets : places.targets+ guard case .unique(let id) = RecordMatching.recognition(nameKey: evidence.key, among: targets) else { continue }+ let pair = AssociationPair(workID: workID, entryID: source.id, kind: kind, recordID: id)+ candidates[pair, default: []].insert(evidence.key)+ }+ }+ }+ guard !candidates.isEmpty else { return false }+ let storage = try AssociationStorageInventory.read(context: context, workIDs: Set(candidates.keys.map(\.workID)), includeNotes: false)+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: Set(candidates.keys))+ var wrote = false+ for pair in candidates.keys.sorted(by: { AssociationDigest.pairToken($0).lexicographicallyPrecedes(AssociationDigest.pairToken($1)) }) {+ guard let current = endpoints.current(pair), let source = endpoints.sources[pair.entryID] else { continue }+ let receipt = storage.ledger.receipt(for: current)+ let supported = candidates[pair, default: []].intersection(receipt.evidence.map(\.key))+ guard !supported.isEmpty else { continue }+ if storage.ledger.activeAcceptanceIDs(for: current).isEmpty {+ let event = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: Array(supported))), validation: receipt)+ context.insert(try AssociationEvent(event: event, recordedAt: timestamp)); wrote = true+ }+ let guardValue = storage.ledger.sourceGuard(workID: pair.workID, entryID: pair.entryID, sourceFingerprint: source.fingerprint)+ var references: [AssociationReviewReference] = []+ let reviewSource = AssociationReviewSource(workID: pair.workID, entryID: pair.entryID)+ for (markerID, marker) in storage.ledger.pendingReviews.markersBySource[reviewSource, default: []]+ where !storage.ledger.pendingReviews.invalidIDs.contains(markerID) && marker.sourceGuard == guardValue {+ for item in marker.items where item.key.kind == pair.kind && item.targetID == pair.recordID+ && supported.contains(item.key.nameKey) && Set(item.spellingKeys).isSubset(of: supported) {+ let reference = AssociationReviewReference(markerID: markerID, key: item.key)+ if !storage.ledger.pendingReviews.isAcknowledged(reference) { references.append(reference) }+ }+ }+ if !references.isEmpty {+ context.insert(try AssociationEvent(event: .init(payload: .reviewAcknowledgement(.init(workID: pair.workID,+ entryID: pair.entryID, references: references, outcome: .kept(kind: pair.kind, recordID: pair.recordID)))), recordedAt: timestamp))+ wrote = true+ }+ }+ return wrote+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swiftindex ba929ebb..54218ab4 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkDetail.swift@@ -169,6 +169,38 @@ public struct WorkDetailPresentation: Sendable, Equatable { extension LibraryRepository { + /// Shared labels and spine metadata, without loading records/facts/credits.+ static func workChapterRows(_ entries: [EntrySnapshot], context: ModelContext) throws -> [WorkChapterRow] {+ var sites = SiteLookupCache()+ return try entries.map { entry in+ // Req 8.12's chapter resolution, as Recent and entry detail+ // resolve it: the chapter title, else the URL-rule-derived+ // sequence — a chapter the rule numbered but did not name is+ // still a parsed chapter — else the cleaned capture title.+ let displayTitle = try entry.authoredNoteTitle ?? entry.chapterTitle ?? entry.chapterSequence+ ?? Self.displayTitle(+ for: entry.captureTitle, hostname: entry.hostname, sites: &sites,+ context: context)+ // Derived here rather than in the row that draws it, for the+ // reason the title is: the spine's order and the citation+ // gutter both read this number, and two derivations of it would+ // be two answers.+ let chapterKey = ChapterKeyDerivation.key(+ chapterSequence: entry.chapterSequence, chapterTitle: entry.chapterTitle)+ return WorkChapterRow(+ id: entry.id,+ displayTitle: displayTitle,+ note: entry.note,+ rating: entry.rating,+ lastSharedAt: entry.lastSharedAt,+ chapterKey: chapterKey,+ sequencePosition: ChapterKeyDerivation.position(+ chapterSequence: entry.chapterSequence),+ showsTitle: entry.authoredTarget?.kind != .note || entry.authoredTarget?.title != nil,+ authoredTarget: entry.authoredTarget)+ }+ }+ public func workDetail(id: UUID) async throws -> WorkDetailPresentation { try await withLockedContext(mode: .shared, operation: "reading Work detail") { context in // One directory for the whole read: the convenience@@ -210,34 +242,7 @@ extension LibraryRepository { // and the open-last-noted answer (5.3). let entries = work.entries - var sites = SiteLookupCache()- let rows = try entries.map { entry in- // Req 8.12's chapter resolution, as Recent and entry detail- // resolve it: the chapter title, else the URL-rule-derived- // sequence — a chapter the rule numbered but did not name is- // still a parsed chapter — else the cleaned capture title.- let displayTitle = try entry.authoredNoteTitle ?? entry.chapterTitle ?? entry.chapterSequence- ?? Self.displayTitle(- for: entry.captureTitle, hostname: entry.hostname, sites: &sites,- context: context)- // Derived here rather than in the row that draws it, for the- // reason the title is: the spine's order and the citation- // gutter both read this number, and two derivations of it would- // be two answers.- let chapterKey = ChapterKeyDerivation.key(- chapterSequence: entry.chapterSequence, chapterTitle: entry.chapterTitle)- return WorkChapterRow(- id: entry.id,- displayTitle: displayTitle,- note: entry.note,- rating: entry.rating,- lastSharedAt: entry.lastSharedAt,- chapterKey: chapterKey,- sequencePosition: ChapterKeyDerivation.position(- chapterSequence: entry.chapterSequence),- showsTitle: entry.authoredTarget?.kind != .note || entry.authoredTarget?.title != nil,- authoredTarget: entry.authoredTarget)- }+ let rows = try Self.workChapterRows(entries, context: context) // Q88's two inputs, from this same context: where each live entry // falls in capture order (oldest first, so a character's facts read@@ -308,6 +313,8 @@ extension LibraryRepository { // of what a tolerated orphan does (Req 5.5). let placeRows = try Place.rows(of: group.rows, context: context) + let chapterSupport = characterRows.isEmpty ? [:] : try Self.characterChapterSupport(workID: id, context: context)+ // Req 8.1's section, through the one derivation the export and the // merge basis also read (`+WorkLinks.linkSnapshots`). let links = try Self.linkSnapshots(of: id, context: context, types: types)@@ -322,7 +329,7 @@ extension LibraryRepository { chapterRows: rows, characters: Self.recordPresentations( Self.recordGroups(characterRows), index: storyPositions,- captureOrder: captureOrder, titles: titles, dates: dates, keys: keys),+ captureOrder: captureOrder, titles: titles, dates: dates, keys: keys, chapterSupport: chapterSupport), // The same derivation over the other table, ranked separately: // ranking the two lists independently is what keeps each list's // order meaningful (`place-extraction` Q14).
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swiftindex 0283161d..82a910f4 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository+WorkMerge.swift@@ -274,9 +274,14 @@ extension LibraryRepository { private static func moveCharacters( from source: WorkGroup, to target: WorkGroup, timestamp: Date ) {- guard let survivor = target.rows.first else { return }+ moveCharacters(from: source.rows, to: target.rows, timestamp: timestamp)+ }++ /// The same verified ownership transition serves silent Work convergence.+ static func moveCharacters(from source: [Work], to target: [Work], timestamp: Date) {+ guard let survivor = target.first else { return } var moved: [CharacterRecord] = []- for row in source.rows {+ for row in source { for character in row.characterValues { character.work = survivor moved.append(character)@@ -286,10 +291,10 @@ extension LibraryRepository { } } recanonicaliseGenericNotesCitations(of: moved, timestamp: timestamp)- for row in target.rows {+ for row in target { row.genericNotesExtractionFingerprint = nil }- for entry in target.rows.flatMap({ $0.entryValues }) {+ for entry in target.flatMap({ $0.entryValues }) { entry.characterExtractionFingerprint = nil } }@@ -306,13 +311,17 @@ extension LibraryRepository { private static func movePlaces( from source: WorkGroup, to target: WorkGroup, timestamp: Date, context: ModelContext ) throws {- guard let survivor = target.rows.first else { return }- let moved = try Place.rows(of: source.rows, context: context)- for row in moved { row.workID = survivor.id }- for row in try PlaceSuppression.rows(of: source.rows, context: context) {- row.workID = survivor.id- }- recanonicaliseGenericNotesCitations(of: moved, timestamp: timestamp)+ movePlaces(rows: try Place.rows(of: source.rows, context: context),+ suppressions: try PlaceSuppression.rows(of: source.rows, context: context),+ to: target.rows, timestamp: timestamp)+ }++ /// Callers already own their bounded save-chunk rows; no per-Work query.+ static func movePlaces(rows: [Place], suppressions: [PlaceSuppression], to target: [Work], timestamp: Date) {+ guard let survivor = target.first else { return }+ for row in rows { row.workID = survivor.id }+ for row in suppressions { row.workID = survivor.id }+ recanonicaliseGenericNotesCitations(of: rows, timestamp: timestamp) } /// The third of `moveCharacters`' three writes, over any record table.@@ -515,6 +524,12 @@ extension LibraryRepository { // cross-site merge moves Entries on sites the source is on and the // target is not, and a hostname-scoped fetch would silently leave // them behind — attached to a Work that is about to be deleted.+ let associationEntries = sourceGroup.rows.flatMap { $0.entryValues }+ let associationRecords = Set(sourceGroup.rows.flatMap { $0.characterValues }.map {+ AssociationRecordAddress(kind: .character, id: $0.id)+ }).union(try Place.rows(of: sourceGroup.rows, context: context).map { .init(kind: .place, id: $0.id) })+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: [sourceID, targetID], entryIDs: Set(associationEntries.map(\.id)), records: associationRecords, allPairs: true) let sourceEntries = sourceGroup.rows.flatMap { $0.entryValues } let noteCalendar = self.noteCalendar() let beforeNoteFacts = Set(sourceEntries.compactMap { entry -> NoEpisodeWriter.NoteFact? in@@ -678,6 +693,9 @@ extension LibraryRepository { // entirely or not at all, and a proper subset left behind is the // partial merge the old refusal was avoiding. for row in sourceGroup.rows { context.delete(row) }+ try associationBefore.finish(context: context, timestamp: timestamp,+ rebinds: [.workMerge(fromWorkID: sourceID, toWorkID: targetID)])+ // Validate the prospective graph, then save once. Merge is the // highest-risk mutation (Work deletion plus bulk reassignment); an
diff --git a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swiftindex f8acb45f..7c12fbb3 100644--- a/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/LibraryRepository.swift@@ -18,10 +18,13 @@ public struct LibraryRecordCounts: Equatable, Sendable { /// meaning zero. public let workTypes: Int public let entrySources: Int+ public let associationEvents: Int+ public let pairNoteVersions: Int public init( entries: Int, works: Int, sites: Int, titlePatterns: Int,- urlRulePatterns: Int = 0, workTypes: Int = 0, entrySources: Int = 0+ urlRulePatterns: Int = 0, workTypes: Int = 0, entrySources: Int = 0,+ associationEvents: Int = 0, pairNoteVersions: Int = 0 ) { self.entries = entries self.works = works@@ -29,6 +32,7 @@ public struct LibraryRecordCounts: Equatable, Sendable { self.titlePatterns = titlePatterns self.urlRulePatterns = urlRulePatterns self.entrySources = entrySources+ self.associationEvents = associationEvents; self.pairNoteVersions = pairNoteVersions self.workTypes = workTypes } @@ -45,6 +49,7 @@ public struct LibraryRecordCounts: Equatable, Sendable { /// exists to keep open. public var holdsNoReaderRecords: Bool { entries == 0 && works == 0 && sites == 0 && titlePatterns == 0 && urlRulePatterns == 0 && entrySources == 0+ && associationEvents == 0 && pairNoteVersions == 0 } } @@ -1020,7 +1025,9 @@ public actor LibraryRepository { titlePatterns: context.fetchCount(FetchDescriptor<TitlePattern>()), urlRulePatterns: context.fetchCount(FetchDescriptor<URLRulePattern>()), workTypes: context.fetchCount(FetchDescriptor<WorkTypeEntity>()),- entrySources: context.fetchCount(FetchDescriptor<EntrySource>())+ entrySources: context.fetchCount(FetchDescriptor<EntrySource>()),+ associationEvents: context.fetchCount(FetchDescriptor<AssociationEvent>()),+ pairNoteVersions: context.fetchCount(FetchDescriptor<PairNoteVersion>()) ) } @@ -1115,6 +1122,8 @@ public actor LibraryRepository { } if let refusal = Self.tornRefusal(group) { return refusal } + let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(group.rows.compactMap { $0.work?.id }), entryIDs: [group.id]) let calendar = noteCalendar() let before = Self.noteFacts(group, calendar: calendar) @@ -1126,6 +1135,8 @@ public actor LibraryRepository { } try NoEpisodeWriter.recordNoteTransition( before: before, after: Self.noteFacts(group, calendar: calendar), context: context)+ try associationBefore.finish(context: context, timestamp: timestamp)+ try Self.recordKnownChapterLinks(entryIDs: [group.id], context: context, timestamp: timestamp) do { try saveStrategy.save(context) } catch { throw LibraryRepositoryError.libraryUnavailable(@@ -1197,6 +1208,8 @@ public actor LibraryRepository { _ = try? context.fetch(FetchDescriptor<NoEpisodeAction>()) } }+ let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(group.rows.compactMap { $0.work?.id }), entryIDs: Set(ownedGroups.map(\.id))) let calendar = noteCalendar() try NoEpisodeWriter.recordNoteTransition( before: Self.noteFacts(group, calendar: calendar), after: [], context: context)@@ -1215,6 +1228,7 @@ public actor LibraryRepository { row.modifiedAt = timestamp } }+ try associationBefore.finish(context: context, timestamp: timestamp) do { try saveStrategy.save(context) } catch { throw LibraryRepositoryError.libraryUnavailable(@@ -1697,6 +1711,8 @@ public actor LibraryRepository { }.flatMap(\.rows) let cleanRedirectRows = Set(affectedRows.filter(\.isResolvedRedirect).map(ObjectIdentifier.init)) + let associationBefore = try AssociationMutation.capture(context: context,+ workIDs: Set(affectedRows.compactMap { $0.work?.id }), entryIDs: Set(affectedRows.map(\.id))) let calendar = noteCalendar() let before = Self.noteFacts(group, calendar: calendar) @@ -1793,6 +1809,8 @@ public actor LibraryRepository { } try NoEpisodeWriter.recordNoteTransition( before: before, after: Self.noteFacts(group, calendar: calendar), context: context)+ try associationBefore.finish(context: context, timestamp: timestamp)+ try Self.recordKnownChapterLinks(entryIDs: [group.id], context: context, timestamp: timestamp) do { try saveStrategy.save(context) } catch { throw LibraryRepositoryError.libraryUnavailable(@@ -1936,7 +1954,10 @@ public actor LibraryRepository { // normal permanent state (Q32), and the reader is being shown how // many types the library holds. workTypes: Self.distinctIdentityCount(- FetchDescriptor<WorkTypeEntity>(), context: context, id: \.id)+ FetchDescriptor<WorkTypeEntity>(), context: context, id: \.id),+ entrySources: Self.distinctIdentityCount(FetchDescriptor<EntrySource>(), context: context, id: \.id),+ associationEvents: Self.distinctIdentityCount(FetchDescriptor<AssociationEvent>(), context: context, id: \.id),+ pairNoteVersions: Self.distinctIdentityCount(FetchDescriptor<PairNoteVersion>(), context: context, id: \.id) ) } }
diff --git a/Packages/AsterismCore/Sources/AsterismCore/Models.swift b/Packages/AsterismCore/Sources/AsterismCore/Models.swiftindex 602bd748..5fcc4dd6 100644--- a/Packages/AsterismCore/Sources/AsterismCore/Models.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/Models.swift@@ -1,7 +1,7 @@ import Foundation import SwiftData -// The live model classes are V20's, nested inside `AsterismSchemaV20`+// The live model classes are V21's, nested inside `AsterismSchemaV21` // (Decision 6, Q20). Top-level typealiases keep every call site (`Entry`, // `Site`, …) unchanged. //@@ -11,51 +11,51 @@ import SwiftData // *top-level* `@Model` per entity name — and there are none, because every // top-level name here is a typealias. Two top-level `@Model`s sharing an entity // name crash `ModelContext` (`docs/agent-notes/schema-migration.md`).-public typealias Entry = AsterismSchemaV20.Entry-public typealias Work = AsterismSchemaV20.Work-public typealias Site = AsterismSchemaV20.Site-public typealias TitlePattern = AsterismSchemaV20.TitlePattern-public typealias URLRulePattern = AsterismSchemaV20.URLRulePattern-public typealias WorkTypeEntity = AsterismSchemaV20.WorkTypeEntity+public typealias Entry = AsterismSchemaV21.Entry+public typealias Work = AsterismSchemaV21.Work+public typealias Site = AsterismSchemaV21.Site+public typealias TitlePattern = AsterismSchemaV21.TitlePattern+public typealias URLRulePattern = AsterismSchemaV21.URLRulePattern+public typealias WorkTypeEntity = AsterismSchemaV21.WorkTypeEntity /// V8: a Work's presence on one site (Q3). One row per hostname, carrying that /// site's URL identity, the rule that derived it and the confirmed Work URL — /// and since V9 the only home any of them has.-public typealias WorkSiteMembership = AsterismSchemaV20.WorkSiteMembership+public typealias WorkSiteMembership = AsterismSchemaV21.WorkSiteMembership /// V8: a reader's "not the same work" over an unordered pair of Works (Q20).-public typealias WorkDistinctPair = AsterismSchemaV20.WorkDistinctPair+public typealias WorkDistinctPair = AsterismSchemaV21.WorkDistinctPair /// V11: a reader-named, ordered collection a Work belongs to at most once /// (`series-and-related-works` Decision 1).-public typealias Series = AsterismSchemaV20.Series+public typealias Series = AsterismSchemaV21.Series /// V11: an undirected, typed connection between two distinct Works /// (`series-and-related-works` Decision 5).-public typealias WorkLink = AsterismSchemaV20.WorkLink+public typealias WorkLink = AsterismSchemaV21.WorkLink /// V12: a person a work is credited to, a reader-managed directory record /// (`work-creators` Decision 2).-public typealias Creator = AsterismSchemaV20.Creator+public typealias Creator = AsterismSchemaV21.Creator /// V12: one entry in the ordered role list credits reference by identity /// (`work-creators` Decision 1).-public typealias CreatorRole = AsterismSchemaV20.CreatorRole+public typealias CreatorRole = AsterismSchemaV21.CreatorRole /// V12: one work-and-creator pairing, carrying the roles that creator holds on /// that work (`work-creators` Decision 6).-public typealias WorkCredit = AsterismSchemaV20.WorkCredit+public typealias WorkCredit = AsterismSchemaV21.WorkCredit // `Character` is deliberately **not** aliased at the top level: the stdlib owns // that name, and shadowing it module-wide would silently retype every // `[Character]` in `MarkdownExport` and `HTMLEntityDecoder` — and every one a // future file writes. The SwiftData entity is still named "Character" (that is // the nested class's name, and what the CloudKit record type and the archive // key on); only the Swift spelling call sites use is qualified.-public typealias CharacterRecord = AsterismSchemaV20.Character-public typealias CharacterSuppression = AsterismSchemaV20.CharacterSuppression+public typealias CharacterRecord = AsterismSchemaV21.Character+public typealias CharacterSuppression = AsterismSchemaV21.CharacterSuppression /// V13: one named location of one work, the second `RecordRow` table /// (`place-extraction` Decision 3). Unlike `Character` the name collides with /// nothing in the stdlib, so it is aliased at the top level under its own name.-public typealias Place = AsterismSchemaV20.Place+public typealias Place = AsterismSchemaV21.Place /// V13: a place's remembered decision not to re-propose, its own record type /// rather than a column on `CharacterSuppression` (`place-extraction` /// Decision 2).-public typealias PlaceSuppression = AsterismSchemaV20.PlaceSuppression-public typealias EntrySource = AsterismSchemaV20.EntrySource-public typealias NoEpisodeAction = AsterismSchemaV20.NoEpisodeAction+public typealias PlaceSuppression = AsterismSchemaV21.PlaceSuppression+public typealias EntrySource = AsterismSchemaV21.EntrySource+public typealias NoEpisodeAction = AsterismSchemaV21.NoEpisodeAction /// The presentation-enum tolerance policy for the **model accessors**, in one /// place (Q2).@@ -137,7 +137,7 @@ enum JSONBlob { } } -extension AsterismSchemaV20 {+extension AsterismSchemaV21 { @Model public final class Entry {@@ -1770,7 +1770,7 @@ public final class PlaceSuppression { } } -} // extension AsterismSchemaV20+} // extension AsterismSchemaV21 /// A rule-derived URL identity a creation site already holds, passed through /// `Work.create` so the minted membership is born carrying it (Req 1.3, 3.1).
diff --git a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swiftindex a06ccc08..1f19dd66 100644--- a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeHistory.swift@@ -59,7 +59,13 @@ public struct NoEpisodeHistory: Equatable, Sendable { } public static func decode(_ data: Data, workID: UUID) throws -> Self {- let wire = try JSONDecoder().decode(Wire.self, from: data)+ try decode(data, workID: workID, decoder: JSONDecoder())+ }++ // One serial decoding operation may reuse its decoder; every physical+ // payload still runs the same wire, version and action validation.+ static func decode(_ data: Data, workID: UUID, decoder: JSONDecoder) throws -> Self {+ let wire = try decoder.decode(Wire.self, from: data) guard wire.version == 1 else { throw HistoryError.invalidVersion(wire.version) } return try Self(workID: workID, key: wire.key, day: wire.day, kind: wire.kind, observedClearKeys: wire.observedClearKeys)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeIndex.swift b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeIndex.swiftindex da146d5e..34adfc1e 100644--- a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeIndex.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeIndex.swift@@ -8,6 +8,10 @@ public struct NoEpisodeIndex { public init(context: ModelContext) throws { let rows = try context.fetch(FetchDescriptor<NoEpisodeAction>())+ self.init(rows: rows)+ }++ fileprivate init(rows: [NoEpisodeAction]) { rowsByWorkID = Dictionary(grouping: rows, by: \.workID) } @@ -34,3 +38,21 @@ public struct NoEpisodeIndex { } } }++/// Read-only inventory for an explicitly selected set of current Work owners.+/// No allActions surface: this subset must never supply a global writer.+/// Payload validation remains lazy and unchanged in NoEpisodeIndex.history.+struct SelectedWorkNoEpisodeReader {+ private let index: NoEpisodeIndex++ init(context: ModelContext, workIDs: Set<UUID>) throws {+ let ids = Array(workIDs)+ let rows = ids.isEmpty ? [] : try context.fetch(+ FetchDescriptor<NoEpisodeAction>(predicate: #Predicate { ids.contains($0.workID) }))+ index = NoEpisodeIndex(rows: rows)+ }++ func history(for workID: UUID) throws -> NoEpisodeHistory {+ try index.history(for: workID)+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swift b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swiftindex b73a85cd..9bb3ab36 100644--- a/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/NoEpisodeWriter.swift@@ -60,66 +60,165 @@ public enum NoEpisodeWriter { public static func recordNoteTransition( before: Set<NoteFact>, after: Set<NoteFact>, context: ModelContext ) throws -> Bool {- guard !before.isEmpty || !after.isEmpty else { return false }- let index = try NoEpisodeIndex(context: context)- let existing = Dictionary(grouping: try index.allActions) {- ActionKey(workID: $0.workID, key: $0.key)+ try HistorySession(context: context).record(before: before, after: after)+ }++ /// Explicitly owned by ONE caller save chunk. Never retained across a save,+ /// rollback or refault, and never stored on a repository/context. Other+ /// writers must invalidate before using this view again.+ final class HistorySession {+ private let context: ModelContext+ private let fetchRows: (ModelContext) throws -> [NoEpisodeAction]+ private let rawWorkID: (NoEpisodeAction) -> UUID+ private var rawRowsByWorkID: [UUID: [NoEpisodeAction]]?+ private var rawRows: [NoEpisodeAction]?+ private var histories: [UUID: NoEpisodeHistory]?+ private var actionsByKey: [ActionKey: NoEpisodeHistory.Action] = [:]++ init(context: ModelContext,+ fetchRows: @escaping (ModelContext) throws -> [NoEpisodeAction] = {+ try $0.fetch(FetchDescriptor<NoEpisodeAction>())+ },+ rawWorkID: @escaping (NoEpisodeAction) -> UUID = { $0.workID }) {+ self.context = context+ self.fetchRows = fetchRows+ self.rawWorkID = rawWorkID }- var actions: [NoEpisodeHistory.Action] = []- let facts = before.union(after)- for fact in facts {- let key = ActionKey(workID: fact.workID, key: fact.stableKey)- if let stored = existing[key]?.first {- guard stored.kind == .clear && stored.day == fact.day.description else {- throw NoEpisodeHistory.HistoryError.conflictingAction(fact.workID, fact.stableKey)- }- continue++ /// External mutations can add/delete physical copies, so discard raw+ /// inventory as well as decoded values. Own inserts are tracked below.+ func invalidate() {+ rawRows = nil+ rawRowsByWorkID = nil+ histories = nil+ actionsByKey = [:]+ }++ /// Match the existing Work-deletion writer: raw moves do NOT decode or+ /// validate histories. Even an empty transition followed by this move+ /// must retain that boundary. The next nonempty transition revalidates+ /// globally, regrouping by the rows' CURRENT Work IDs.+ func repointActions(from workIDs: Set<UUID>, to target: UUID) throws {+ try loadRawRows()+ if rawRowsByWorkID == nil {+ rawRowsByWorkID = Dictionary(grouping: rawRows!, by: rawWorkID) }- actions.append(try .init(workID: fact.workID, key: fact.stableKey,- day: fact.day.description, kind: .clear,- observedClearKeys: []))+ for source in workIDs where source != target {+ guard let rows = rawRowsByWorkID!.removeValue(forKey: source) else { continue }+ for row in rows { row.workID = target }+ rawRowsByWorkID![target, default: []].append(contentsOf: rows)+ }+ histories = nil+ actionsByKey = [:] }- // A mark can have acknowledged the stable key. Clear that overlap before- // a note leaves, so deleting or moving it never revives the mark.- let beforeByScope = Dictionary(grouping: before) {- Scope(workID: $0.workID, day: $0.day.description)++ private func loadRawRows() throws {+ guard rawRows == nil else { return }+ rawRows = try fetchRows(context) }- for (scope, scopedFacts) in beforeByScope {- let history = try index.history(for: scope.workID)- var clears = history.clearKeys(workID: scope.workID, day: scope.day)- clears.formUnion(scopedFacts.map(\.stableKey))- if history.actions.contains(where: {- $0.day == scope.day && $0.kind == .mark- && clears.isSubset(of: Set($0.observedClearKeys))- }) {- actions.append(try .init(workID: scope.workID, key: "clear/\(UUID().uuidString)",- day: scope.day, kind: .clear, observedClearKeys: []))++ private func loadHistories() throws {+ guard histories == nil else { return }+ try loadRawRows()+ let decoder = JSONDecoder()+ var loaded: [UUID: NoEpisodeHistory] = [:]+ var keys: [ActionKey: NoEpisodeHistory.Action] = [:]+ for (workID, rows) in Dictionary(grouping: rawRows!, by: \.workID) {+ let actions = try rows.map { row in+ let action = try NoEpisodeHistory.Action.decode(row.payloadData, workID: row.workID, decoder: decoder)+ guard action.key == row.key else { throw NoEpisodeHistory.HistoryError.invalidPayload }+ return action+ }+ let history = try NoEpisodeHistory(actions)+ loaded[workID] = history+ for action in history.actions {+ keys[ActionKey(workID: workID, key: action.key)] = action+ } }+ // No partially validated global history can authorize an insertion.+ histories = loaded+ actionsByKey = keys }- let priorAssignments = Set(before.map {- NoteAssignment(entryID: $0.entryID, workID: $0.workID, day: $0.day)- })- for fact in after where !priorAssignments.contains(- NoteAssignment(entryID: fact.entryID, workID: fact.workID, day: fact.day)) {- actions.append(try .init(workID: fact.workID, key: "clear/\(UUID().uuidString)",- day: fact.day.description, kind: .clear,- observedClearKeys: []))- }- // The common unchanged pass has all stable keys and no overlap. It- // must not re-fetch and decode the action table a second time.- guard !actions.isEmpty else { return false }- for action in actions {- let key = ActionKey(workID: action.workID, key: action.key)- if let prior = existing[key]?.first {- guard prior == action else {- throw NoEpisodeHistory.HistoryError.conflictingAction(action.workID, action.key)++ @discardableResult+ func record(before: Set<NoteFact>, after: Set<NoteFact>) throws -> Bool {+ guard !before.isEmpty || !after.isEmpty else { return false }+ try loadHistories()+ var actions: [NoEpisodeHistory.Action] = []+ let facts = before.union(after)+ for fact in facts {+ let key = ActionKey(workID: fact.workID, key: fact.stableKey)+ if let stored = actionsByKey[key] {+ guard stored.kind == .clear && stored.day == fact.day.description else {+ throw NoEpisodeHistory.HistoryError.conflictingAction(fact.workID, fact.stableKey)+ }+ continue }- continue+ actions.append(try .init(workID: fact.workID, key: fact.stableKey,+ day: fact.day.description, kind: .clear,+ observedClearKeys: [])) }- context.insert(NoEpisodeAction(workID: action.workID, key: action.key,- payloadData: try action.canonicalData()))+ // A mark can have acknowledged the stable key. Clear that overlap before+ // a note leaves, so deleting or moving it never revives the mark.+ let beforeByScope = Dictionary(grouping: before) {+ Scope(workID: $0.workID, day: $0.day.description)+ }+ for (scope, scopedFacts) in beforeByScope {+ let history = histories![scope.workID] ?? .empty+ // Histories were fully validated above. Without a mark on+ // this day, the overlap predicate below is necessarily false.+ guard history.actions.contains(where: {+ $0.day == scope.day && $0.kind == .mark+ }) else { continue }+ var clears = history.clearKeys(workID: scope.workID, day: scope.day)+ clears.formUnion(scopedFacts.map(\.stableKey))+ if history.actions.contains(where: {+ $0.day == scope.day && $0.kind == .mark+ && clears.isSubset(of: Set($0.observedClearKeys))+ }) {+ actions.append(try .init(workID: scope.workID, key: "clear/\(UUID().uuidString)",+ day: scope.day, kind: .clear, observedClearKeys: []))+ }+ }+ let priorAssignments = Set(before.map {+ NoteAssignment(entryID: $0.entryID, workID: $0.workID, day: $0.day)+ })+ for fact in after where !priorAssignments.contains(+ NoteAssignment(entryID: fact.entryID, workID: fact.workID, day: fact.day)) {+ actions.append(try .init(workID: fact.workID, key: "clear/\(UUID().uuidString)",+ day: fact.day.description, kind: .clear,+ observedClearKeys: []))+ }+ // The common unchanged pass has all stable keys and no overlap. It+ // must not re-fetch and decode the action table a second time.+ guard !actions.isEmpty else { return false }+ // Every decision above uses the SAME before-call snapshot. Publish the+ // new clears to the reusable view only after validating the whole batch.+ var nextHistories: [UUID: NoEpisodeHistory] = [:]+ for (workID, additions) in Dictionary(grouping: actions, by: \.workID) {+ nextHistories[workID] = try (histories![workID] ?? .empty)+ .union(NoEpisodeHistory(additions))+ }+ let encoded = try actions.map { ($0, try $0.canonicalData()) }+ for (action, data) in encoded {+ let key = ActionKey(workID: action.workID, key: action.key)+ if let prior = actionsByKey[key] {+ guard prior == action else {+ throw NoEpisodeHistory.HistoryError.conflictingAction(action.workID, action.key)+ }+ continue+ }+ let row = NoEpisodeAction(workID: action.workID, key: action.key, payloadData: data)+ context.insert(row)+ rawRows!.append(row)+ if rawRowsByWorkID != nil {+ rawRowsByWorkID![action.workID, default: []].append(row)+ }+ actionsByKey[key] = action+ }+ for (workID, history) in nextHistories { histories![workID] = history }+ return true }- return true } private struct ActionKey: Hashable {
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RecordHistoryJourneyFixture.swift b/Packages/AsterismCore/Sources/AsterismCore/RecordHistoryJourneyFixture.swiftnew file mode 100644index 00000000..38648dd6--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/RecordHistoryJourneyFixture.swift@@ -0,0 +1,56 @@+import Foundation+import SwiftData++#if DEBUG+extension LibraryRepository {+ /// Only reachable from an isolated UI-test scenario. Extends the existing+ /// completed synthetic fixture; same-root relaunch preserves reader edits.+ public func seedRecordHistoryJourneyFixture() async throws {+ try await seedAssociationNotesFixture()+ let workID = UUID(uuidString: "24680000-0000-4000-8000-000000000001")!+ let characterID = UUID(uuidString: "24680000-0000-4000-8000-000000000004")!+ let lastID = UUID(uuidString: "24680000-0000-4000-8000-000000000028")!+ let completed = try await withLockedContext(mode: .exclusive, operation: "preparing isolated history journey") { context in+ let existing = try context.fetch(FetchDescriptor<Entry>())+ if existing.contains(where: { $0.id == lastID }) { return true }+ guard existing.count == 2,+ let work = try context.fetch(FetchDescriptor<Work>()).first(where: { $0.id == workID }) else {+ throw LibraryRepositoryError.invalidInput(operation: "preparing isolated history journey", reason: "unexpected fixture state")+ }+ for number in 6...28 {+ let id = UUID(uuidString: String(format: "24680000-0000-4000-8000-%012d", number))!+ let title = number == 6 || number == 7 ? "Shared title" : "History \(number)"+ let bodyNumber = number == 7 ? 6 : number+ let entry = Entry(id: id, captureTitle: title, captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: Date().addingTimeInterval(Double(number)),+ note: " Alice reads Cafe\u{301}.\nExact saved chapter \(bodyNumber). ")+ try entry.authorTarget(.init(kind: .chapter, title: title, designation: String(number)))+ context.insert(entry); entry.work = work; Self.applyManualAssignment(to: entry, at: entry.modifiedAt)+ }+ try saveStrategy.save(context); return false+ }+ guard !completed else { return }+ for number in 6...28 {+ let id = UUID(uuidString: String(format: "24680000-0000-4000-8000-%012d", number))!+ let current = try await entry(id: id)+ if number == 28 {+ let accepted = try await commitDecision(.init(workID: workID, kind: .character, action: .accept,+ displayedKeys: ["alice"], displayedTargetID: characterID, proposedName: "Alice",+ mentions: [.init(entryID: id, noteFingerprint: CharacterCoverageFingerprint.of(current.note), spellingKeys: ["alice"])]))+ let pair = AssociationPair(workID: workID, entryID: id, kind: .character, recordID: characterID)+ guard case .committed = accepted, let basis = try await associationNoteBasis(pair: pair),+ try await saveAssociationNote(basis: basis, text: " Cafe\u{301} skipped chapter annotation ") == .committed else {+ throw LibraryRepositoryError.invalidInput(operation: "preparing isolated history journey", reason: "detached-note seed refused")+ }+ }+ let outcome = try await commitDecision(.init(workID: workID, kind: .character,+ action: number == 28 ? .skip : .accept, displayedKeys: ["alice"], displayedTargetID: characterID,+ proposedName: "Alice", mentions: [.init(entryID: id,+ noteFingerprint: CharacterCoverageFingerprint.of(current.note), spellingKeys: ["alice"])]))+ guard case .committed = outcome else {+ throw LibraryRepositoryError.invalidInput(operation: "preparing isolated history journey", reason: "link decision refused")+ }+ }+ }+}+#endif
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RecordHistorySnapshot.swift b/Packages/AsterismCore/Sources/AsterismCore/RecordHistorySnapshot.swiftnew file mode 100644index 00000000..0d439d7b--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/RecordHistorySnapshot.swift@@ -0,0 +1,72 @@+import Foundation++public struct RecordHistorySelection: Sendable, Equatable, Hashable {+ public let workID: UUID+ public let kind: RecordKind+ public let recordID: UUID+ public init(workID: UUID, kind: RecordKind, recordID: UUID) {+ self.workID = workID; self.kind = kind; self.recordID = recordID+ }+}++public enum RecordHistoryAvailability: Sendable, Equatable {+ case available, reviewRequired, unavailable+}++/// Compact row metadata. Full display bodies belong to the same immutable+/// snapshot and are revealed only through its generation-checked detail read.+public struct RecordHistoryRow: Sendable, Equatable, Identifiable {+ public let id: AssociationPair+ public let displayTitle: String+ public let chapterKey: ChapterKey?+ public let notedAt: Date+ public let sourcePreview: String+ public let sourceFingerprint: String+ public let hasAnnotation: Bool+ public let hasConflictingAnnotations: Bool+ public init(id: AssociationPair, displayTitle: String, chapterKey: ChapterKey?, notedAt: Date,+ sourcePreview: String, sourceFingerprint: String, hasAnnotation: Bool, hasConflictingAnnotations: Bool) {+ self.id = id; self.displayTitle = displayTitle; self.chapterKey = chapterKey; self.notedAt = notedAt+ self.sourcePreview = sourcePreview; self.sourceFingerprint = sourceFingerprint+ self.hasAnnotation = hasAnnotation; self.hasConflictingAnnotations = hasConflictingAnnotations+ }+}++public struct RecordHistoryDetail: Sendable, Equatable {+ public let pair: AssociationPair+ public let sourceText: String+ public let annotationHeads: [AssociationNoteValue]+ public let annotationMetadataNeedsReview: Bool+ public init(pair: AssociationPair, sourceText: String, annotationHeads: [AssociationNoteValue], annotationMetadataNeedsReview: Bool = false) {+ self.pair = pair; self.sourceText = sourceText; self.annotationHeads = annotationHeads+ self.annotationMetadataNeedsReview = annotationMetadataNeedsReview+ }+}++public struct RecordHistorySnapshot: Sendable, Equatable {+ public let selection: RecordHistorySelection+ public let generation: String+ public let availability: RecordHistoryAvailability+ /// Nil means incomplete/unavailable membership; verified rows remain usable.+ public let activeChapterCount: Int?+ public let rows: [RecordHistoryRow]+ public let unavailableEntryIDs: Set<UUID>+ private let capturedDetails: [AssociationPair: RecordHistoryDetail]+ public init(selection: RecordHistorySelection, generation: String, availability: RecordHistoryAvailability,+ activeChapterCount: Int?, rows: [RecordHistoryRow], unavailableEntryIDs: Set<UUID> = [],+ details: [RecordHistoryDetail] = []) {+ self.selection = selection; self.generation = generation; self.availability = availability+ self.activeChapterCount = activeChapterCount; self.rows = rows; self.unavailableEntryIDs = unavailableEntryIDs+ self.capturedDetails = Dictionary(details.map { ($0.pair, $0) }, uniquingKeysWith: { first, _ in first })+ }+ /// Display-only captured values, never fresh write authority. A stale UI+ /// callback cannot mix a different generation's bodies into current rows.+ public func detail(for pair: AssociationPair, expectedGeneration: String) -> RecordHistoryDetail? {+ guard expectedGeneration == generation, pair.workID == selection.workID,+ pair.kind == selection.kind, pair.recordID == selection.recordID else { return nil }+ return capturedDetails[pair]+ }+ public var displayTextUTF8ByteCount: Int {+ capturedDetails.values.reduce(0) { $0 + $1.sourceText.utf8.count + $1.annotationHeads.reduce(0) { $0 + $1.text.utf8.count } }+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RecordMentionGrounding.swift b/Packages/AsterismCore/Sources/AsterismCore/RecordMentionGrounding.swiftnew file mode 100644index 00000000..f2bbf986--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/RecordMentionGrounding.swift@@ -0,0 +1,63 @@+import Foundation++/// The literal name rules shared by model grounding and saved-link maintenance.+/// Matching stays case-insensitive/NFC; returned evidence retains the original+/// saved source scalars rather than an echo or normalized reconstruction.+public enum RecordMentionGrounding {+ public static let maximumNameLength = 100+ public enum Failure: String, Sendable { case emptyName, pronounName, nameTooLong, nameNotInSource, nameNeverCapitalised }+ public static let pronouns: Set<String> = [+ "i", "me", "my", "mine", "myself", "you", "your", "yours", "yourself", "yourselves",+ "he", "him", "his", "himself", "she", "her", "hers", "herself", "it", "its", "itself",+ "we", "us", "our", "ours", "ourselves", "they", "them", "their", "theirs", "themselves",+ ]+ public static func failure(for name: String, in source: String) -> Failure? {+ guard !name.isEmpty else { return .emptyName }+ guard !pronouns.contains(RecordNameKey.normalize(name)) else { return .pronounName }+ guard name.count <= maximumNameLength else { return .nameTooLong }+ let matches = occurrences(of: name, in: source)+ guard !matches.isEmpty else { return .nameNotInSource }+ guard matches.contains(where: { capitalised($0) }) else { return .nameNeverCapitalised }+ return nil+ }+ public static func evidence(names: [String], in source: String) -> [AssociationEvidence] {+ evidence(names: names, in: source, completeNames: false)+ }+ /// Literal inference has no model/user name authority. Require complete+ /// names here while preserving established general grounding semantics.+ static func completeNameEvidence(names: [String], in source: String) -> [AssociationEvidence] {+ evidence(names: names, in: source, completeNames: true)+ }+ /// Transition-only support proof. This never replaces the historical+ /// literal evidence encoded in a whole association receipt.+ static func maintenanceEvidence(names: [String], in source: String) -> [AssociationEvidence] {+ let cased = names.filter { $0.contains(where: \.isCased) }+ let uncased = names.filter { !$0.contains(where: \.isCased) }+ return Array(Set(completeNameEvidence(names: cased, in: source)+ + evidence(names: uncased, in: source))).sorted(by: AssociationEvidence.ordered)+ }+ private static func evidence(names: [String], in source: String, completeNames: Bool) -> [AssociationEvidence] {+ var result: Set<AssociationEvidence> = []+ for name in Set(names) where !name.isEmpty && name.count <= maximumNameLength+ && !pronouns.contains(RecordNameKey.normalize(name)) {+ for spelling in occurrences(of: name, in: source, completeNames: completeNames) where capitalised(spelling) {+ result.insert(.init(key: RecordNameKey.normalize(name), spelling: spelling))+ }+ }+ return result.sorted(by: AssociationEvidence.ordered)+ }+ private static func capitalised(_ spelling: String) -> Bool {+ !spelling.contains(where: \.isCased) || spelling.contains { $0.isCased && !$0.isLowercase }+ }+ private static func occurrences(of name: String, in source: String, completeNames: Bool = false) -> [String] {+ let needle = name.precomposedStringWithCanonicalMapping+ guard !needle.isEmpty else { return [] }+ var from = source.startIndex, values: [String] = []+ while from < source.endIndex,+ let range = source.range(of: needle, options: [.caseInsensitive], range: from..<source.endIndex) {+ if !completeNames || RecordNameBoundaries.contains(range, in: source) { values.append(String(source[range])) }+ from = range.upperBound+ }+ return values+ }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RecordNameBoundaries.swift b/Packages/AsterismCore/Sources/AsterismCore/RecordNameBoundaries.swiftnew file mode 100644index 00000000..2ba8a77f--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/RecordNameBoundaries.swift@@ -0,0 +1,56 @@+import Foundation++/// Complete names may border punctuation, but never an adjacent word component.+/// Work over source scalars so letters/marks from every script participate.+enum RecordNameBoundaries {+ static func contains(_ range: Range<String.Index>, in text: String) -> Bool {+ let scalars = text.unicodeScalars+ if range.lowerBound > scalars.startIndex {+ let previous = scalars.index(before: range.lowerBound)+ let value = scalars[previous]+ if joiner(value) {+ if previous > scalars.startIndex, word(scalars[scalars.index(before: previous)]) { return false }+ } else if word(value) { return false }+ }+ guard range.upperBound < scalars.endIndex else { return true }+ let next = range.upperBound, value = scalars[next]+ if apostrophe(value) {+ let component = scalars.index(after: next)+ guard component < scalars.endIndex, word(scalars[component]) else { return true }+ // A possessive is a delimiter only as a complete suffix.+ guard scalars[component] == "s" || scalars[component] == "S" else { return false }+ return !continues(at: scalars.index(after: component), in: scalars)+ }+ if hyphen(value) {+ let component = scalars.index(after: next)+ return component == scalars.endIndex || !word(scalars[component])+ }+ return !word(value)+ }+ private static func continues(at index: String.Index, in scalars: String.UnicodeScalarView) -> Bool {+ guard index < scalars.endIndex else { return false }+ if word(scalars[index]) && !joiner(scalars[index]) { return true }+ if joiner(scalars[index]) {+ let next = scalars.index(after: index)+ return next < scalars.endIndex && word(scalars[next])+ }+ return false+ }+ private static func word(_ value: Unicode.Scalar) -> Bool {+ switch value.properties.generalCategory {+ case .uppercaseLetter, .lowercaseLetter, .titlecaseLetter, .modifierLetter, .otherLetter,+ .decimalNumber, .letterNumber, .otherNumber, .nonspacingMark, .spacingMark, .enclosingMark,+ .connectorPunctuation: true+ default: false+ }+ }+ private static let apostrophes: Set<Unicode.Scalar> = ["'", "’", "ʼ", "'"]+ private static let hyphens: Set<Unicode.Scalar> = ["-", "‐", "‑", "﹣", "-"]+ private static func apostrophe(_ value: Unicode.Scalar) -> Bool {+ apostrophes.contains(value)+ }+ private static func hyphen(_ value: Unicode.Scalar) -> Bool {+ hyphens.contains(value)+ }+ private static func joiner(_ value: Unicode.Scalar) -> Bool { apostrophe(value) || hyphen(value) }+}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/RecordRanking.swift b/Packages/AsterismCore/Sources/AsterismCore/RecordRanking.swiftindex 714be308..e4e50bfe 100644--- a/Packages/AsterismCore/Sources/AsterismCore/RecordRanking.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/RecordRanking.swift@@ -3,8 +3,9 @@ import Foundation // The prominence order a work's records are listed in (Reqs 1 and 2), for any // `RecordRow`. //-// Two pure types, derived on read from data the surfaces already hold: nothing-// is stored, no fetch is added, and both the work page and the share sheet rank+// Two pure types, derived on read: nothing is stored. Legacy facts are joined+// with validated saved chapter support by one Work-scoped inventory read; both+// the work page and the share sheet rank // the same way against the whole work (Decision 1). Internal rather than public // because `RecordGroup` holds SwiftData rows and is not `Sendable` (Q36); // the tests reach them through `@testable import`.@@ -95,7 +96,7 @@ struct StoryPositionIndex { } } -/// What a record's facts are worth, and the order that follows (Req 1).+/// What a record's saved evidence is worth, and the order that follows. /// /// `Σ w(d) · f(n)` over the record's buckets: `w` decays with distance so a /// record who has stopped appearing drifts down, and `f` is concave so@@ -156,23 +157,34 @@ enum RecordRanking { /// distance, and generic → live → dangling within one distance — because /// that is what makes two identical profiles produce the same `Double` to /// the last bit (Decision 3).- static func score(facts: [RecordFact], index: StoryPositionIndex) -> Double {+ static func score(facts: [RecordFact], index: StoryPositionIndex, chapterEntryIDs: Set<UUID> = []) -> Double { var generic = 0 var dangling = 0 var live: [Int: Int] = [:]+ var entryFacts: [UUID: Int] = [:] for fact in facts { switch fact.source { case .genericNotes: generic += 1 case .entry(let entryID):- if let distance = index.distance(of: entryID) {- live[distance, default: 0] += 1+ if index.distance(of: entryID) != nil {+ entryFacts[entryID, default: 0] += 1 } else { dangling += 1 } } } + // A saved, current chapter link supplies the minimum evidence for+ // that Entry. Existing facts remain historical evidence; the link does+ // not count again where one or more facts already cite the Entry.+ for id in chapterEntryIDs where index.distance(of: id) != nil {+ entryFacts[id] = max(entryFacts[id, default: 0], 1)+ }+ for (id, count) in entryFacts {+ live[index.distance(of: id)!, default: 0] += count+ }+ // `tier` is the within-distance sequence; live buckets are keyed by // distance, so no two of them can collide on it. var buckets: [(distance: Int, tier: Int, count: Int)] = []@@ -226,30 +238,35 @@ enum RecordRanking { private struct SortKey { let score: Double let nameKey: String- let hasFacts: Bool+ let hasEvidence: Bool let id: UUID } private static func sortKey<Row: RecordRow>(- of group: RecordGroup<Row>, facts: [RecordFact], index: StoryPositionIndex+ of group: RecordGroup<Row>, facts: [RecordFact], index: StoryPositionIndex,+ chapterSupport: [UUID: Set<UUID>] ) -> SortKey {- SortKey(- score: facts.isEmpty ? 0 : score(facts: facts, index: index),+ // Place ranking is deliberately unchanged, including if a UUID also+ // happens to address a character in the same Work.+ let links: Set<UUID> = Row.kind == .character+ ? chapterSupport[group.id, default: []].filter { index.distance(of: $0) != nil } : []+ return SortKey(+ score: score(facts: facts, index: index, chapterEntryIDs: links), nameKey: RecordNameKey.normalize(group.presentedContent.name),- hasFacts: !facts.isEmpty,+ hasEvidence: !facts.isEmpty || !links.isEmpty, id: group.id) } - /// Descending score, then name order; every record with no presented- /// facts last, in name order (Reqs 1.1, 1.6).+ /// Descending score, then name order; records with neither presented facts+ /// nor current saved chapter support follow, in name order. /// /// The partition is a rule, not a floor: a fact far enough back for its /// weight to underflow still outranks a record nobody has noted anything /// about (Q16). Scores are compared with `<` and fall to name order only on /// a bit-exact `==` (Decision 3). private static func precedes(_ left: SortKey, _ right: SortKey) -> Bool {- if left.hasFacts != right.hasFacts { return left.hasFacts }- if left.hasFacts, left.score != right.score { return left.score > right.score }+ if left.hasEvidence != right.hasEvidence { return left.hasEvidence }+ if left.hasEvidence, left.score != right.score { return left.score > right.score } return left.nameKey == right.nameKey ? left.id.uuidString < right.id.uuidString : left.nameKey < right.nameKey@@ -258,18 +275,18 @@ enum RecordRanking { /// The order (Reqs 1.1, 1.6) over records whose facts a caller already /// holds — the seam Req 4.3's measurement times (Decision 4). static func order<Row: RecordRow>(- _ records: [RankedRecord<Row>], index: StoryPositionIndex+ _ records: [RankedRecord<Row>], index: StoryPositionIndex, chapterSupport: [UUID: Set<UUID>] = [:] ) -> [RankedRecord<Row>] {- let keys = records.map { sortKey(of: $0.group, facts: $0.facts, index: index) }+ let keys = records.map { sortKey(of: $0.group, facts: $0.facts, index: index, chapterSupport: chapterSupport) } return zip(records, keys).sorted { precedes($0.1, $1.1) }.map(\.0) } /// Decode once, then order (Reqs 1.1, 1.6) — what the work page calls, which /// draws the facts it carries out (Decision 4). static func rank<Row: RecordRow>(- _ groups: [UUID: RecordGroup<Row>], index: StoryPositionIndex+ _ groups: [UUID: RecordGroup<Row>], index: StoryPositionIndex, chapterSupport: [UUID: Set<UUID>] = [:] ) -> [RankedRecord<Row>] {- order(decode(groups), index: index)+ order(decode(groups), index: index, chapterSupport: chapterSupport) } /// The same order for a caller that wants only the groups — the share@@ -281,11 +298,11 @@ enum RecordRanking { /// once. The scoring and the ordering are `rank`'s, so the share sheet and /// the work page still answer with one order (Decision 1). static func rankGroups<Row: RecordRow>(- _ groups: [UUID: RecordGroup<Row>], index: StoryPositionIndex+ _ groups: [UUID: RecordGroup<Row>], index: StoryPositionIndex, chapterSupport: [UUID: Set<UUID>] = [:] ) -> [RecordGroup<Row>] { groups.values .map { group in- (group, sortKey(of: group, facts: group.presentedContent.facts, index: index))+ (group, sortKey(of: group, facts: group.presentedContent.facts, index: index, chapterSupport: chapterSupport)) } .sorted { precedes($0.1, $1.1) } .map(\.0)
diff --git a/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift b/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swiftindex 3c26fc20..ced3c039 100644--- a/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/ShareWorkContext.swift@@ -288,16 +288,19 @@ extension LibraryRepository { let rowsByID = Dictionary(grouping: allRows, by: \.id) // The work page's order, from the work page's inputs: every live entry // of the work, whatever chapter is being shared (Req 2.7). Ranked here,- // above the `do`, and out of parts that cannot throw — the row walk, the- // index, the scoring — so a failure in the notes half below costs the- // notes and not the cast (`share-sheet-characters` Q15).+ // above the optional notes `do/catch`. Validated saved support is a+ // prerequisite of the cast and its storage read can throw; a failure in+ // the notes half below still preserves the already ranked cast+ // (`share-sheet-characters` Q15). let storyPositions = StoryPositionIndex(entries: storyPositionInputs(buckets: rowsByID)) // `rankGroups`, not `rank`: this sheet draws names, aliases and notes, // so a character's facts are decoded, scored and dropped before the next // character's are read rather than the whole cast's being held at once // (Q43). The order is `rank`'s own.+ let characterRows = characterRows(of: works)+ let chapterSupport = characterRows.isEmpty ? [:] : try characterChapterSupport(workID: id, context: context) let characters = RecordRanking.rankGroups(- recordGroups(characterRows(of: works)), index: storyPositions+ recordGroups(characterRows), index: storyPositions, chapterSupport: chapterSupport ) .map { group in let content = group.presentedContent
diff --git a/Packages/AsterismCore/Sources/AsterismCore/TodayPresentation.swift b/Packages/AsterismCore/Sources/AsterismCore/TodayPresentation.swiftindex c47eb45f..2da8b343 100644--- a/Packages/AsterismCore/Sources/AsterismCore/TodayPresentation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/TodayPresentation.swift@@ -327,6 +327,9 @@ public struct EntryTeachingDetail: Equatable, Sendable { /// Populated in the same locked read, from one predicate fetch over the /// entry's work: the two lists are one read's answer, not two. public let citingPlaces: [EntryCitingRecord]+ /// Saved association/note values from this same locked Entry detail read.+ /// Independent of fact citations and never an extraction input.+ public let chapterAssociations: [ChapterAssociationSnapshot] public init( entry: EntrySnapshot, siteMode: SiteMode?,@@ -340,8 +343,10 @@ public struct EntryTeachingDetail: Equatable, Sendable { hasCurrentURLRule: Bool = false, groupState: RecordGroupState<EntryAuthoredContent> = .single, citingCharacters: [EntryCitingRecord] = [],- citingPlaces: [EntryCitingRecord] = []+ citingPlaces: [EntryCitingRecord] = [],+ chapterAssociations: [ChapterAssociationSnapshot] = [] ) {+ self.chapterAssociations = chapterAssociations self.groupState = groupState self.citingCharacters = citingCharacters self.citingPlaces = citingPlaces
diff --git a/Packages/AsterismCore/Sources/AsterismCore/WorkChapterOrder.swift b/Packages/AsterismCore/Sources/AsterismCore/WorkChapterOrder.swiftnew file mode 100644index 00000000..ae7283e2--- /dev/null+++ b/Packages/AsterismCore/Sources/AsterismCore/WorkChapterOrder.swift@@ -0,0 +1,36 @@+import Foundation++extension WorkChapterRow {+ /// The existing Work spine order, shared by selected record histories.+ public static func inChapterOrder(_ rows: [WorkChapterRow]) -> [WorkChapterRow] {+ rows.enumerated().sorted(by: precedesInChapterOrder).map(\.element)+ }+ private static func precedesInChapterOrder(+ _ left: (offset: Int, element: WorkChapterRow),+ _ right: (offset: Int, element: WorkChapterRow)+ ) -> Bool {+ let lhs = left.element+ let rhs = right.element+ // The placement where both have one; a note with one before a note+ // without. `ChapterPlacement` is the scale — one derivation shared with+ // the share sheet's catch-up selection (share-sheet-last-note Decision+ // 4), so the spine and the sheet cannot come apart about order. The+ // `lastSharedAt` fallback below stays here: it is what an *unplaced*+ // row falls back to on this page, and the sheet has no such fallback.+ switch (+ ChapterPlacement(sequencePosition: lhs.sequencePosition, chapterKey: lhs.chapterKey),+ ChapterPlacement(sequencePosition: rhs.sequencePosition, chapterKey: rhs.chapterKey)+ ) {+ case (.some(let leftPlacement), .some(let rightPlacement)):+ if leftPlacement != rightPlacement { return leftPlacement < rightPlacement }+ case (.some, .none): return true+ case (.none, .some): return false+ case (.none, .none): break+ }+ if lhs.lastSharedAt != rhs.lastSharedAt {+ return lhs.lastSharedAt < rhs.lastSharedAt+ }+ return left.offset < right.offset+ }++}
diff --git a/Packages/AsterismCore/Sources/AsterismCore/WorkRecordPresentation.swift b/Packages/AsterismCore/Sources/AsterismCore/WorkRecordPresentation.swiftindex 588b7102..abab986e 100644--- a/Packages/AsterismCore/Sources/AsterismCore/WorkRecordPresentation.swift+++ b/Packages/AsterismCore/Sources/AsterismCore/WorkRecordPresentation.swift@@ -133,9 +133,9 @@ extension LibraryRepository { /// result on rather than leaving `recordPresentations` to decode the /// same 200 blobs a second time. internal static func rankedRecordGroups<Row: RecordRow>(- _ groups: [UUID: RecordGroup<Row>], index: StoryPositionIndex+ _ groups: [UUID: RecordGroup<Row>], index: StoryPositionIndex, chapterSupport: [UUID: Set<UUID>] = [:] ) -> [RecordRanking.RankedRecord<Row>] {- RecordRanking.rank(groups, index: index)+ RecordRanking.rank(groups, index: index, chapterSupport: chapterSupport) } /// The work's characters as the page draws them, in prominence order.@@ -158,9 +158,10 @@ extension LibraryRepository { captureOrder: [UUID: Int], titles: [UUID: String], dates: [UUID: Date] = [:],- keys: [UUID: ChapterKey] = [:]+ keys: [UUID: ChapterKey] = [:],+ chapterSupport: [UUID: Set<UUID>] = [:] ) -> [WorkRecordPresentation] {- rankedRecordGroups(groups, index: index)+ rankedRecordGroups(groups, index: index, chapterSupport: chapterSupport) .map { ranked in let group = ranked.group let content = group.presentedContent
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionAssembler.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionAssembler.swiftindex 0c02028b..9ffbf0e0 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionAssembler.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionAssembler.swift@@ -38,7 +38,43 @@ public enum CharacterExtractionAssembler { ) -> [ExtractionProposal] { let filtered = survivors(of: candidates, context: context, pass: pass) let resolved = applyDualKindRule(to: filtered, context: context, pass: pass)- return capped(grouped(resolved, revisions: revisions, pass: pass))+ return capped(grouped(resolved, revisions: revisions, context: context, pass: pass))+ }++ /// Shipping note-first path. Legacy fact assembly remains available to+ /// compatibility tools, but cannot enter a new extraction decision.+ public static func assembleNoteFirst(+ _ candidates: [GroundedCandidate], revisions: [SourceRef: String],+ context: CharacterExtractionContext, pass: ExtractionPassKind+ ) -> [ExtractionProposal] {+ let names = candidates.map { candidate in+ var value = candidate; value.facts = []; return value+ }+ let filtered = survivors(of: names, context: context, pass: pass, noteFirst: true)+ // Confidence is classified before unmatched kinds can fold together.+ let resolved = applyDualKindRule(to: filtered, context: context, pass: pass)+ return capped(grouped(resolved, revisions: revisions, context: context, pass: pass)).map { proposal in+ var value = proposal+ value.isNoteFirst = true+ let matching = names.filter { candidate in+ candidate.nameKey == proposal.nameKey && proposal.returnedKinds.contains(candidate.kind)+ }+ value.sourceEvidence = ProposalSourceEvidence.merged(matching.compactMap { candidate in+ guard var evidence = candidate.sourceEvidence else { return nil }+ evidence.isDecisionBasis = proposal.citedRevisions[candidate.source] == evidence.fingerprint+ return evidence+ })+ if proposal.kind == .character {+ switch RecordMatching.recognition(nameKey: proposal.nameKey,+ among: context.records(of: .character).map(\.matchTarget)) {+ case .noMatch: break+ case .unique(let id):+ value.target = context.mentionIndex.canLink(kind: .character, recordID: id) ? .existing(id) : .unresolved+ case .ambiguous: value.target = .unresolved+ }+ }+ return value+ } } // MARK: - Step 1: one source response, one kind, one name key@@ -55,6 +91,8 @@ public enum CharacterExtractionAssembler { var facts: [GroundedFact] var aliases: [String] var returnedKinds: Set<RecordKind>+ var mentionKeys: [String]+ var unresolved = false } private struct ResponseKey: Hashable {@@ -65,7 +103,7 @@ public enum CharacterExtractionAssembler { private static func survivors( of candidates: [GroundedCandidate], context: CharacterExtractionContext,- pass: ExtractionPassKind+ pass: ExtractionPassKind, noteFirst: Bool = false ) -> [Survivor] { var order: [ResponseKey] = [] var grouped: [ResponseKey: [GroundedCandidate]] = [:]@@ -78,21 +116,31 @@ public enum CharacterExtractionAssembler { return order.compactMap { key in guard let copies = grouped[key] else { return nil }- return survivor(of: copies, key: key, context: context, pass: pass)+ return survivor(of: copies, key: key, context: context, pass: pass, noteFirst: noteFirst) } } private static func survivor( of copies: [GroundedCandidate], key: ResponseKey,- context: CharacterExtractionContext, pass: ExtractionPassKind+ context: CharacterExtractionContext, pass: ExtractionPassKind, noteFirst: Bool ) -> Survivor? {- let match = resolve(key.nameKey, among: context.records(of: key.kind))+ let recognition = RecordMatching.recognition(nameKey: key.nameKey,+ among: context.records(of: key.kind).map(\.matchTarget))+ let unresolved: Bool+ if noteFirst && key.kind == .character {+ switch recognition {+ case .ambiguous: unresolved = true+ case .unique(let id): unresolved = !context.mentionIndex.canLink(kind: .character, recordID: id)+ case .noMatch: unresolved = false+ }+ } else { unresolved = false }+ let match = unresolved ? nil : resolve(key.nameKey, among: context.records(of: key.kind)) // A name-key suppression blocks a *new candidate* only, and only under // its own kind (Q13). A record the work already has stays enrichable // regardless of what was skipped under its name (Q47), and a manual pass // exists to get past both (Req 1.11, Q49).- if pass == .automatic, match == nil,+ if pass == .automatic, match == nil, !unresolved, context.suppressedNameKeys(of: key.kind).contains(key.nameKey) { return nil }@@ -124,12 +172,28 @@ public enum CharacterExtractionAssembler { } } + var mentionKeys: [String] = []+ if case .entry(let entryID) = key.source, context.mentionIndex.eligibleEntries.contains(entryID),+ match.map({ context.mentionIndex.canLink(kind: key.kind, recordID: $0.id) }) ?? true {+ let suppressed = match.map { context.mentionIndex.isSuppressed(entryID: entryID,+ kind: key.kind, recordID: $0.id, spellingKey: key.nameKey) } ?? false+ let active = match.flatMap { context.mentionIndex.pair(entryID: entryID, kind: key.kind, recordID: $0.id) }+ .map { context.mentionIndex.activePairs.contains($0) } ?? false+ if noteFirst && key.kind == .character {+ if !suppressed { mentionKeys = [key.nameKey] }+ } else if (!active || suppressed), pass == .manual || !suppressed {+ mentionKeys = [key.nameKey]+ }+ }+ // Q36's survival predicate, which Req 1.5's dual-kind rule then runs // over. A *new* name is itself new content, so a name-only candidate // stands (Q25); a bundle needs a fact or an alias the record does not // already have.- if match != nil, facts.isEmpty, aliases.isEmpty { return nil }- if match == nil, facts.isEmpty, !copies.contains(where: { $0.facts.isEmpty }) {+ if !noteFirst || key.kind != .character {+ if match != nil, facts.isEmpty, aliases.isEmpty, mentionKeys.isEmpty { return nil }+ }+ if match == nil, facts.isEmpty, mentionKeys.isEmpty, !copies.contains(where: { $0.facts.isEmpty }) { // Everything this candidate offered was already accepted, which // means it is not a new record at all — its target was renamed or // deleted out from under the key. Nothing left to decide.@@ -139,7 +203,7 @@ public enum CharacterExtractionAssembler { return Survivor(key: ProposalKey(kind: key.kind, nameKey: key.nameKey), name: copies[0].name, source: key.source, match: match, resolvedKey: resolvedKey, facts: facts, aliases: aliases,- returnedKinds: [key.kind])+ returnedKinds: [key.kind], mentionKeys: mentionKeys, unresolved: unresolved) } // MARK: - Step 2: the dual-kind rule (Req 1.5)@@ -176,7 +240,7 @@ public enum CharacterExtractionAssembler { var folded: Set<Int> = [] for (_, pair) in indexes { guard let character = pair[.character], let place = pair[.place],- result[character].match == nil, result[place].match == nil+ result[character].match == nil, !result[character].unresolved, result[place].match == nil else { continue } var facts = result[character].facts@@ -201,7 +265,7 @@ public enum CharacterExtractionAssembler { // MARK: - Step 3: one row per kind and name key across the pass private static func grouped(- _ survivors: [Survivor], revisions: [SourceRef: String], pass: ExtractionPassKind+ _ survivors: [Survivor], revisions: [SourceRef: String], context: CharacterExtractionContext, pass: ExtractionPassKind ) -> [ExtractionProposal] { var order: [ProposalKey] = [] var groups: [ProposalKey: [Survivor]] = [:]@@ -238,12 +302,32 @@ public enum CharacterExtractionAssembler { returnedKinds.formUnion(survivor.returnedKinds) } + let mentions: [AssociationMentionDecision] = group.compactMap { survivor in+ guard case .entry(let entryID) = survivor.source, !survivor.mentionKeys.isEmpty,+ let fingerprint = revisions[survivor.source] else { return nil }+ let rejected = survivor.match.map { context.mentionIndex.rejectionIDs(entryID: entryID,+ kind: key.kind, recordID: $0.id, spellingKeys: survivor.mentionKeys) } ?? []+ return .init(entryID: entryID, noteFingerprint: fingerprint,+ spellingKeys: survivor.mentionKeys, observedRejectionIDs: rejected, sourceGuard: context.mentionIndex.sourceGuards[entryID])+ }+ let eligibility = Dictionary(uniqueKeysWithValues: group.compactMap { survivor -> (SourceRef, String)? in+ guard case .entry(let entryID) = survivor.source,+ let digest = context.mentionIndex.eligibilityByEntry[entryID] else { return nil }+ return (survivor.source, digest)+ }) let target: ExtractionProposal.Target = group[0].match.map { .existing($0.id) } ?? .newRecord return ExtractionProposal( name: group[0].name, nameKey: key.nameKey, kind: key.kind, proposedAliases: aliases, target: target, facts: facts, citedRevisions: cited,- returnedKinds: returnedKinds, pass: pass)+ returnedKinds: returnedKinds, pass: pass, mentions: mentions, citedMentionEligibility: eligibility,+ reviewAcknowledgements: cited.keys.compactMap { source -> AssociationReviewAcknowledgement? in+ guard case .entry(let entryID) = source, let workID = context.mentionIndex.workID else { return nil }+ return .init(workID: workID, entryID: entryID,+ references: context.mentionIndex.pendingReviewReferences[entryID, default: []].filter {+ $0.key == .init(kind: key.kind, nameKey: key.nameKey)+ })+ }) } }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBounds.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBounds.swiftindex dbfc3c99..7cccd3cf 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBounds.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBounds.swift@@ -1,3 +1,4 @@+import AsterismCore import Foundation /// Every tunable the extraction pipeline has, in one place (Req 1.2, 1.10).@@ -40,7 +41,7 @@ public enum CharacterExtractionBounds { /// Longest proposed name, statement and evidence span. Over-long values are /// **dropped, never truncated**: a cut evidence span is no longer the /// verbatim quote Req 1.6 requires, and a cut name no longer matches.- public static let maximumNameLength = 100+ public static let maximumNameLength = RecordMentionGrounding.maximumNameLength public static let maximumStatementLength = 500 public static let maximumEvidenceLength = 500 }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBridge.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBridge.swiftindex c381cdec..75cec052 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBridge.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionBridge.swift@@ -26,7 +26,7 @@ extension ExistingCharacter { public init(_ target: MatchTarget) { self.init( id: target.id, name: target.currentNameKey, retainedKey: target.retainedKey,- aliases: target.aliasKeys)+ aliases: target.aliasKeys, isTorn: target.isTorn) } } @@ -50,7 +50,7 @@ extension CharacterExtractionContext { } self.init( records: records, acceptedFacts: acceptedFacts,- suppressedNameKeys: suppressedNameKeys, suppressedFacts: suppressedFacts)+ suppressedNameKeys: suppressedNameKeys, suppressedFacts: suppressedFacts, mentionIndex: candidate.mentionIndex) } } @@ -71,12 +71,17 @@ extension ExtractionCandidate { (includingCovered ? sources : uncoveredSources).map { ExtractionSource( workID: workID, workTitle: displayTitle, source: $0.ref, text: $0.text,- fingerprint: $0.fingerprint)+ fingerprint: $0.fingerprint, mentionEligibilityDigest: $0.mentionEligibilityDigest,+ displayTitle: $0.displayTitle, capturedAt: $0.capturedAt, isChapter: $0.isChapter, stableOrder: $0.stableOrder) } } /// Every source's current revision, which is what a proposal's staleness is /// judged against (Req 2.7).+ public var eligibilityBySource: [SourceRef: String] {+ Dictionary(uniqueKeysWithValues: sources.map { ($0.ref, $0.attemptFingerprint) })+ }+ public var revisionsBySource: [SourceRef: String] { Dictionary(uniqueKeysWithValues: sources.map { ($0.ref, $0.fingerprint) }) }@@ -98,7 +103,7 @@ extension ExtractionProposal { /// save (Req 2.7, Q65). Ordered so two devices send the same request. public var completedSources: [CompletedSource] { citedRevisions- .map { CompletedSource(ref: $0.key, fingerprint: $0.value) }+ .map { CompletedSource(ref: $0.key, fingerprint: $0.value, mentionEligibilityDigest: citedMentionEligibility[$0.key]) } .sorted { $0.ref.orderToken < $1.ref.orderToken } } @@ -131,7 +136,7 @@ extension ExtractionProposal { untickedFacts: Set<RecordFactIdentity> = [] ) -> DecisionRequest { let shownAliases = proposedAliases.filter { !struckAliases.contains($0) }- let shownFacts = facts.map(\.storedFact)+ let shownFacts = isNoteFirst ? [] : facts.map(\.storedFact) let targetID: UUID? = if case .existing(let id) = target { id } else { nil } return DecisionRequest( workID: workID,@@ -144,6 +149,8 @@ extension ExtractionProposal { proposedAliases: shownAliases, facts: shownFacts.filter { !untickedFacts.contains($0.identity) }, untickedFacts: shownFacts.map(\.identity).filter(untickedFacts.contains),- completedSources: completedSources)+ completedSources: completedSources, mentions: mentions, reviewAcknowledgements: reviewAcknowledgements,+ reviewedKey: .init(kind: kind, nameKey: nameKey), requiresCurrentSources: isNoteFirst,+ guardedSources: isNoteFirst ? completedSources : nil) } }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionLedger.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionLedger.swiftindex 4ac62947..b9508684 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionLedger.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionLedger.swift@@ -89,13 +89,18 @@ public struct WorkExtractionState: Sendable, Equatable { /// Every source the work has now, with its current fingerprint. A proposal /// citing a revision that is not in here has gone stale. public var revisions: [SourceRef: String]+ public var eligibility: [SourceRef: String]+ public var sourceGuards: [UUID: String] /// The work's records, per kind. A bundle targeting one that is gone is /// discarded, and it is judged against the kind it is displayed under — a /// place bundle is never saved by a character of the same id. public var recordIDs: [RecordKind: Set<UUID>] - public init(revisions: [SourceRef: String], recordIDs: [RecordKind: Set<UUID>]) {+ public init(revisions: [SourceRef: String], recordIDs: [RecordKind: Set<UUID>],+ eligibility: [SourceRef: String]? = nil, sourceGuards: [UUID: String] = [:]) { self.revisions = revisions+ self.eligibility = eligibility ?? revisions+ self.sourceGuards = sourceGuards self.recordIDs = recordIDs } @@ -134,6 +139,7 @@ public struct CharacterExtractionLedger: Sendable, Equatable { } public private(set) var held: [UUID: [ExtractionProposal]] = [:]+ private var attemptedFingerprints: [ExtractionSourceKey: String] = [:] public private(set) var attempted: Set<ExtractionSourceKey> = [] public private(set) var inFlight: InFlight? public private(set) var budgetSpent: Duration = .zero@@ -246,10 +252,12 @@ public struct CharacterExtractionLedger: Sendable, Equatable { switch settlement { case .proposals(let proposals): attempted.insert(key)+ attemptedFingerprints[key] = attempt?.fingerprint guard !proposals.isEmpty else { return } hold(proposals, for: key.work) case .failed, .timedOut: attempted.insert(key)+ attemptedFingerprints[key] = attempt?.fingerprint case .cancelled: break }@@ -292,7 +300,7 @@ public struct CharacterExtractionLedger: Sendable, Equatable { /// pass's facts, which were kept past suppression on purpose (Q17), and a /// later sweep must not turn them into facts a reclassify preview would /// filter back out.- private static func merged(+ public static func merged( _ older: ExtractionProposal, into newer: ExtractionProposal ) -> ExtractionProposal { var facts = newer.facts@@ -301,6 +309,8 @@ public struct CharacterExtractionLedger: Sendable, Equatable { facts.append(fact) } facts.sort(by: CharacterExtractionAssembler.isOrderedBefore)+ let noteFirst = older.isNoteFirst || newer.isNoteFirst+ if noteFirst { facts = [] } var aliases = newer.proposedAliases var seenAliases = Set(newer.aliasKeys + [newer.nameKey])@@ -312,6 +322,17 @@ public struct CharacterExtractionLedger: Sendable, Equatable { var revisions = older.citedRevisions for (source, fingerprint) in newer.citedRevisions { revisions[source] = fingerprint } + var eligibility = older.citedMentionEligibility+ eligibility.merge(newer.citedMentionEligibility) { _, new in new }+ for mention in newer.mentions where newer.citedMentionEligibility[.entry(mention.entryID)] == nil {+ eligibility.removeValue(forKey: .entry(mention.entryID))+ }+ var mentions = Dictionary(grouping: older.mentions + newer.mentions, by: \.entryID).values.compactMap { rows -> AssociationMentionDecision? in+ guard let newest = rows.last else { return nil }+ return .init(entryID: newest.entryID, noteFingerprint: newest.noteFingerprint,+ spellingKeys: rows.flatMap(\.spellingKeys), observedRejectionIDs: rows.flatMap(\.observedRejectionIDs), sourceGuard: newest.sourceGuard)+ }+ mentions.sort { $0.entryID.uuidString < $1.entryID.uuidString } let reclassified = older.displayedKind != older.kind return ExtractionProposal( name: newer.name, nameKey: newer.nameKey, kind: newer.kind, proposedAliases: aliases,@@ -319,7 +340,19 @@ public struct CharacterExtractionLedger: Sendable, Equatable { citedRevisions: revisions, displayedKind: reclassified ? older.displayedKind : newer.displayedKind, returnedKinds: older.returnedKinds.union(newer.returnedKinds),- pass: older.isManual || newer.isManual ? .manual : .automatic)+ pass: older.isManual || newer.isManual ? .manual : .automatic, mentions: mentions, citedMentionEligibility: eligibility,+ reviewAcknowledgements: Dictionary(grouping: older.reviewAcknowledgements + newer.reviewAcknowledgements, by: \.entryID)+ .values.compactMap { values in+ values.first.map { .init(workID: $0.workID, entryID: $0.entryID, references: values.flatMap(\.references)) }+ }.sorted { $0.entryID.uuidString < $1.entryID.uuidString },+ sourceEvidence: ProposalSourceEvidence.merged(older.sourceEvidence + newer.sourceEvidence),+ isNoteFirst: noteFirst)+ }++ /// Replace only a work's held value snapshot after guarded background+ /// routing; this is not a model attempt or a coverage settlement.+ public mutating func replaceHeld(_ proposals: [ExtractionProposal], for work: UUID) {+ held[work] = proposals.isEmpty ? nil : proposals } // MARK: - Decisions@@ -337,6 +370,38 @@ public struct CharacterExtractionLedger: Sendable, Equatable { return true } + /// A fresh candidate read can invalidate one automatic mention without+ /// discarding unrelated source proposals or changing coverage eligibility.+ public mutating func refreshMentionDecisions(for work: UUID, index: AssociationMentionIndex) {+ guard let proposals = held[work] else { return }+ let refreshed = proposals.compactMap { proposal -> ExtractionProposal? in+ var result = proposal+ let targetID: UUID? = if case .existing(let id) = proposal.target { id } else { nil }+ result.mentions = proposal.mentions.compactMap { mention in+ // A save can settle an automatic known-place/character row.+ // Only its captured original obligation may disappear; another+ // pending spelling of that key keeps the row reviewable.+ if !proposal.isManual, proposal.facts.isEmpty, proposal.proposedAliases.isEmpty,+ let targetID, let guardValue = mention.sourceGuard,+ index.sourceGuards[mention.entryID] == guardValue,+ let pair = index.pair(entryID: mention.entryID, kind: proposal.displayedKind, recordID: targetID),+ index.activePairs.contains(pair) {+ let key = AssociationReviewKey(kind: proposal.kind, nameKey: proposal.nameKey)+ let captured = proposal.reviewAcknowledgements.filter { $0.workID == work && $0.entryID == mention.entryID }+ .flatMap(\.references).filter { $0.key == key }+ let pending = index.pendingReviewReferences[mention.entryID, default: []]+ if !captured.isEmpty, !pending.contains(where: { $0.key == key }) { return nil }+ }+ return index.refreshed(mention, kind: proposal.displayedKind, recordID: targetID, reconsider: proposal.isManual)+ }+ if !proposal.mentions.isEmpty, result.mentions.isEmpty,+ proposal.isBundle, proposal.facts.isEmpty, proposal.proposedAliases.isEmpty,+ !proposal.isManual || targetID.map({ !index.canLink(kind: proposal.displayedKind, recordID: $0) }) == true { return nil }+ return result+ }+ held[work] = refreshed.isEmpty ? nil : refreshed+ }+ public mutating func clearHeld(for work: UUID) { held[work] = nil }@@ -403,6 +468,7 @@ public struct CharacterExtractionLedger: Sendable, Equatable { let dropped = attempted.filter { $0.work == work } if !dropped.isEmpty { invalidated.insert(work) } attempted.subtract(dropped)+ for key in dropped { attemptedFingerprints[key] = nil } if inFlight?.key.work == work { inFlight?.void() invalidated.insert(work)@@ -410,6 +476,11 @@ public struct CharacterExtractionLedger: Sendable, Equatable { continue } + let changedAttempts = attempted.filter { key in+ key.work == work && attemptedFingerprints[key].map { state.eligibility[key.source] != $0 } == true+ }+ attempted.subtract(changedAttempts)+ for key in changedAttempts { attemptedFingerprints[key] = nil } if let proposals = held[work] { let surviving = proposals.filter { survives($0, in: state) } if surviving.count != proposals.count {@@ -418,7 +489,7 @@ public struct CharacterExtractionLedger: Sendable, Equatable { } } if let inFlight, inFlight.key.work == work, !inFlight.voided,- state.revisions[inFlight.key.source] != inFlight.fingerprint {+ state.eligibility[inFlight.key.source] != inFlight.fingerprint { self.inFlight?.void() invalidated.insert(work) }@@ -434,9 +505,10 @@ public struct CharacterExtractionLedger: Sendable, Equatable { !state.recordIDs(of: proposal.displayedKind).contains(id) { return false }- return proposal.citedRevisions.allSatisfy { source, fingerprint in- state.revisions[source] == fingerprint- }+ return proposal.citedRevisions.allSatisfy { source, fingerprint in state.revisions[source] == fingerprint }+ && proposal.mentions.allSatisfy { mention in+ mention.sourceGuard.map { state.sourceGuards[mention.entryID] == $0 } ?? true+ } } /// The run's cheap state goes; nothing durable is touched, because the@@ -445,6 +517,7 @@ public struct CharacterExtractionLedger: Sendable, Equatable { public mutating func memoryWarning() -> ExtractionSourceKey? { held.removeAll() attempted.removeAll()+ attemptedFingerprints.removeAll() inFlight?.void() return inFlight?.key }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionTypes.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionTypes.swiftindex 9fe37386..ff1d49b1 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionTypes.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterExtractionTypes.swift@@ -21,14 +21,55 @@ public struct ExtractionSource: Sendable, Equatable { public var source: SourceRef public var text: String public var fingerprint: String+ public var mentionEligibilityDigest: String?+ public var displayTitle: String+ public var capturedAt: Date?+ public var isChapter: Bool+ public var stableOrder: Int+ public var attemptFingerprint: String { mentionEligibilityDigest ?? fingerprint } public init(workID: UUID, workTitle: String, source: SourceRef,- text: String, fingerprint: String) {+ text: String, fingerprint: String, mentionEligibilityDigest: String? = nil,+ displayTitle: String = "", capturedAt: Date? = nil, isChapter: Bool = false, stableOrder: Int = 0) { self.workID = workID self.workTitle = workTitle self.source = source self.text = text self.fingerprint = fingerprint+ self.mentionEligibilityDigest = mentionEligibilityDigest+ self.displayTitle = displayTitle; self.capturedAt = capturedAt+ self.isChapter = isChapter; self.stableOrder = stableOrder+ }+}++/// Captured display provenance is independent of actionable mention writes.+/// One block per source revision within an original proposal key.+public struct ProposalSourceEvidence: Sendable, Equatable, Identifiable {+ public var source: SourceRef+ public var fingerprint: String+ public var text: String+ public var displayTitle: String+ public var capturedAt: Date?+ public var isChapter: Bool+ public var stableOrder: Int+ public var spellings: [String]+ public var isDecisionBasis: Bool+ public var id: String { source.orderToken + "\u{1F}" + fingerprint }+ public init(source: ExtractionSource, spellings: [String], isDecisionBasis: Bool = true) {+ self.source = source.source; self.fingerprint = source.fingerprint; self.text = source.text+ self.displayTitle = source.displayTitle; self.capturedAt = source.capturedAt+ self.isChapter = source.isChapter; self.stableOrder = source.stableOrder+ self.spellings = Array(Set(spellings)).sorted(); self.isDecisionBasis = isDecisionBasis+ }+ public static func merged(_ values: [Self]) -> [Self] {+ var result: [Self] = []+ for value in values {+ if let index = result.firstIndex(where: { $0.id == value.id && $0.text == value.text }) {+ result[index].spellings = Array(Set(result[index].spellings + value.spellings)).sorted()+ result[index].isDecisionBasis = result[index].isDecisionBasis || value.isDecisionBasis+ } else { result.append(value) }+ }+ return result.sorted { ($0.stableOrder, $0.source.orderToken, $0.fingerprint) < ($1.stableOrder, $1.source.orderToken, $1.fingerprint) } } } @@ -81,15 +122,17 @@ public struct GroundedCandidate: Sendable, Equatable { public var proposedAliases: [String] public var source: SourceRef public var facts: [GroundedFact]+ public var sourceEvidence: ProposalSourceEvidence? public init(name: String, nameKey: String, kind: RecordKind, proposedAliases: [String],- source: SourceRef, facts: [GroundedFact]) {+ source: SourceRef, facts: [GroundedFact], sourceEvidence: ProposalSourceEvidence? = nil) { self.name = name self.nameKey = nameKey self.kind = kind self.proposedAliases = proposedAliases self.source = source self.facts = facts+ self.sourceEvidence = sourceEvidence } } @@ -102,12 +145,14 @@ public struct ExistingCharacter: Sendable, Equatable { /// Minted at accept or create and kept through renames (Q19/Q46). public var retainedKey: String public var aliases: [String]+ public var isTorn: Bool - public init(id: UUID, name: String, retainedKey: String, aliases: [String] = []) {+ public init(id: UUID, name: String, retainedKey: String, aliases: [String] = [], isTorn: Bool = false) { self.id = id self.name = name self.retainedKey = retainedKey self.aliases = aliases+ self.isTorn = isTorn } /// Every key this character answers to, for deduping proposed aliases.@@ -125,7 +170,7 @@ public struct ExistingCharacter: Sendable, Equatable { currentNameKey: RecordNameKey.normalize(name), retainedKey: retainedKey, aliasKeys: aliases.map(RecordNameKey.normalize),- isTorn: false)+ isTorn: isTorn) } } @@ -137,6 +182,7 @@ public struct ExistingCharacter: Sendable, Equatable { /// against accepted place facts and place suppressions only, and a skipped /// place "Bay" must never silence a character "Bay". public struct CharacterExtractionContext: Sendable, Equatable {+ public var mentionIndex: AssociationMentionIndex /// The work's records of each kind, in the terms matching cares about. public var records: [RecordKind: [ExistingCharacter]] /// Identity triples already accepted. No pass re-proposes these — manual@@ -158,7 +204,9 @@ public struct CharacterExtractionContext: Sendable, Equatable { public init(records: [RecordKind: [ExistingCharacter]], acceptedFacts: [RecordKind: Set<RecordFactIdentity>], suppressedNameKeys: [RecordKind: Set<String>],- suppressedFacts: [RecordKind: Set<RecordFactIdentity>]) {+ suppressedFacts: [RecordKind: Set<RecordFactIdentity>],+ mentionIndex: AssociationMentionIndex = .empty) {+ self.mentionIndex = mentionIndex self.records = records self.acceptedFacts = acceptedFacts self.suppressedNameKeys = suppressedNameKeys@@ -216,6 +264,7 @@ public struct ProposalKey: Sendable, Hashable { public struct ExtractionProposal: Sendable, Equatable { public enum Target: Sendable, Equatable { case newRecord+ case unresolved case existing(UUID) } @@ -247,6 +296,11 @@ public struct ExtractionProposal: Sendable, Equatable { /// against. A proposal is stale when **any** of them has changed (Req 2.7, /// Q83). public var citedRevisions: [SourceRef: String]+ public var mentions: [AssociationMentionDecision]+ public var reviewAcknowledgements: [AssociationReviewAcknowledgement]+ public var sourceEvidence: [ProposalSourceEvidence]+ public var isNoteFirst: Bool+ public var citedMentionEligibility: [SourceRef: String] /// The pass that produced the row, carried because suppression reads /// differently on each: the sweep honours it, the manual pass ignores it /// for both kinds (Req 1.11, Q17, Q49).@@ -262,7 +316,9 @@ public struct ExtractionProposal: Sendable, Equatable { public init(name: String, nameKey: String, kind: RecordKind, proposedAliases: [String], target: Target, facts: [GroundedFact], citedRevisions: [SourceRef: String], displayedKind: RecordKind? = nil, returnedKinds: Set<RecordKind>? = nil,- pass: ExtractionPassKind = .automatic) {+ pass: ExtractionPassKind = .automatic, mentions: [AssociationMentionDecision] = [],+ citedMentionEligibility: [SourceRef: String] = [:], reviewAcknowledgements: [AssociationReviewAcknowledgement] = [],+ sourceEvidence: [ProposalSourceEvidence] = [], isNoteFirst: Bool = false) { self.name = name self.nameKey = nameKey self.kind = kind@@ -272,6 +328,10 @@ public struct ExtractionProposal: Sendable, Equatable { self.target = target self.facts = facts self.citedRevisions = citedRevisions+ self.mentions = mentions+ self.citedMentionEligibility = citedMentionEligibility+ self.reviewAcknowledgements = reviewAcknowledgements+ self.sourceEvidence = sourceEvidence; self.isNoteFirst = isNoteFirst self.pass = pass }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterGrounding.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterGrounding.swiftindex 66404eb6..7237790f 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterGrounding.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/CharacterGrounding.swift@@ -78,6 +78,12 @@ public enum CharacterGrounding { }, kind: .place, cap: CharacterExtractionBounds.maximumPlaceCandidates, in: haystack, source: source.source, into: &outcome)+ outcome.candidates = outcome.candidates.map { candidate in+ var value = candidate+ value.sourceEvidence = ProposalSourceEvidence(source: source,+ spellings: [candidate.name] + candidate.proposedAliases)+ return value+ } return outcome } @@ -151,74 +157,17 @@ public enum CharacterGrounding { /// pronoun stands for, and without the model's reading there is nothing /// host-side to fold them into. private static func dropReason(for name: String, in haystack: String) -> GroundingDrop.Reason? {- guard !name.isEmpty else { return .emptyName }- guard !pronouns.contains(RecordNameKey.normalize(name)) else { return .pronounName }- guard name.count <= CharacterExtractionBounds.maximumNameLength else { return .nameTooLong }- switch presence(of: name, in: haystack) {- case .absent: return .nameNotInSource- case .lowercaseOnly: return .nameNeverCapitalised- case .present: return nil- }- }-- private enum Presence {- case absent- /// In the source, but never with a capital letter.- case lowercaseOnly- case present- }-- /// One case-insensitive scan answering Req 1.6 and Q115 together: is the- /// name in the source, and is it ever written there with a capital letter?- ///- /// The junk the prompt cannot talk the model out of — "sex", "hotel",- /// "general", "gun girl", "the weird lady" — is written in lowercase in the- /// note, and the reader's real names never are: 84 of 84 name occurrences- /// in the export the prototype ran over carry a capital. So the note's own- /// spelling is the one deterministic signal that separates a proper name- /// from a common noun, and it is checked *any letter, any occurrence*- /// rather than first-letter-of-every-word so that "prince Kyllian",- /// "van Helsing" and "al-Hakim" all pass on their capitalised part.- /// "Capital" means a cased letter that is not lowercase, so titlecase- /// digraphs count too.- ///- /// What it does not catch, by design: capitalised places ("Tokyo",- /// "Brockton Bay" — no safe host-side rule exists; see Decision 6) and a- /// common noun that opens a sentence ("Sex was the whole chapter"). Both- /// stay the review flow's job. A name with no cased letters at all- /// (Hangul, kana, CJK) is present the moment it is found: there is nothing- /// to check.- private static func presence(of name: String, in haystack: String) -> Presence {- let needle = name.precomposedStringWithCanonicalMapping- let uncased = !needle.contains(where: \.isCased)- var found = Presence.absent- var searchFrom = haystack.startIndex- while let range = haystack.range(of: needle, options: [.caseInsensitive],- range: searchFrom..<haystack.endIndex) {- if uncased || haystack[range].contains(where: { $0.isCased && !$0.isLowercase }) {- return .present- }- found = .lowercaseOnly- searchFrom = range.upperBound+ guard let failure = RecordMentionGrounding.failure(for: name, in: haystack) else { return nil }+ switch failure {+ case .emptyName: return .emptyName+ case .pronounName: return .pronounName+ case .nameTooLong: return .nameTooLong+ case .nameNotInSource: return .nameNotInSource+ case .nameNeverCapitalised: return .nameNeverCapitalised }- return found } - /// English personal pronouns, compared against the name *key* so case is- /// already folded. Exactly these: the shipped sweep proposed "He", "his"- /// and "they" as characters, and "everyone"-class words stay the prompt's- /// job (Q55) — a stoplist of common nouns would be guessing at the corpus.- /// A story whose character is literally named "It" loses that candidate- /// to this rule; hand-creation (Q39) is the way back.- static let pronouns: Set<String> = [- "i", "me", "my", "mine", "myself",- "you", "your", "yours", "yourself", "yourselves",- "he", "him", "his", "himself",- "she", "her", "hers", "herself",- "it", "its", "itself",- "we", "us", "our", "ours", "ourselves",- "they", "them", "their", "theirs", "themselves",- ]+ static let pronouns = RecordMentionGrounding.pronouns private static func split(_ name: String, in haystack: String) -> GroundedName? { guard name.contains("/") else { return nil }
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/ExtractionResult.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/ExtractionResult.swiftindex d41d4d48..40379ddc 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/ExtractionResult.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/ExtractionResult.swift@@ -88,6 +88,31 @@ public struct ExtractionResult: Sendable, Equatable { } } +/// The live model contract deliberately contains names only. Legacy fact DTOs+/// above remain available for compatibility, grounding tests and saved-data tools.+@Generable+public struct NamedExtractionEntity: Sendable, Equatable {+ @Guide(description: "The name exactly as the saved note spells it. Never infer an unnamed entity.")+ public var name: String+ public init(name: String = "") { self.name = name }+}++@Generable+public struct NamedExtractionResult: Sendable, Equatable {+ @Guide(description: "Named story characters explicitly named in the note. Empty if none.")+ public var characters: [NamedExtractionEntity]+ @Guide(description: "Named story places explicitly named in the note. Empty if none.")+ public var places: [NamedExtractionEntity]+ public init(characters: [NamedExtractionEntity] = [], places: [NamedExtractionEntity] = []) {+ self.characters = characters+ self.places = places+ }+ public var legacyValue: ExtractionResult {+ ExtractionResult(characters: characters.map { .init(name: $0.name) },+ places: places.map { .init(name: $0.name) })+ }+}+ /// The seam between the extraction pipeline and the on-device model. /// Everything above it is testable on the host without Apple Intelligence. public protocol CharacterExtractionModelClient: Sendable {
diff --git a/Packages/AsterismCore/Sources/AsterismIntelligence/FoundationCharacterExtractionModelClient.swift b/Packages/AsterismCore/Sources/AsterismIntelligence/FoundationCharacterExtractionModelClient.swiftindex 7245849a..881fee9f 100644--- a/Packages/AsterismCore/Sources/AsterismIntelligence/FoundationCharacterExtractionModelClient.swift+++ b/Packages/AsterismCore/Sources/AsterismIntelligence/FoundationCharacterExtractionModelClient.swift@@ -23,9 +23,9 @@ public struct FoundationCharacterExtractionModelClient: CharacterExtractionModel let session = LanguageModelSession(instructions: Self.instructions) // `Response<Content>` is not Sendable, so only its content leaves here. let response = try await session.respond(to: Self.prompt(for: source),- generating: ExtractionResult.self,+ generating: NamedExtractionResult.self, options: Self.generationOptions)- return response.content+ return response.content.legacyValue } /// Greedy sampling. The prototype measured a fact-triple Jaccard of 1.00@@ -44,28 +44,8 @@ public struct FoundationCharacterExtractionModelClient: CharacterExtractionModel // MARK: - Prompting - /// The prototype's instructions, tightened by its findings (Q55) and by- /// the first real runs (Q113, Q114), then widened to both kinds by- /// `place-extraction`'s own prototype (its Q43, Q62).- ///- /// The junk tail the character prototype produced — "everyone", "the- /// general", "redevelopment law" — was ~25% of candidates and is- /// prompt-shaped, so the task is stated as **named story characters**, and- /// the model is told what is not one. The shipped sweep then added two more- /// shapes: pronouns reported as characters ("He", "his", "they"), whose- /// facts belong to the named character they stand for, and places or- /// activities ("hotel", "sex") reported as if they were people. What the- /// tightening misses, the review flow catches; what it must never do is- /// invent, which is why the verbatim-quote rule is stated twice and- /// grounding checks it anyway.- ///- /// The place paragraph and the epithet sentence are the combined request's- /// only additions, and the not-a-character list deliberately keeps "places"- /// so the model files them under places rather than under characters. This- /// is arm B of `specs/place-extraction/prototype/Sources/main.swift`- /// **verbatim**: Req 1.8's regression measurement and the Req 6.1 timings in- /// `prototype/prototype-findings.md` are this text's, so a reword is a- /// re-measurement (Q62).+ /// Names-only extraction; saved source prose is displayed directly and never+ /// synthesized into facts or annotations. static let instructions = """ You extract named story characters and named places from a reader's private \ note about one chapter of a serial story. The note is informal and may be \@@ -90,18 +70,10 @@ public struct FoundationCharacterExtractionModelClient: CharacterExtractionModel an object, an event, or the real world outside the story. If the note names \ no places, return an empty list of places. - A pronoun is never a character. When the note says "he", "she", "they", \- "his", "her", "their" or "it", work out which named character the word \- refers to and report the fact under that character's name. If you cannot \- tell which named character a pronoun refers to, leave that fact out.-+ A pronoun is never a character. Do not infer a name from a pronoun. Spell each name exactly as the note spells it, character for character.-- For every fact, copy the supporting words out of the note into the quote \- field verbatim — the same characters, in the same order, with the same \- spelling, punctuation and capitalisation. Do not paraphrase, translate, \- correct or shorten them. A fact you cannot support with the note's own \- words is a fact you must not report. A character or place the note only \+ Copy names verbatim. Return names only: no facts, summaries, paraphrases,+ quotes, annotations or other prose. A character or place the note only mentions by name is reported with no facts. """ @@ -114,7 +86,7 @@ public struct FoundationCharacterExtractionModelClient: CharacterExtractionModel \(source.text) List the named story characters and the named places this note mentions, \- with any facts it states about them.+ returning names only. """ }
diff --git a/Packages/AsterismCore/Sources/AsterismPresentation/WorksListOptions.swift b/Packages/AsterismCore/Sources/AsterismPresentation/WorksListOptions.swiftindex 9fdf2547..0322783d 100644--- a/Packages/AsterismCore/Sources/AsterismPresentation/WorksListOptions.swift+++ b/Packages/AsterismCore/Sources/AsterismPresentation/WorksListOptions.swift@@ -35,7 +35,7 @@ public nonisolated enum WorksListStorageKey { /// App Group — so this is the seam the test pins, and a preference added /// later that is not reset is a visible omission here rather than a /// forgotten line there.- public static let seededLaunchResets = [sort, RestoreStorageKey.worksDestination, RestoreStorageKey.selectedSidebarItem, RestoreStorageKey.todayPath, RestoreStorageKey.libraryPath]+ public static let seededLaunchResets = [sort, RestoreStorageKey.worksDestination, RestoreStorageKey.selectedSidebarItem, RestoreStorageKey.todayPath, RestoreStorageKey.libraryPath, RestoreStorageKey.selectedTab, RestoreStorageKey.selectedTodayEntryID, RestoreStorageKey.selectedWorkID] + WorksGroup.allCases.map { "worksGroup.sort." + $0.rawValue } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationArchiveCodecTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationArchiveCodecTests.swiftnew file mode 100644index 00000000..c6d050df--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationArchiveCodecTests.swift@@ -0,0 +1,66 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Association archive codec precision")+struct AssociationArchiveCodecTests {+ private func payload() -> BackupV20Payload {+ .init(library: .init(entries: [], works: [], sites: [], titlePatterns: [], urlRules: []))+ }+ @Test func exactRawTimestampAndMalformedUnicodeVariantsRoundTrip() throws {+ let instant = Date(timeIntervalSinceReferenceDate: 813_456_789.1234567)+ let event = AssociationEvent()+ event.workID = UUID(); event.recordKindRaw = "Café"; event.eventData = Data([0xff])+ event.recordedAt = instant+ let first = AssociationRawEvent(event)+ var second = first+ second.recordKindRaw = "Cafe\u{301}"+ let note = PairNoteVersion()+ note.workID = event.workID; note.operationRaw = "Café"; note.text = "Cafe\u{301} exact"+ note.authoredAt = instant+ let noteFirst = AssociationRawNote(note)+ var noteSecond = noteFirst+ noteSecond.operationRaw = "Cafe\u{301}"+ #expect(first != second)+ #expect(noteFirst != noteSecond)+ var original = payload()+ original.associationEvents = [first, second]+ original.pairNoteVersions = [noteFirst, noteSecond]+ let data = try BackupV20Codec.encode(payload: original,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let decoded = try BackupV20Codec.decode(data)+ #expect(decoded.payload == original)+ #expect(decoded.payload.associationEvents.count == 2)+ #expect(decoded.payload.pairNoteVersions.count == 2)+ #expect(decoded.payload.associationEvents.allSatisfy {+ $0.recordedAt.timeIntervalSinceReferenceDate.bitPattern == instant.timeIntervalSinceReferenceDate.bitPattern+ })+ #expect(decoded.payload.pairNoteVersions.allSatisfy {+ $0.authoredAt.timeIntervalSinceReferenceDate.bitPattern == instant.timeIntervalSinceReferenceDate.bitPattern+ })+ #expect(Array(try #require(decoded.payload.associationEvents[1].recordKindRaw).utf8) == Array("Cafe\u{301}".utf8))+ #expect(Array(decoded.payload.pairNoteVersions[1].operationRaw.utf8) == Array("Cafe\u{301}".utf8))+ }+ @Test func nativeArraysAreRequiredAndChecksummed() throws {+ let data = try BackupV20Codec.encode(payload: payload(),+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ var object = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any])+ var body = try #require(object["payload"] as? [String: Any])+ body.removeValue(forKey: "pairNoteVersions"); object["payload"] = body+ #expect(throws: (any Error).self) { try BackupV20Codec.decode(JSONSerialization.data(withJSONObject: object)) }+ body["pairNoteVersions"] = []; body["associationEvents"] = [["id": UUID().uuidString]]+ object["payload"] = body+ #expect(throws: (any Error).self) { try BackupV20Codec.decode(JSONSerialization.data(withJSONObject: object)) }+ }+ @Test func boundedPredecessorsHaveAbsentFeatureData() throws {+ let old = BackupV18Fixtures.payload()+ let data18 = try BackupV18Codec.encode(payload: old, metadata: BackupV18Fixtures.metadata())+ let converted18 = try BackupV20Codec.decodeCompatible(data18).payload+ #expect(converted18.associationEvents.isEmpty && converted18.pairNoteVersions.isEmpty)+ let data19 = try BackupV19Codec.encode(payload: payload().library,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let converted19 = try BackupV20Codec.decodeCompatible(data19).payload+ #expect(converted19.associationEvents.isEmpty && converted19.pairNoteVersions.isEmpty)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationArchiveIntegrationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationArchiveIntegrationTests.swiftnew file mode 100644index 00000000..2c6c17a9--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationArchiveIntegrationTests.swift@@ -0,0 +1,358 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Association full archive integration", .serialized)+struct AssociationArchiveIntegrationTests {+ @Test func fullExporterRestorePreservesContradictoryRawBodiesAndWholeReceipts() async throws {+ let source = try await M5Fixture()+ let pair = AssociationPair(workID: UUID(), entryID: UUID(), kind: .character, recordID: UUID())+ let instant = Date(timeIntervalSinceReferenceDate: 813_456_789.1234567)+ try await source.repository.withLockedContext(mode: .exclusive, operation: "seeding full raw archive fixture") { context in+ let work = Work(id: pair.workID, displayTitle: "Synthetic raw archive", timestamp: M5Fixture.epoch)+ let entry = Entry(id: pair.entryID, captureTitle: "Chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Alice arrived.")+ try entry.authorTarget(.init(kind: .chapter)); context.insert(work); context.insert(entry); entry.work = work; LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch)+ context.insert(CharacterRecord(id: pair.recordID, name: "Alice", nameKey: "alice", work: work))+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: [pair])+ let current = try #require(endpoints.current(pair))+ let core = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: ["alice"])))+ let inventory = AssociationLedgerInventory(events: [core])+ var first = core; first.validation = inventory.receipt(for: current)+ var other = core+ var different = current; different.sourceFingerprint = "other complete source revision"+ other.validation = inventory.receipt(for: different)+ context.insert(try AssociationEvent(event: first, recordedAt: instant))+ context.insert(try AssociationEvent(event: other, recordedAt: instant))+ let note = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [core.id], text: "Café", originalContext: "Original Café context", authoredAt: instant)+ let nfc = try PairNoteVersion(note: note), nfd = try PairNoteVersion(note: note)+ nfd.text = "Cafe\u{301}"+ let malformed = try PairNoteVersion(note: note)+ malformed.parentHeadIDsData = Data([0xff]); malformed.operationRaw = "Cafe\u{301}"+ context.insert(nfc); context.insert(nfd); context.insert(malformed)+ try context.save()+ }+ let original = try await source.repository.backupV20Snapshot()+ #expect(original.associationEvents.count == 2)+ #expect(original.pairNoteVersions.count == 3)+ let exporter = BackupV20Exporter(repository: source.repository,+ stagingDirectory: source.directory.appendingPathComponent("raw-archive-stage"))+ let result = try await exporter.export(metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ defer { exporter.cleanup(result) }+ let plan = try BackupImporter.plan(from: Data(contentsOf: result.fileURL))+ let restored = try await M5Fixture()+ _ = try await restored.repository.confirmImport(plan: plan)+ let snapshot = try await restored.repository.backupV20Snapshot()+ #expect(snapshot.associationEvents.count == 2 && snapshot.pairNoteVersions.count == 3)+ #expect(Set(snapshot.associationEvents.map(\.validationData)) == Set(original.associationEvents.map(\.validationData)))+ #expect(Set(snapshot.pairNoteVersions.map { Data($0.text.utf8) }) == Set(original.pairNoteVersions.map { Data($0.text.utf8) }))+ #expect(snapshot.pairNoteVersions.contains { $0.parentHeadIDsData == Data([0xff]) })+ #expect(snapshot.pairNoteVersions.allSatisfy { $0.authoredAt.timeIntervalSinceReferenceDate.bitPattern == instant.timeIntervalSinceReferenceDate.bitPattern })+ #expect(snapshot.associationEvents.allSatisfy { $0.recordedAt.timeIntervalSinceReferenceDate.bitPattern == instant.timeIntervalSinceReferenceDate.bitPattern })+ _ = try await restored.repository.confirmImport(plan: plan)+ let repeated = try await restored.repository.backupV20Snapshot()+ #expect(repeated.associationEvents.count == 2 && repeated.pairNoteVersions.count == 3)+ let reopened = try await LibraryRepository.openForApp(LibraryConfiguration(rootDirectory: restored.directory),+ clock: FixedRepositoryClock(M5Fixture.epoch)).repository+ let reopenedSnapshot = try await reopened.backupV20Snapshot()+ #expect(reopenedSnapshot.associationEvents.count == 2 && reopenedSnapshot.pairNoteVersions.count == 3)+ let raw = try await reopened.detachedAssociationNotes()+ #expect(raw.count == 3 && raw.allSatisfy { !$0.canRecover })+ #expect(Set(raw.map(\.id)).count == 3)+ await #expect(throws: BackupV18ExportError.self) { try await restored.repository.backupV19Snapshot() }+ await #expect(throws: BackupV18ExportError.self) { try await restored.repository.backupV18Snapshot() }+ withExtendedLifetime((source, restored)) {}+ }+ private func coherentSource() async throws -> (M5Fixture, AssociationPair, BackupV20Payload) {+ let fixture = try await M5Fixture()+ let pair = AssociationPair(workID: UUID(), entryID: UUID(), kind: .character, recordID: UUID())+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding coherent archive source") { context in+ let work = Work(id: pair.workID, displayTitle: "Synthetic coherent archive", timestamp: M5Fixture.epoch)+ let entry = Entry(id: pair.entryID, captureTitle: "Chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Nova arrived.")+ try entry.authorTarget(.init(kind: .chapter)); context.insert(work); context.insert(entry); entry.work = work; LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch)+ context.insert(CharacterRecord(id: pair.recordID, name: "Alice", nameKey: "alice", aliases: ["Nova"], work: work))+ try context.save()+ }+ _ = try await fixture.repository.commitDecision(.init(workID: pair.workID, kind: .character, action: .accept,+ displayedKeys: ["nova"], displayedTargetID: pair.recordID, proposedName: "Nova", mentions: [+ .init(entryID: pair.entryID, noteFingerprint: CharacterCoverageFingerprint.of("Nova arrived."), spellingKeys: ["nova"])]))+ return (fixture, pair, try await fixture.repository.backupV20Snapshot())+ }+ private func plan(_ payload: BackupV20Payload) throws -> BackupImportPlan {+ try BackupImporter.plan(from: BackupV20Codec.encode(payload: payload,+ metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch)))+ }+ @Test func coherentAliasAndSourceBundleRestoresWithoutArtificialLocalBarrier() async throws {+ let (source, pair, incoming) = try await coherentSource()+ let target = try await M5Fixture()+ _ = try await target.repository.confirmImport(plan: plan(.init(library: incoming.library)))+ try await target.repository.withLockedContext(mode: .exclusive, operation: "simulating source before matching metadata arrival") { context in+ for row in try context.fetch(FetchDescriptor<Entry>()) { row.note = "No supported name." }+ for row in try context.fetch(FetchDescriptor<CharacterRecord>()) { row.aliases = [] }+ try context.save()+ }+ _ = try await target.repository.confirmImport(plan: plan(incoming))+ let active = try await target.repository.chapterAssociations(entryID: pair.entryID).filter { !$0.activeAcceptanceIDs.isEmpty }+ #expect(active.count == 1 && active.first?.pair == pair)+ let restored = try await target.repository.backupV20Snapshot()+ #expect(restored.associationEvents == incoming.associationEvents)+ withExtendedLifetime((source, target)) {}+ }+ private final class FailAfterSourceCommit: RepositorySaveStrategy, @unchecked Sendable {+ private var sawFinalSource = false+ private var failed = false+ func save(_ context: ModelContext) throws {+ if sawFinalSource && !failed { failed = true; throw CocoaError(.fileWriteUnknown) }+ try context.save()+ if try context.fetch(FetchDescriptor<Entry>()).contains(where: { $0.note == "Nova arrived." }) { sawFinalSource = true }+ }+ }+ @Test("Changed existing source cannot revive known inactive root, even after a later import chunk fails", arguments: [false, true])+ func changedSourceDoesNotReviveKnownInactiveRoot(failLaterChunk: Bool) async throws {+ let (source, pair, initial) = try await coherentSource()+ let target = try await M5Fixture()+ _ = try await target.repository.confirmImport(plan: plan(initial))+ try await target.repository.withLockedContext(mode: .exclusive, operation: "simulating unsupported synced note revision") { context in+ for row in try context.fetch(FetchDescriptor<Entry>()) { row.note = "No supported name." }+ try context.save()+ }+ #expect(try await target.repository.chapterAssociations(entryID: pair.entryID).allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ var incoming = initial+ var new = try #require(initial.associationEvents.first)+ new.id = UUID(); incoming.associationEvents = [new]+ let incomingPlan = try plan(incoming)+ if failLaterChunk {+ do {+ _ = try await target.repository.withLockedContext(mode: .exclusive, operation: "injecting later archive chunk failure") { context in+ try LibraryRepository.upsert(incomingPlan.payload, exportedAt: M5Fixture.epoch, importedAt: M5Fixture.epoch,+ context: context, batchSize: 1, saveStrategy: FailAfterSourceCommit())+ }+ Issue.record("injected later chunk must fail")+ } catch { }+ #expect(try await target.repository.entry(id: pair.entryID).note == "Nova arrived.")+ #expect(try await target.repository.chapterAssociations(entryID: pair.entryID).allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ }+ _ = try await target.repository.confirmImport(plan: incomingPlan)+ #expect(try await target.repository.chapterAssociations(entryID: pair.entryID).allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ let once = try await target.repository.backupV20Snapshot()+ #expect(Set(once.associationEvents.map(\.id)).isSuperset(of: Set(initial.associationEvents.map(\.id) + [new.id])))+ #expect(once.associationEvents.contains { if case .invalidate = $0.value?.payload { return true }; return false })+ _ = try await target.repository.confirmImport(plan: incomingPlan)+ #expect(try await target.repository.backupV20Snapshot().associationEvents == once.associationEvents)+ withExtendedLifetime((source, target)) {}+ }++ @Test func beforeActiveCarryPreservesIncomingWholeVariantsAndStaleLocalVariant() async throws {+ let (source, pair, initial) = try await coherentSource()+ let target = try await M5Fixture()+ _ = try await target.repository.confirmImport(plan: plan(initial))+ let local = try #require(initial.associationEvents.first { if case .accept = $0.value?.payload { return true }; return false })+ let initialEvent = try #require(local.value), initialReceipt = try #require(initialEvent.validation)+ var stale = initialEvent+ var staleReceipt = initialReceipt; staleReceipt.sourceFingerprint = "stale local whole variant"+ stale.validation = staleReceipt+ let capturedStale = stale+ try await target.repository.withLockedContext(mode: .exclusive, operation: "seeding stale whole local receipt") { context in+ context.insert(try AssociationEvent(event: capturedStale, recordedAt: M5Fixture.epoch)); try context.save()+ }+ let entry = try await source.repository.entry(id: pair.entryID)+ _ = try await source.repository.updateEntry(id: pair.entryID, basis: .init(entry: entry), note: "NOVA arrived.", rating: nil)+ var incoming = try await source.repository.backupV20Snapshot()+ var current = try #require(incoming.associationEvents.first { if case .accept = $0.value?.payload { return true }; return false })+ current.id = UUID()+ let currentValue = try #require(current.value)+ var variant = currentValue+ var otherReceipt = try #require(currentValue.validation); otherReceipt.sourceFingerprint = "other incoming whole variant"+ variant.validation = otherReceipt+ let rawVariant = AssociationRawEvent(try AssociationEvent(event: variant, recordedAt: M5Fixture.epoch))+ incoming.associationEvents.removeAll { if case .accept = $0.value?.payload { return true }; return false }+ incoming.associationEvents += [local, current, rawVariant]+ let importPlan = try plan(incoming)+ _ = try await target.repository.confirmImport(plan: importPlan)+ let once = try await target.repository.backupV20Snapshot()+ #expect(Set(once.associationEvents.map(\.variantIdentity)).isSuperset(of: Set(incoming.associationEvents.map(\.variantIdentity))))+ let staleRaw = AssociationRawEvent(try AssociationEvent(event: stale, recordedAt: M5Fixture.epoch))+ #expect(once.associationEvents.contains { $0.variantIdentity == staleRaw.variantIdentity })+ let links = try await target.repository.chapterAssociations(entryID: pair.entryID).filter { !$0.activeAcceptanceIDs.isEmpty }+ #expect(links.first?.activeAcceptanceIDs == [local.id, current.id])+ _ = try await target.repository.confirmImport(plan: importPlan)+ #expect(try await target.repository.backupV20Snapshot().associationEvents == once.associationEvents)+ withExtendedLifetime((source, target)) {}+ }++ @Test("Entry normalization uses winning changes and holds inactive roots across interrupted retries", arguments: [0, 1, 2, 3])+ func normalizationChangeCannotLetActualEntryWriterReviveKnownInactiveRoot(mode: Int) async throws {+ let source = try await M5Fixture(), target = try await M5Fixture()+ let workA = UUID(), workB = UUID(), entryID = UUID(), recordID = UUID()+ try await source.repository.seedM5Rows(sites: [.init(hostname: "synthetic.test")], works: [+ .init(id: workA, displayTitle: "Same", hostname: "synthetic.test", titleProvenance: .parsed,+ lastParsedTitle: "Same", createdAt: M5Fixture.epoch),+ .init(id: workB, displayTitle: "Same", hostname: "synthetic.test", titleProvenance: .parsed,+ lastParsedTitle: "Same", createdAt: M5Fixture.epoch.addingTimeInterval(10))], entries: [+ .init(id: entryID, captureTitle: "Chapter", hostname: "synthetic.test", path: "one", note: "Nova arrived.", workID: workA)],+ characters: [.init(id: recordID, name: "Alice", aliases: ["Nova"], workID: workA)])+ _ = try await source.repository.commitDecision(.init(workID: workA, kind: .character, action: .accept,+ displayedKeys: ["nova"], displayedTargetID: recordID, proposedName: "Nova", mentions: [+ .init(entryID: entryID, noteFingerprint: CharacterCoverageFingerprint.of("Nova arrived."), spellingKeys: ["nova"])]))+ if mode == 3 {+ try await source.repository.withLockedContext(mode: .exclusive, operation: "capturing an old receipt that knows an existing barrier") { context in+ let barrier = AssociationLedgerEvent(payload: .invalidate(.entry(workID: workA, entryID: entryID)))+ context.insert(try AssociationEvent(event: barrier, recordedAt: M5Fixture.epoch))+ let rows = try context.fetch(FetchDescriptor<AssociationEvent>())+ let ledger = AssociationLedgerInventory(events: rows.compactMap(\.ledgerValue))+ let pair = AssociationPair(workID: workA, entryID: entryID, kind: .character, recordID: recordID)+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: [pair])+ let current = try #require(endpoints.current(pair))+ for row in rows {+ if case .accept = row.ledgerValue?.payload { row.validationData = try JSONBlob.encode(ledger.receipt(for: current)) }+ }+ try context.save()+ }+ }+ let initial = try await source.repository.backupV20Snapshot()+ var localInitial = initial+ if mode == 3 { localInitial.associationEvents.removeAll { if case .accept = $0.value?.payload { return true }; return false } }+ _ = try await target.repository.confirmImport(plan: plan(localInitial))+ let archiveEntry = try #require(initial.library.entries.first)+ try await target.repository.withLockedContext(mode: .exclusive, operation: "seeding split manual owners before normalization changes") { context in+ let works = try context.fetch(FetchDescriptor<Work>())+ let other = try #require(works.first { $0.id == workB })+ other.lastParsedTitle = "Other"; other.displayTitle = "Other"+ if mode == 0 { other.modifiedAt = M5Fixture.epoch.addingTimeInterval(1000) }+ let original = try #require(try context.fetch(FetchDescriptor<Entry>()).first { $0.id == entryID })+ original.note = "No supported names."+ let twin = ArchiveRecordBuilders.makeEntry(archiveEntry.predecessorRecord)+ twin.note = original.note; context.insert(twin); twin.work = other; twin.site = original.site+ try context.save()+ let rows = [original, twin]+ let canonical = try LibraryRepository.canonicalWorkIDs(normalising: rows, context: context)+ #expect(LibraryRepository.entryGroup(id: entryID, rows: rows, canonicalWorkIDs: canonical)?.isTorn == true)+ }+ var incoming = localInitial+ if mode != 3 {+ incoming.associationEvents = incoming.associationEvents.map { raw in+ var copy = raw; copy.id = UUID(); return copy+ }+ }+ let incomingPlan = try plan(incoming)+ if mode == 2 {+ do {+ _ = try await target.repository.withLockedContext(mode: .exclusive, operation: "failing after the normalization-dependent source chunk") { context in+ try LibraryRepository.upsert(incomingPlan.payload, exportedAt: M5Fixture.epoch, importedAt: M5Fixture.epoch,+ context: context, batchSize: 1, saveStrategy: FailAfterSourceCommit())+ }+ Issue.record("injected normalization import failure must throw")+ } catch { }+ let reopened = try await LibraryRepository.openForApp(LibraryConfiguration(rootDirectory: target.directory),+ clock: FixedRepositoryClock(M5Fixture.epoch)).repository+ #expect(try await reopened.chapterAssociations(entryID: entryID).allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ }+ _ = try await target.repository.confirmImport(plan: incomingPlan)+ try await target.repository.withLockedContext(mode: .shared, operation: "checking final normalized writer and early guard") { context in+ let rows = try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { $0.id == entryID }))+ #expect(rows.count == 2)+ if mode == 0 {+ #expect(rows.allSatisfy { $0.note == "No supported names." })+ #expect(Set(rows.compactMap { $0.work?.id }) == [workA, workB])+ } else {+ #expect(rows.allSatisfy { $0.note == "Nova arrived." && $0.work?.id == workA })+ let canonical = try LibraryRepository.canonicalWorkIDs(normalising: rows, context: context)+ #expect(LibraryRepository.entryGroup(id: entryID, rows: rows, canonicalWorkIDs: canonical)?.isTorn == false)+ }+ let barriers = try context.fetch(FetchDescriptor<AssociationEvent>()).compactMap(\.ledgerValue)+ .filter { if case .invalidate = $0.payload { return true }; return false }+ #expect(mode == 0 ? barriers.isEmpty : !barriers.isEmpty)+ if mode == 3 { #expect(!Set(barriers.map(\.id)).subtracting(Set(localInitial.associationEvents.map(\.id))).isEmpty) }+ }+ #expect(try await target.repository.chapterAssociations(entryID: entryID).allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ if mode == 3 {+ let unseen = try #require(initial.associationEvents.first { if case .accept = $0.value?.payload { return true }; return false })+ try await target.repository.withLockedContext(mode: .exclusive, operation: "arriving the previously unseen old receipt after normalized import") { context in+ context.insert(AssociationEvent(raw: unseen)); try context.save()+ }+ #expect(try await target.repository.chapterAssociations(entryID: entryID).allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ }+ let once = try await target.repository.withLockedContext(mode: .shared, operation: "capturing normalization retry raw rows") { context in+ try context.fetch(FetchDescriptor<AssociationEvent>()).map(AssociationRawEvent.init)+ }+ _ = try await target.repository.confirmImport(plan: incomingPlan)+ let repeated = try await target.repository.withLockedContext(mode: .shared, operation: "checking normalization retry has no metadata growth") { context in+ try context.fetch(FetchDescriptor<AssociationEvent>()).map(AssociationRawEvent.init)+ }+ #expect(Set(once.map(\.variantIdentity)) == Set(repeated.map(\.variantIdentity)))+ #expect(once.count == repeated.count)+ withExtendedLifetime((source, target)) {}+ }++ @Test("Missing Work closure preserves unresolved pattern intent, never manual unattachment", arguments: [0, 1, 2])+ func missingWorkClosureRequiresUnchangedUnresolvedPatternIntent(mode: Int) async throws {+ let source = try await M5Fixture(), target = try await M5Fixture()+ let workID = UUID(), entryID = UUID(), characterID = UUID(), placeID = UUID()+ try await source.repository.seedM5Rows(sites: [.init(hostname: "closure.test", mode: .taught, wholeTitleRule: true)],+ works: [.init(id: workID, displayTitle: "Closure book", hostname: "closure.test")],+ entries: [.init(id: entryID, captureTitle: "Chapter one", hostname: "closure.test", path: "one",+ note: "Alice visits Harbor.", workID: workID)],+ characters: [.init(id: characterID, name: "Alice", workID: workID)],+ places: [.init(id: placeID, name: "Harbor", workID: workID)])+ try await source.repository.withLockedContext(mode: .exclusive, operation: "recording a valid pattern assignment for closure") { context in+ let entry = try #require(try context.fetch(FetchDescriptor<Entry>()).first)+ let pattern = try #require(try context.fetch(FetchDescriptor<TitlePattern>()).first)+ try entry.authorTarget(.init(kind: .chapter))+ entry.editCitations { $0.workAssignment = .pattern(.init(id: pattern.id)) }+ try context.save()+ }+ let pairs = [AssociationPair(workID: workID, entryID: entryID, kind: .character, recordID: characterID),+ AssociationPair(workID: workID, entryID: entryID, kind: .place, recordID: placeID)]+ for pair in pairs {+ let name = pair.kind == .character ? "Alice" : "Harbor"+ _ = try await source.repository.commitDecision(.init(workID: workID, kind: pair.kind, action: .accept,+ displayedKeys: [RecordNameKey.normalize(name)], displayedTargetID: pair.recordID, proposedName: name,+ mentions: [.init(entryID: entryID, noteFingerprint: CharacterCoverageFingerprint.of("Alice visits Harbor."),+ spellingKeys: [RecordNameKey.normalize(name)])]))+ let basis = try #require(try await source.repository.associationNoteBasis(pair: pair))+ #expect(try await source.repository.saveAssociationNote(basis: basis, text: "Exact \(name) observation") == .committed)+ }+ let incoming = try await source.repository.backupV20Snapshot()+ let importPlan = try plan(incoming)+ _ = try await target.repository.confirmImport(plan: importPlan)+ try await target.repository.withLockedContext(mode: .exclusive, operation: "simulating missing Work relationship arrival") { context in+ let entries = try context.fetch(FetchDescriptor<Entry>())+ for entry in entries {+ entry.work = nil+ if mode != 0 {+ entry.editCitations { $0.assignManually() }+ entry.intentionallyUnattached = mode == 1+ }+ }+ for record in try context.fetch(FetchDescriptor<CharacterRecord>()) { record.work = nil }+ for work in try context.fetch(FetchDescriptor<Work>()) { context.delete(work) }+ try context.save()+ #expect(try context.fetch(FetchDescriptor<Entry>()).count == 1)+ #expect(try context.fetch(FetchDescriptor<CharacterRecord>()).count == 1)+ #expect(try context.fetch(FetchDescriptor<Place>()).count == 1)+ }+ #expect(try await target.repository.chapterAssociations(entryID: entryID).allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ _ = try await target.repository.confirmImport(plan: importPlan)+ let active = try await target.repository.chapterAssociations(entryID: entryID).filter { !$0.activeAcceptanceIDs.isEmpty }+ #expect(mode == 0 ? Set(active.map(\.pair)) == Set(pairs) : active.isEmpty)+ let restored = try await target.repository.backupV20Snapshot()+ if mode == 0 {+ #expect(restored.associationEvents == incoming.associationEvents)+ #expect(restored.pairNoteVersions == incoming.pairNoteVersions)+ for pair in pairs {+ let basis = try #require(try await target.repository.associationNoteBasis(pair: pair))+ #expect(basis.heads.count == 1)+ #expect(basis.heads[0].text == (pair.kind == .character ? "Exact Alice observation" : "Exact Harbor observation"))+ }+ } else {+ #expect(restored.associationEvents.contains { if case .invalidate = $0.value?.payload { return true }; return false })+ #expect(try await target.repository.detachedAssociationNotes().count == 2)+ }+ _ = try await target.repository.confirmImport(plan: importPlan)+ #expect(try await target.repository.backupV20Snapshot() == restored)+ withExtendedLifetime((source, target)) {}+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationDuplicateTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationDuplicateTests.swiftnew file mode 100644index 00000000..955d377c--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationDuplicateTests.swift@@ -0,0 +1,228 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Association duplicate Work transitions", .serialized)+struct AssociationDuplicateTests {+ private struct Seed {+ let store: DuplicateStore+ let source: UUID+ let target: UUID+ let entry: UUID+ let roots: [AssociationPair: UUID]+ let inactive: UUID+ }+ private func seed(strategy: (any RepositorySaveStrategy)? = nil) throws -> Seed {+ let store = try DuplicateStore(saveStrategy: strategy)+ let site = store.addSite()+ let target = store.addWork(title: "Same Work", createdAt: 0, site: site)+ let source = store.addWork(title: "Same Work", createdAt: 10, site: site)+ let entry = store.addEntry(key: "one", capturedAt: 20, note: "Alice visited Harbor.", work: source, site: site)+ let character = CharacterRecord(name: "Alice", nameKey: "alice", work: source)+ let place = Place(name: "Harbor", nameKey: "harbor", workID: source.id)+ store.seed.insert(character); store.seed.insert(place)+ let pairs: [AssociationPair] = [+ .init(workID: source.id, entryID: entry.id, kind: .character, recordID: character.id),+ .init(workID: source.id, entryID: entry.id, kind: .place, recordID: place.id)]+ let endpoints = try AssociationEndpointInventory.read(context: store.seed, pairs: Set(pairs))+ var roots: [AssociationPair: UUID] = [:]+ for pair in pairs {+ let current = try #require(endpoints.current(pair))+ let core = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: current.evidence.map(\.key))))+ let inventory = AssociationLedgerInventory(events: [core])+ var event = core; event.validation = inventory.receipt(for: current)+ store.seed.insert(try AssociationEvent(event: event, recordedAt: DuplicateStore.epoch))+ roots[pair] = core.id+ let note = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [core.id], operation: .text,+ text: pair.kind == .character ? "Cafe\u{301} exact character" : "Harbor exact place",+ originalContext: "Original Café chapter")+ store.seed.insert(try PairNoteVersion(note: note))+ }+ let inactive = AssociationLedgerEvent(payload: .accept(.init(pair: pairs[0], spellingKeys: ["alice"])))+ store.seed.insert(try AssociationEvent(event: inactive, recordedAt: DuplicateStore.epoch))+ store.seed.insert(try PairNoteVersion(note: .init(pair: pairs[0], attachmentAcceptanceIDs: [inactive.id],+ text: "Unvalidated exact text remains detached", originalContext: "Original inactive origin")))+ try store.commit()+ return .init(store: store, source: source.id, target: target.id, entry: entry.id, roots: roots, inactive: inactive.id)+ }+ private func assertTransferred(_ value: Seed) throws {+ try value.store.read { context in+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [value.source, value.target])+ let pairs = Set(value.roots.keys.map {+ AssociationPair(workID: value.target, entryID: $0.entryID, kind: $0.kind, recordID: $0.recordID)+ })+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: pairs)+ let oldCharacter = try #require(value.roots.keys.first { $0.kind == .character })+ #expect(storage.notes.heads(for: oldCharacter).contains {+ $0.attachmentAcceptanceIDs == [value.inactive] && $0.text == "Unvalidated exact text remains detached"+ })+ for pair in pairs {+ let current = try #require(endpoints.current(pair))+ let active = storage.ledger.activeAcceptanceIDs(for: current)+ #expect(active.count == 1)+ #expect(!active.contains(value.inactive))+ let heads = storage.notes.heads(for: pair)+ #expect(heads.count == 1)+ #expect(heads.first?.attachmentAcceptanceIDs == AssociationDigest.ordered(Array(active)))+ let expected = pair.kind == .character ? "Cafe\u{301} exact character" : "Harbor exact place"+ #expect(heads.first.map { ExactScalarString($0.text) } == ExactScalarString(expected))+ #expect(heads.first.map { ExactScalarString($0.originalContext) } == ExactScalarString("Original Café chapter"))+ }+ }+ }+ @Test func observedWorkConvergenceMovesBothKindsAndExactHeadsBeforeDeletion() throws {+ let value = try seed()+ _ = try value.store.reconcile()+ try assertTransferred(value)+ #expect(try value.store.read { try $0.fetchCount(FetchDescriptor<Work>()) } == 2)+ let featureCount = try value.store.read {+ try $0.fetchCount(FetchDescriptor<AssociationEvent>()) + $0.fetchCount(FetchDescriptor<PairNoteVersion>())+ }+ _ = try value.store.reconcile()+ try assertTransferred(value)+ #expect(try value.store.read { try $0.fetchCount(FetchDescriptor<Work>()) } == 1)+ _ = try value.store.reconcile()+ #expect(try value.store.read {+ try $0.fetchCount(FetchDescriptor<AssociationEvent>()) + $0.fetchCount(FetchDescriptor<PairNoteVersion>())+ } == featureCount)+ withExtendedLifetime(value.store) {}+ }+ @Test func staleWorkDeletionPlanDoesNotTransferLateChildrenOrMintRoutes() throws {+ let value = try seed()+ _ = try value.store.reconcile()+ let lateEntry = UUID(), lateRecord = UUID()+ _ = try value.store.reconcile(afterDerivation: { context in+ let old = try #require(try context.fetch(FetchDescriptor<Work>()).first { $0.id == value.source })+ old.genericNotes = "Authored notes changed after verified plan"+ let entry = Entry(id: lateEntry, captureTitle: "Late", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: DuplicateStore.epoch, note: "Late Alice")+ try entry.authorTarget(.init(kind: .chapter)); context.insert(entry); entry.work = old+ let record = CharacterRecord(id: lateRecord, name: "Late Alice", nameKey: "late alice", work: old)+ context.insert(record)+ })+ try value.store.read { context in+ #expect(try context.fetch(FetchDescriptor<Entry>()).first { $0.id == lateEntry }?.work?.id == value.source)+ #expect(try context.fetch(FetchDescriptor<CharacterRecord>()).first { $0.id == lateRecord }?.work?.id == value.source)+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [value.source, value.target])+ #expect(!storage.ledger.pairs.contains { $0.entryID == lateEntry || $0.recordID == lateRecord })+ }+ withExtendedLifetime(value.store) {}+ }+ @Test func verifiedWorkDeletionTransfersCoherentLateChildrenButNeverAdoptsInactiveRoots() throws {+ let value = try seed()+ _ = try value.store.reconcile()+ let entryID = UUID(), characterID = UUID(), placeID = UUID()+ var lateRoots: [UUID] = []+ _ = try value.store.reconcile(afterDerivation: { context in+ let source = try #require(try context.fetch(FetchDescriptor<Work>()).first { $0.id == value.source })+ let entry = Entry(id: entryID, captureTitle: "Late chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: DuplicateStore.epoch, note: "Alice visited Harbor.")+ try entry.authorTarget(.init(kind: .chapter)); context.insert(entry); entry.work = source+ context.insert(CharacterRecord(id: characterID, name: "Alice", nameKey: "alice", work: source))+ context.insert(Place(id: placeID, name: "Harbor", nameKey: "harbor", workID: source.id))+ let pairs: Set<AssociationPair> = [+ .init(workID: source.id, entryID: entryID, kind: .character, recordID: characterID),+ .init(workID: source.id, entryID: entryID, kind: .place, recordID: placeID)]+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: pairs)+ let previous = try AssociationStorageInventory.read(context: context, workIDs: [source.id])+ for pair in pairs {+ let current = try #require(endpoints.current(pair))+ let core = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: current.evidence.map(\.key))))+ var accepted = core+ accepted.validation = previous.ledger.receipt(for: current)+ context.insert(try AssociationEvent(event: accepted, recordedAt: DuplicateStore.epoch))+ context.insert(try PairNoteVersion(note: .init(pair: pair, attachmentAcceptanceIDs: [core.id],+ text: "Cafe\u{301} late exact", originalContext: "Late origin")))+ lateRoots.append(core.id)+ }+ })+ try value.store.read { context in+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [value.source, value.target])+ let pairs: Set<AssociationPair> = [+ .init(workID: value.target, entryID: entryID, kind: .character, recordID: characterID),+ .init(workID: value.target, entryID: entryID, kind: .place, recordID: placeID)]+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: pairs)+ for pair in pairs {+ let current = try #require(endpoints.current(pair))+ let ids = storage.ledger.activeAcceptanceIDs(for: current)+ #expect(ids.count == 1 && ids.isDisjoint(with: Set(lateRoots)))+ #expect(storage.notes.heads(for: pair).first.map { ExactScalarString($0.text) } == ExactScalarString("Cafe\u{301} late exact"))+ }+ #expect(try context.fetchCount(FetchDescriptor<Work>()) == 1)+ }+ try assertTransferred(value)+ withExtendedLifetime(value.store) {}+ }++ private final class ArmedFailure: RepositorySaveStrategy, @unchecked Sendable {+ private let lock = NSLock()+ private var fail = false+ private var failures = 0+ func arm() { lock.withLock { fail = true } }+ var failureCount: Int { lock.withLock { failures } }+ func save(_ context: ModelContext) throws {+ let shouldFail = lock.withLock {+ if fail { fail = false; failures += 1; return true }; return false+ }+ if shouldFail { throw CocoaError(.fileWriteUnknown) }+ try context.save()+ }+ }+ @Test func failedWorkDeletionChunkReplaysCurrentOwnersSuppressionsAndExactHeadsOnce() throws {+ let strategy = ArmedFailure(), value = try seed(strategy: strategy)+ _ = try value.store.reconcile()+ let entryID = UUID(), characterID = UUID(), placeID = UUID()+ var roots: [UUID] = []+ _ = try value.store.reconcile(afterDerivation: { context in+ let source = try #require(try context.fetch(FetchDescriptor<Work>()).first { $0.id == value.source })+ let entry = Entry(id: entryID, captureTitle: "Late", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: DuplicateStore.epoch, note: "Alice visited Harbor.")+ try entry.authorTarget(.init(kind: .chapter)); context.insert(entry); entry.work = source+ context.insert(CharacterRecord(id: characterID, name: "Alice", nameKey: "alice", work: source))+ context.insert(Place(id: placeID, name: "Harbor", nameKey: "harbor", workID: source.id))+ context.insert(CharacterSuppression(work: source, nameKey: "blocked"))+ context.insert(PlaceSuppression(workID: source.id, nameKey: "blocked"))+ let pairs: Set<AssociationPair> = [+ .init(workID: source.id, entryID: entryID, kind: .character, recordID: characterID),+ .init(workID: source.id, entryID: entryID, kind: .place, recordID: placeID)]+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: pairs)+ let prior = try AssociationStorageInventory.read(context: context, workIDs: [source.id])+ for pair in pairs {+ let current = try #require(endpoints.current(pair))+ let core = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: current.evidence.map(\.key))),+ validation: prior.ledger.receipt(for: current))+ context.insert(try AssociationEvent(event: core, recordedAt: DuplicateStore.epoch))+ context.insert(try PairNoteVersion(note: .init(pair: pair, attachmentAcceptanceIDs: [core.id],+ text: "Cafe\u{301} replay text", originalContext: "Cafe\u{301} exact origin")))+ roots.append(core.id)+ }+ strategy.arm()+ })+ #expect(strategy.failureCount == 1)+ try value.store.read { context in+ #expect(try context.fetchCount(FetchDescriptor<Work>()) == 1)+ #expect(try context.fetch(FetchDescriptor<CharacterRecord>()).first { $0.id == characterID }?.work?.id == value.target)+ #expect(try context.fetch(FetchDescriptor<Place>()).first { $0.id == placeID }?.workID == value.target)+ #expect(try context.fetch(FetchDescriptor<CharacterSuppression>()).map { $0.work?.id } == [value.target])+ #expect(try context.fetch(FetchDescriptor<PlaceSuppression>()).map(\.workID) == [value.target])+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [value.source, value.target])+ let children = storage.rawEvents.compactMap(\.value).filter {+ guard case .accept(let core) = $0.payload, let rebind = core.rebind else { return false }+ return !Set(rebind.predecessorIDs).isDisjoint(with: Set(roots))+ }+ #expect(children.count == 2)+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: Set(children.compactMap { $0.payload.pair }))+ for child in children {+ let pair = try #require(child.payload.pair)+ #expect(storage.ledger.activeAcceptanceIDs(for: try #require(endpoints.current(pair))) == [child.id])+ let heads = storage.notes.heads(for: pair)+ #expect(heads.count == 1)+ #expect(heads.first.map { ExactScalarString($0.text) } == ExactScalarString("Cafe\u{301} replay text"))+ #expect(heads.first.map { ExactScalarString($0.originalContext) } == ExactScalarString("Cafe\u{301} exact origin"))+ }+ }+ withExtendedLifetime(value.store) {}+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationHistoricalContextTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationHistoricalContextTests.swiftnew file mode 100644index 00000000..a3b4e3f0--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationHistoricalContextTests.swift@@ -0,0 +1,44 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite struct AssociationHistoricalContextTests {+ @Test func systemRebindCannotConsumeParentWithOnlyContextScalarsChanged() {+ let work = UUID(), entry = UUID(), destinationEntry = UUID(), record = UUID()+ let pair = AssociationPair(workID: work, entryID: entry, kind: .character, recordID: record)+ let destination = AssociationPair(workID: work, entryID: destinationEntry, kind: .character, recordID: record)+ let original = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: ["alice"])))+ let rebind = AssociationLedgerEvent(payload: .accept(.init(pair: destination, spellingKeys: ["alice"],+ rebind: .init(operation: .entryMerge(workID: work, fromEntryID: entry, toEntryID: destinationEntry), predecessorIDs: [original.id]))))+ let parent = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [original.id], text: "Exact text", originalContext: "Café")+ let child = AssociationNoteValue(pair: destination, attachmentAcceptanceIDs: [rebind.id], parentHeadIDs: [parent.id],+ operation: .rebind, text: parent.text, originalContext: "Cafe\u{301}", rebindAcceptanceID: rebind.id)+ let ledger = AssociationLedgerInventory(events: [rebind, original])+ let notes = AssociationNoteFold(notes: [child, parent], ledger: ledger)+ #expect(ledger.acceptance(rebind.id) != nil)+ #expect(notes.invalidIDs.contains(child.id))+ #expect(notes.heads(for: pair) == [parent])+ #expect(notes.heads(for: destination).isEmpty)+ #expect(notes.rawNotes.count == 2)+ }+ @Test func exactTimestampBitsDistinguishTypedAndRawAuthoredVariants() throws {+ let plus = Date(timeIntervalSinceReferenceDate: 0.0), minus = Date(timeIntervalSinceReferenceDate: -0.0)+ #expect(plus.timeIntervalSinceReferenceDate.bitPattern != minus.timeIntervalSinceReferenceDate.bitPattern)+ let pair = AssociationPair(workID: UUID(), entryID: UUID(), kind: .character, recordID: UUID())+ let core = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: ["alice"])))+ let ledger = AssociationLedgerInventory(events: [core])+ let first = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [core.id], text: "Exact", authoredAt: plus)+ var second = first; second.authoredAt = minus+ #expect(first != second)+ let rawFirst = AssociationRawNote(try PairNoteVersion(note: first))+ let rawSecond = AssociationRawNote(try PairNoteVersion(note: second))+ #expect(rawFirst != rawSecond)+ #expect(rawFirst.variantIdentity != rawSecond.variantIdentity)+ #expect(AssociationNoteFold(notes: [first], ledger: ledger).heads(for: pair) == [first])+ #expect(AssociationNoteFold(notes: [second], ledger: ledger).heads(for: pair) == [second])+ let fold = AssociationNoteFold(notes: [first, second], ledger: ledger)+ #expect(fold.invalidIDs.contains(first.id))+ #expect(fold.rawNotes.count == 2)+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationIntegrationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationIntegrationTests.swiftnew file mode 100644index 00000000..491c8009--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationIntegrationTests.swift@@ -0,0 +1,462 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Chapter association repository integration", .serialized)+struct AssociationIntegrationTests {+ private struct IDs: Sendable {+ var work = UUID(), entry = UUID(), character = UUID(), place = UUID()+ }+ private func fixture(note: String = "Alice visited Harbor.", aliases: [String] = [],+ saveStrategy: any RepositorySaveStrategy = ModelContextSaveStrategy()) async throws -> (M5Fixture, IDs) {+ let fixture = try await M5Fixture(saveStrategy: saveStrategy), ids = IDs()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding synthetic association chapter") { context in+ let work = Work(id: ids.work, displayTitle: "Synthetic association Work", timestamp: M5Fixture.epoch)+ let entry = Entry(id: ids.entry, captureTitle: "Chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: note)+ try entry.authorTarget(.init(kind: .chapter))+ let character = CharacterRecord(id: ids.character, name: "Alice", nameKey: "alice", aliases: aliases, work: nil)+ let place = Place(id: ids.place, name: "Harbor", nameKey: "harbor", workID: ids.work)+ context.insert(work); context.insert(entry); context.insert(character); context.insert(place)+ entry.work = work; LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch); character.work = work; try context.save()+ }+ return (fixture, ids)+ }+ private func decision(_ ids: IDs, note: String = "Alice visited Harbor.", kind: RecordKind = .character,+ spelling: String = "Alice", action: DecisionAction = .accept,+ observedRejections: [UUID] = []) -> DecisionRequest {+ .init(workID: ids.work, kind: kind, action: action, displayedKeys: [RecordNameKey.normalize(spelling)],+ displayedTargetID: kind == .character ? ids.character : ids.place, proposedName: spelling,+ mentions: [.init(entryID: ids.entry, noteFingerprint: CharacterCoverageFingerprint.of(note),+ spellingKeys: [RecordNameKey.normalize(spelling)], observedRejectionIDs: observedRejections)])+ }+ private func active(_ repository: LibraryRepository, _ entryID: UUID) async throws -> [ChapterAssociationSnapshot] {+ try await repository.chapterAssociations(entryID: entryID).filter { !$0.activeAcceptanceIDs.isEmpty }+ }+ @Test func nameOnlyCharacterAndPlaceAreSavedWithoutFactsOnURLFreeChapter() async throws {+ let (fixture, ids) = try await fixture()+ #expect(try await fixture.repository.commitDecision(decision(ids)) == .committed(recordID: ids.character))+ #expect(try await fixture.repository.commitDecision(decision(ids, kind: .place, spelling: "Harbor")) == .committed(recordID: ids.place))+ let links = try await active(fixture.repository, ids.entry)+ #expect(Set(links.map(\.pair.kind)) == [.character, .place])+ #expect(Set(links.map(\.pair.entryID)) == [ids.entry])+ let facts = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking synthetic facts") { context in+ (try context.fetch(FetchDescriptor<CharacterRecord>()).flatMap(\.facts),+ try context.fetch(FetchDescriptor<Place>()).flatMap(\.facts))+ }+ #expect(facts.0.isEmpty && facts.1.isEmpty)+ withExtendedLifetime(fixture) {}+ }+ @Test func distinctChapterIDsSharingURLKeepIndependentLinks() async throws {+ let (fixture, ids) = try await fixture()+ let second = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding same-URL chapters") { context in+ let entry = try #require(try context.fetch(FetchDescriptor<Entry>()).first)+ let site = Site(hostname: "synthetic.test"); context.insert(site)+ entry.rawURLString = "https://synthetic.test/shared"; entry.hostname = site.hostname; entry.site = site+ let another = Entry(id: second, captureTitle: "Another chapter", captureTitleSource: .manual,+ rawURLString: entry.rawURLString, hostname: site.hostname, entryIdentityKey: "", timestamp: M5Fixture.epoch, note: entry.note)+ try another.authorTarget(.init(kind: .chapter)); context.insert(another); another.work = entry.work; another.site = site+ try context.save()+ }+ _ = try await fixture.repository.commitDecision(decision(ids))+ var other = ids; other.entry = second+ _ = try await fixture.repository.commitDecision(decision(other))+ #expect(try await active(fixture.repository, ids.entry).map(\.pair.entryID) == [ids.entry])+ #expect(try await active(fixture.repository, second).map(\.pair.entryID) == [second])+ withExtendedLifetime(fixture) {}+ }+ @Test func allFactsUntickedStillSavesDisplayedMention() async throws {+ let (fixture, ids) = try await fixture()+ var request = decision(ids)+ request.untickedFacts = [.init(nameKey: "alice", source: .entry(ids.entry), quote: "Alice visited Harbor.")]+ #expect(try await fixture.repository.commitDecision(request) == .committed(recordID: ids.character))+ #expect(try await active(fixture.repository, ids.entry).count == 1)+ withExtendedLifetime(fixture) {}+ }+ @Test func removalAndReturnRequireNewAcceptanceAndPreserveFacts() async throws {+ let (fixture, ids) = try await fixture()+ var request = decision(ids)+ request.facts = [.init(statement: "Visited", quote: "Alice visited Harbor.", nameKey: "alice", source: .entry(ids.entry))]+ _ = try await fixture.repository.commitDecision(request)+ let old = try #require(try await active(fixture.repository, ids.entry).first)+ var entry = try await fixture.repository.entry(id: ids.entry)+ #expect(try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Only Harbor.", rating: nil) == .committed)+ #expect(try await active(fixture.repository, ids.entry).allSatisfy { $0.pair.kind == .place })+ entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Alice returned.", rating: nil)+ let saved = try #require(try await active(fixture.repository, ids.entry).first { $0.pair.recordID == ids.character })+ #expect(old.activeAcceptanceIDs.isDisjoint(with: saved.activeAcceptanceIDs))+ _ = try await fixture.repository.commitDecision(decision(ids, note: "Alice returned."))+ let newer = try #require(try await active(fixture.repository, ids.entry).first)+ #expect(old.activeAcceptanceIDs.isDisjoint(with: newer.activeAcceptanceIDs))+ let facts = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking preserved cited fact") { context in+ try context.fetch(FetchDescriptor<CharacterRecord>()).flatMap(\.facts)+ }+ #expect(facts == request.facts)+ withExtendedLifetime(fixture) {}+ }+ @Test func remainingAliasPreservesRootAndRefreshesExactEvidence() async throws {+ let note = "Alice and Nova arrived."+ let (fixture, ids) = try await fixture(note: note, aliases: ["Nova"])+ _ = try await fixture.repository.commitDecision(decision(ids, note: note))+ let before = try #require(try await active(fixture.repository, ids.entry).first)+ let entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "NOVA remains.", rating: nil)+ let after = try #require(try await active(fixture.repository, ids.entry).first)+ #expect(after.activeAcceptanceIDs == before.activeAcceptanceIDs)+ #expect(after.evidence.contains { ExactScalarString($0.spelling) == ExactScalarString("NOVA") })+ #expect(!after.evidence.contains { $0.spelling == "Alice" || $0.spelling == "Nova" })+ withExtendedLifetime(fixture) {}+ }+ @Test func staleMissingEntryAcceptRefusesBeforeFactsOrAliases() async throws {+ let (fixture, ids) = try await fixture()+ var request = decision(ids)+ request.proposedAliases = ["Unwritten Alias"]+ request.facts = [.init(statement: "Visited", quote: "Alice visited Harbor.", nameKey: "alice", source: .entry(ids.entry))]+ let entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.deleteEntry(id: ids.entry, basis: .init(entry: entry), disclosedVariants: nil)+ #expect(try await fixture.repository.commitDecision(request) == .refused(.staleSource(.entry(ids.entry))))+ let saved = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking stale acceptance atomicity") { context in+ let row = try #require(try context.fetch(FetchDescriptor<CharacterRecord>()).first)+ return (row.aliases, row.facts, try context.fetchCount(FetchDescriptor<AssociationEvent>()))+ }+ #expect(saved.0.isEmpty && saved.1.isEmpty)+ #expect(try await active(fixture.repository, ids.entry).isEmpty)+ withExtendedLifetime(fixture) {}+ }+ @Test func nonChapterEntryKeepsFactExtractionButRefusesMention() async throws {+ let (fixture, ids) = try await fixture()+ let contract = try await fixture.repository.projectEntryCorrection(entryID: ids.entry)+ _ = try await fixture.repository.commitEntryCorrection(contract, target: .init(kind: .note))+ #expect(try await fixture.repository.commitDecision(decision(ids)) == .refused(.staleSource(.entry(ids.entry))))+ var factsOnly = decision(ids); factsOnly.mentions = []+ factsOnly.facts = [.init(statement: "Visited", quote: "Alice visited Harbor.", nameKey: "alice", source: .entry(ids.entry))]+ #expect(try await fixture.repository.commitDecision(factsOnly) == .committed(recordID: ids.character))+ #expect(try await active(fixture.repository, ids.entry).isEmpty)+ withExtendedLifetime(fixture) {}+ }+ @Test func harmlessRenameRetainingStableTargetDoesNotRefusePendingAcceptance() async throws {+ let (fixture, ids) = try await fixture()+ let pending = decision(ids)+ let basis = RecordEditBasis(kind: .character, recordID: ids.character, name: "Alice", note: "", aliases: [], facts: [])+ _ = try await fixture.repository.commitRecordEdits(workID: ids.work, operations: [.update(basis: basis, draft: .init(kind: .character, name: "Alice Renamed"))])+ #expect(try await fixture.repository.commitDecision(pending) == .committed(recordID: ids.character))+ #expect(try await active(fixture.repository, ids.entry).count == 1)+ withExtendedLifetime(fixture) {}+ }+ @Test func rejectionStaysSpellingScopedAcrossUnrelatedSourceEdit() async throws {+ let note = "Alice and Ally arrived."+ let (fixture, ids) = try await fixture(note: note, aliases: ["Ally"])+ _ = try await fixture.repository.commitDecision(decision(ids, note: note, action: .skip))+ let entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: note + " Again.", rating: nil)+ let candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ #expect(candidate.mentionIndex.isSuppressed(entryID: ids.entry, kind: .character, recordID: ids.character, spellingKey: "alice"))+ #expect(!candidate.mentionIndex.isSuppressed(entryID: ids.entry, kind: .character, recordID: ids.character, spellingKey: "ally"))+ _ = try await fixture.repository.commitDecision(decision(ids, note: note + " Again.", spelling: "Ally"))+ #expect(try await active(fixture.repository, ids.entry).count == 1)+ withExtendedLifetime(fixture) {}+ }+ @Test func oldCoverageAndNewAliasUseCompositeMentionEligibility() async throws {+ let (fixture, ids) = try await fixture()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding legacy fact coverage") { context in+ for entry in try context.fetch(FetchDescriptor<Entry>()) {+ entry.characterExtractionFingerprint = CharacterCoverageFingerprint.of(entry.note)+ }+ try context.save()+ }+ var candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ var source = try #require(candidate.sources.first)+ #expect(!source.isCovered)+ _ = try await fixture.repository.advanceCoverage(workID: ids.work, sources: [source.completedSource])+ candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ source = try #require(candidate.sources.first)+ #expect(source.isCovered)+ let basis = RecordEditBasis(kind: .character, recordID: ids.character, name: "Alice", note: "", aliases: [], facts: [])+ _ = try await fixture.repository.commitRecordEdits(workID: ids.work, operations: [.update(basis: basis,+ draft: .init(kind: .character, name: "Alice", aliases: ["Ally"]))])+ let updated = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ #expect(try #require(updated.sources.first).isCovered == false)+ withExtendedLifetime(fixture) {}+ }+ @Test func removingFinalAliasRetiresLinkWithoutModelAndKeepsRecord() async throws {+ let (fixture, ids) = try await fixture(note: "Ally arrived.", aliases: ["Ally"])+ _ = try await fixture.repository.commitDecision(decision(ids, note: "Ally arrived.", spelling: "Ally"))+ let basis = RecordEditBasis(kind: .character, recordID: ids.character, name: "Alice", note: "", aliases: ["Ally"], facts: [])+ _ = try await fixture.repository.commitRecordEdits(workID: ids.work, operations: [.update(basis: basis, draft: .init(kind: .character, name: "Alice"))])+ #expect(try await active(fixture.repository, ids.entry).isEmpty)+ let count = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking preserved record") { context in+ try context.fetchCount(FetchDescriptor<CharacterRecord>())+ }+ #expect(count == 1)+ withExtendedLifetime(fixture) {}+ }+ @Test func actualSourceChangeWritesBarrierEvenWithNoKnownLinks() async throws {+ let (fixture, ids) = try await fixture(note: "Nobody known is here.")+ var entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: entry.note, rating: .up)+ let before = try await eventCount(fixture.repository)+ entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Still nobody known.", rating: .up)+ #expect(try await eventCount(fixture.repository) == before + 1)+ withExtendedLifetime(fixture) {}+ }+ private func eventCount(_ repository: LibraryRepository) async throws -> Int {+ try await repository.withLockedContext(mode: .shared, operation: "counting synthetic ledger rows") { context in+ try context.fetchCount(FetchDescriptor<AssociationEvent>())+ }+ }+ @Test func explicitOrphanDeletionHoldsKnownOldOwnerProofAgainstReplay() async throws {+ let (fixture, ids) = try await fixture()+ _ = try await fixture.repository.commitDecision(decision(ids))+ let raw = try await fixture.repository.withLockedContext(mode: .exclusive, operation: "simulating orphan arrival") { context in+ let raw = AssociationRawEvent(try #require(try context.fetch(FetchDescriptor<AssociationEvent>()).first))+ for entry in try context.fetch(FetchDescriptor<Entry>()) { entry.work = nil }+ try context.save(); return raw+ }+ let orphan = try await fixture.repository.entry(id: ids.entry)+ #expect(orphan.workID == nil)+ _ = try await fixture.repository.deleteEntry(id: ids.entry, basis: .init(entry: orphan), disclosedVariants: nil)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "replaying former source and proof") { context in+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first)+ let row = Entry(id: ids.entry, captureTitle: "Chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Alice visited Harbor.")+ try row.authorTarget(.init(kind: .chapter)); context.insert(row); row.work = work+ context.insert(AssociationEvent(raw: raw)); try context.save()+ }+ #expect(try await active(fixture.repository, ids.entry).isEmpty)+ withExtendedLifetime(fixture) {}+ }+ @Test func globallyConflictingNewSourceHasNoFeatureMentionEligibility() async throws {+ let (fixture, ids) = try await fixture()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding conflicting source owner") { context in+ let other = Work(displayTitle: "Other synthetic Work", timestamp: M5Fixture.epoch)+ let twin = Entry(id: ids.entry, captureTitle: "Chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Alice visited Harbor.")+ try twin.authorTarget(.init(kind: .chapter)); context.insert(other); context.insert(twin); twin.work = other+ try context.save()+ }+ let candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ #expect(!candidate.mentionIndex.eligibleEntries.contains(ids.entry))+ #expect(candidate.sources.contains { $0.ref == .entry(ids.entry) })+ #expect(try await fixture.repository.commitDecision(decision(ids)) == .refused(.staleSource(.entry(ids.entry))))+ withExtendedLifetime(fixture) {}+ }+ @Test func globallyConflictingNewTargetHasNoFeatureMentionEligibility() async throws {+ let (fixture, ids) = try await fixture()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding conflicting target owner") { context in+ let other = Work(displayTitle: "Other synthetic Work", timestamp: M5Fixture.epoch)+ let twin = CharacterRecord(id: ids.character, name: "Alice", nameKey: "alice", work: nil)+ context.insert(other); context.insert(twin); twin.work = other; try context.save()+ }+ let candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ #expect(!candidate.mentionIndex.canLink(kind: .character, recordID: ids.character))+ #expect(candidate.records(of: .character).contains { $0.id == ids.character })+ #expect(try await fixture.repository.commitDecision(decision(ids)) == .refused(.torn(recordID: ids.character)))+ withExtendedLifetime(fixture) {}+ }+ @Test func articleBearingCurrentNameKeepsFullExactEvidence() async throws {+ let note = "The Queen visited Harbor."+ let (fixture, ids) = try await fixture(note: note)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "naming article-bearing character") { context in+ let row = try #require(try context.fetch(FetchDescriptor<CharacterRecord>()).first)+ row.name = "The Queen"; row.nameKey = "queen"; try context.save()+ }+ _ = try await fixture.repository.commitDecision(decision(ids, note: note, spelling: "The Queen"))+ let link = try #require(try await active(fixture.repository, ids.entry).first)+ #expect(link.evidence.contains { ExactScalarString($0.spelling) == ExactScalarString("The Queen") })+ withExtendedLifetime(fixture) {}+ }+ @Test func failedAcceptanceSaveKeepsFactsAliasesLinksAndCoverageAtomic() async throws {+ let strategy = InstrumentedSaveStrategy()+ let (fixture, ids) = try await fixture(saveStrategy: strategy)+ let candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ var request = decision(ids)+ request.proposedAliases = ["Ally"]+ request.facts = [.init(statement: "Visited", quote: "Alice visited Harbor.", nameKey: "alice", source: .entry(ids.entry))]+ request.completedSources = candidate.sources.map(\.completedSource)+ strategy.resetCounts(); strategy.shouldFail = true+ do { _ = try await fixture.repository.commitDecision(request); Issue.record("injected save must fail") }+ catch { }+ strategy.shouldFail = false+ #expect(strategy.attemptCount == 1 && strategy.successCount == 0)+ let saved = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking failed acceptance isolation") { context in+ let character = try #require(try context.fetch(FetchDescriptor<CharacterRecord>()).first)+ let entry = try #require(try context.fetch(FetchDescriptor<Entry>()).first)+ return (character.aliases, character.facts, entry.characterExtractionFingerprint,+ try context.fetchCount(FetchDescriptor<AssociationEvent>()))+ }+ #expect(saved.0.isEmpty && saved.1.isEmpty && saved.2 == nil && saved.3 == 0)+ withExtendedLifetime(fixture) {}+ }+ @Test func combineThenConversionWithActiveDestinationDeduplicatesFinalPair() async throws {+ let note = "Alice and Ally arrived."+ let (fixture, ids) = try await fixture(note: note)+ let targetID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding active combine target") { context in+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first)+ let target = CharacterRecord(id: targetID, name: "Ally", nameKey: "ally", work: nil)+ context.insert(target); target.work = work; try context.save()+ }+ _ = try await fixture.repository.commitDecision(decision(ids, note: note))+ var targetRequest = decision(ids, note: note, spelling: "Ally"); targetRequest.displayedTargetID = targetID+ _ = try await fixture.repository.commitDecision(targetRequest)+ #expect(try await active(fixture.repository, ids.entry).count == 2)+ let source = RecordEditBasis(kind: .character, recordID: ids.character, name: "Alice", note: "", aliases: [], facts: [])+ let target = RecordEditBasis(kind: .character, recordID: targetID, name: "Ally", note: "", aliases: [], facts: [])+ let result = try await fixture.repository.commitRecordEdits(workID: ids.work, operations: [+ .combine(source: source, target: target),+ .convert(basis: target, to: .place, draft: .init(kind: .place, name: "Ally", aliases: ["Alice"]))])+ guard case .committed(let written) = result else { Issue.record("verified identity chain must commit"); return }+ let finalID = try #require(written.last)+ let links = try await active(fixture.repository, ids.entry)+ #expect(links.count == 1)+ #expect(links.first?.pair == .init(workID: ids.work, entryID: ids.entry, kind: .place, recordID: finalID))+ #expect(links.first?.activeAcceptanceIDs.count == 2)+ withExtendedLifetime(fixture) {}+ }++ @Test func resolvingGlobalTargetConflictRearmsCoveredUnchangedSource() async throws {+ let (fixture, ids) = try await fixture()+ let otherID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding temporarily conflicting target") { context in+ let other = Work(id: otherID, displayTitle: "Other synthetic Work", timestamp: M5Fixture.epoch)+ let twin = CharacterRecord(id: ids.character, name: "Alice", nameKey: "alice", work: nil)+ context.insert(other); context.insert(twin); twin.work = other; try context.save()+ }+ var candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ let initial = try #require(candidate.sources.first)+ #expect(!candidate.mentionIndex.canLink(kind: .character, recordID: ids.character))+ _ = try await fixture.repository.advanceCoverage(workID: ids.work, sources: [initial.completedSource])+ candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ #expect(try #require(candidate.sources.first).isCovered)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "simulating conflict resolution by sync") { context in+ for row in try context.fetch(FetchDescriptor<CharacterRecord>()) where row.work?.id == otherID { context.delete(row) }+ try context.save()+ }+ candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ let resolved = try #require(candidate.sources.first)+ #expect(candidate.mentionIndex.canLink(kind: .character, recordID: ids.character))+ #expect(resolved.fingerprint == initial.fingerprint)+ #expect(resolved.mentionEligibilityDigest != initial.mentionEligibilityDigest)+ #expect(!resolved.isCovered)+ withExtendedLifetime(fixture) {}+ }++ private final class FailFirstSave: RepositorySaveStrategy, @unchecked Sendable {+ private let lock = NSLock()+ private var attempts = 0+ func save(_ context: ModelContext) throws {+ let first = lock.withLock { attempts += 1; return attempts == 1 }+ if first { throw CocoaError(.fileWriteUnknown) }+ try context.save()+ }+ var count: Int { lock.withLock { attempts } }+ }+ private func deleteDuplicateChapter(fixture: M5Fixture, ids: IDs,+ strategy: any RepositorySaveStrategy) async throws -> UUID {+ let survivorID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "deleting verified synthetic duplicate chapter") { context in+ let old = try #require(try context.fetch(FetchDescriptor<Entry>()).first { $0.id == ids.entry })+ let survivor = Entry(id: survivorID, captureTitle: old.captureTitle, captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: old.note)+ try survivor.authorTarget(.init(kind: .chapter)); context.insert(survivor); survivor.work = old.work+ try context.save()+ let rows = [ids.entry: [old], survivorID: [survivor]]+ let members = [ids.entry, survivorID]+ let plan = DuplicateDeletionPlan(key: .init(recordType: .entry, memberIDs: members),+ survivorID: survivorID, loserIDs: [ids.entry],+ fingerprint: DuplicateReconciler.entryFingerprint(members, rowsByID: rows, canonicalWorkIDs: [:]))+ let committed = try DuplicateReconciler.commitDeletions([plan], canonicalWorkIDs: [:],+ context: context, saveStrategy: strategy)+ #expect(committed == [plan.key])+ }+ return survivorID+ }+ @Test func duplicateDeletionRebindsOnlyVerifiedActiveChapterRoots() async throws {+ let (fixture, ids) = try await fixture()+ _ = try await fixture.repository.commitDecision(decision(ids))+ let old = try #require(try await active(fixture.repository, ids.entry).first)+ let survivor = try await deleteDuplicateChapter(fixture: fixture, ids: ids, strategy: ModelContextSaveStrategy())+ #expect(try await active(fixture.repository, ids.entry).isEmpty)+ let current = try #require(try await active(fixture.repository, survivor).first)+ #expect(current.pair.entryID == survivor && current.pair.recordID == ids.character)+ #expect(current.activeAcceptanceIDs.isDisjoint(with: old.activeAcceptanceIDs))+ withExtendedLifetime(fixture) {}+ }+ @Test func duplicateDeletionFailedChunkRecapturesAndReplaysAssociationBasis() async throws {+ let (fixture, ids) = try await fixture()+ _ = try await fixture.repository.commitDecision(decision(ids))+ let old = try #require(try await active(fixture.repository, ids.entry).first)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding exact head before failed duplicate chunk") { context in+ context.insert(try PairNoteVersion(note: .init(pair: old.pair,+ attachmentAcceptanceIDs: Array(old.activeAcceptanceIDs), text: "Cafe\u{301} survives replay",+ originalContext: "Original Café chapter")))+ try context.save()+ }+ let strategy = FailFirstSave()+ let survivor = try await deleteDuplicateChapter(fixture: fixture, ids: ids, strategy: strategy)+ #expect(strategy.count == 2)+ #expect(try await active(fixture.repository, ids.entry).isEmpty)+ let current = try #require(try await active(fixture.repository, survivor).first)+ #expect(current.activeAcceptanceIDs.count == 1)+ #expect(current.noteHeads.count == 1)+ #expect(current.noteHeads.first.map { ExactScalarString($0.text) } == ExactScalarString("Cafe\u{301} survives replay"))+ let raw = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking one committed duplicate rebind") { context in+ try context.fetch(FetchDescriptor<AssociationEvent>()).compactMap { $0.ledgerValue }.filter {+ if case .accept(let core) = $0.payload { return core.rebind != nil }; return false+ }+ }+ #expect(raw.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test func manualChapterUpdatePreservesObservedRootAndRefreshesEvidence() async throws {+ let (fixture, ids) = try await fixture()+ _ = try await fixture.repository.commitDecision(decision(ids))+ let before = try #require(try await active(fixture.repository, ids.entry).first)+ let projection = try await fixture.repository.projectManualEntry(workID: ids.work)+ guard case .committed = try await fixture.repository.commitManualEntry(projection: projection,+ draft: .init(target: .init(kind: .chapter), note: "ALICE remains.", existingEntryID: ids.entry)) else {+ Issue.record("Existing manual chapter update must commit"); return+ }+ let after = try #require(try await active(fixture.repository, ids.entry).first)+ #expect(after.activeAcceptanceIDs == before.activeAcceptanceIDs)+ #expect(after.evidence.map { ExactScalarString($0.spelling) } == [ExactScalarString("ALICE")])+ withExtendedLifetime(fixture) {}+ }+ @Test func chapterCaptureExistingSourceUpdatesInItsOneSave() async throws {+ let (fixture, ids) = try await fixture()+ _ = try await fixture.repository.commitDecision(decision(ids))+ let before = try #require(try await active(fixture.repository, ids.entry).first)+ let url = "https://synthetic.test/chapter"+ let projection = try await fixture.repository.projectChapterCapture(rawURL: url, captureTitle: "Chapter", workID: ids.work)+ guard case .committed = try await fixture.repository.commitChapterCapture(.init(projection: projection,+ capture: .init(captureTitle: "Chapter", captureTitleSource: .manual, rawURLString: url, note: "ALICE remains."),+ intent: .existing(ids.entry, contentChoice: .source))) else {+ Issue.record("Explicit existing chapter capture must commit"); return+ }+ let after = try #require(try await active(fixture.repository, ids.entry).first)+ #expect(after.activeAcceptanceIDs == before.activeAcceptanceIDs)+ #expect(after.evidence.map { ExactScalarString($0.spelling) } == [ExactScalarString("ALICE")])+ withExtendedLifetime(fixture) {}+ }+ @Test func correctionToNonChapterRetiresAssociationDespiteSupportedText() async throws {+ let (fixture, ids) = try await fixture()+ _ = try await fixture.repository.commitDecision(decision(ids))+ let before = try #require(try await active(fixture.repository, ids.entry).first)+ let correction = try await fixture.repository.projectEntryCorrection(entryID: ids.entry)+ #expect(try await fixture.repository.commitEntryCorrection(correction,+ target: .init(kind: .note)) == .committed(entryID: ids.entry))+ #expect(try await active(fixture.repository, ids.entry).isEmpty)+ let next = try await fixture.repository.projectEntryCorrection(entryID: ids.entry)+ _ = try await fixture.repository.commitEntryCorrection(next, target: .init(kind: .chapter))+ let returned = try #require(try await active(fixture.repository, ids.entry).first { $0.pair.recordID == ids.character })+ #expect(before.activeAcceptanceIDs.isDisjoint(with: returned.activeAcceptanceIDs))+ #expect(!before.activeAcceptanceIDs.isEmpty)+ withExtendedLifetime(fixture) {}+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationJourneyFixtureTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationJourneyFixtureTests.swiftnew file mode 100644index 00000000..c978d045--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationJourneyFixtureTests.swift@@ -0,0 +1,89 @@+#if DEBUG+import Foundation+import Testing+@testable import AsterismCore++@Suite("Isolated chapter link journey fixture", .serialized)+struct AssociationJourneyFixtureTests {+ @Test func seedsBothKindsDetachedRecoveryAndCopyOnlyRawTextWithoutReseeding() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.seedAssociationNotesFixture()+ let first = try await fixture.repository.chapterAssociations(entryID: LibraryRepository.associationFixtureChapterID)+ #expect(Set(first.map { $0.pair.kind }) == [.character, .place])+ #expect(first.allSatisfy { !$0.activeAcceptanceIDs.isEmpty })+ #expect(first.first { $0.pair.kind == .place }?.noteHeads.count == 2)+ let detached = try await fixture.repository.detachedAssociationNotes()+ #expect(detached.contains { $0.canRecover && $0.raw.text == "Earlier chapter link note" })+ #expect(detached.contains { !$0.canRecover && $0.raw.text == "Cafe\u{301} raw text remains copyable" })+ #expect(detached.contains { !$0.canRecover && $0.raw.text == "Missing endpoint note" })+ let character = try #require(first.first { $0.pair.kind == .character })+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: character.pair))+ #expect(try await fixture.repository.saveAssociationNote(basis: basis, text: "Cafe\u{301} reader edit") == .committed)+ let before = try await fixture.repository.backupV20Snapshot()+ try await fixture.repository.seedAssociationNotesFixture()+ let after = try await fixture.repository.backupV20Snapshot()+ #expect(after == before, "A completed fixture launch preserves every saved edit and raw variant")+ let heads = try #require(try await fixture.repository.associationNoteBasis(pair: character.pair)).heads+ #expect(heads.map { Array($0.text.utf8) } == [Array("Cafe\u{301} reader edit".utf8)])+ withExtendedLifetime(fixture) {}+ }++ @Test("Unicode readback refuses fresh or unrelated roots without seeding", arguments: [false, true])+ func unicodeReadbackRequiresAlreadyCompletedFixture(unrelated: Bool) async throws {+ let fixture = try await M5Fixture()+ if unrelated { _ = try await fixture.repository.createWork(.init(displayTitle: "Unrelated synthetic Work", hostname: "")) }+ let before = try await fixture.repository.backupV20Snapshot()+ await #expect(throws: (any Error).self) {+ try await fixture.repository.seedAssociationNotesFixture(verifyUnicodeAppend: true)+ }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }++ @Test func seededUnicodeAppendReadbackAndCurrentArchivePreserveExactBytes() async throws {+ let fixture = try await M5Fixture()+ try await fixture.repository.seedAssociationNotesFixture()+ let pair = try #require(try await fixture.repository.chapterAssociations(entryID: LibraryRepository.associationFixtureRecoveryChapterID)+ .first { $0.pair.kind == .place }?.pair)+ let original = "Cafe\u{301} seeded link note"+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ #expect(basis.heads.count == 1 && Data(basis.heads[0].text.utf8) == Data(original.utf8))+ let before = try await fixture.repository.backupV20Snapshot()+ let chapter = try #require(before.library.entries.first { $0.id == pair.entryID })+ #expect(chapter.chapterTitle == nil && chapter.citations.chapterTitle.kind == .none,+ "Raw legacy chapter fields remain absent beside the authored target")+ let target = try AuthoredEntryTarget.decode(try #require(chapter.authoredTargetData))+ #expect(target.kind == .chapter && target.title == "Return" && target.designation == "2")+ await #expect(throws: (any Error).self) {+ try await fixture.repository.seedAssociationNotesFixture(verifyUnicodeAppend: true)+ }+ #expect(try await fixture.repository.backupV20Snapshot() == before, "Failed readback writes nothing")+ let expected = original + " ASCII appended"+ #expect(try await fixture.repository.saveAssociationNote(basis: basis, text: expected) == .committed)+ let saved = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ #expect(saved.heads.count == 1 && Data(saved.heads[0].text.utf8) == Data(expected.utf8))+ let payload = try await fixture.repository.backupV20Snapshot()+ let encoded = try BackupV20Codec.encode(payload: payload, metadata: .init(appBuild: "unicode-fixture", exportedAt: M5Fixture.epoch))+ let decoded = try BackupV20Codec.decode(encoded).payload+ let archived = try #require(decoded.pairNoteVersions.first { $0.id == saved.heads[0].id })+ #expect(Data(archived.text.utf8) == Data(expected.utf8))+ let restored = try await M5Fixture()+ _ = try await restored.repository.confirmImport(plan: BackupImporter.plan(from: encoded))+ let restoredBasis = try #require(try await restored.repository.associationNoteBasis(pair: pair))+ #expect(restoredBasis.heads.count == 1 && Data(restoredBasis.heads[0].text.utf8) == Data(expected.utf8))+ try await fixture.repository.seedAssociationNotesFixture(verifyUnicodeAppend: true)+ #expect(try await fixture.repository.backupV20Snapshot() == payload, "Successful readback also writes nothing")+ withExtendedLifetime((fixture, restored)) {}+ }++ @Test func refusesAnUnrelatedNonemptyLibraryWithoutChangingIt() async throws {+ let fixture = try await M5Fixture()+ _ = try await fixture.repository.createWork(.init(displayTitle: "Unrelated synthetic Work", hostname: ""))+ let before = try await fixture.repository.backupV20Snapshot()+ await #expect(throws: (any Error).self) { try await fixture.repository.seedAssociationNotesFixture() }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }+}++#endif
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationLedgerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationLedgerTests.swiftnew file mode 100644index 00000000..39f419d6--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationLedgerTests.swift@@ -0,0 +1,276 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite struct AssociationLedgerTests {+ private let work = UUID(uuidString: "10000000-0000-0000-0000-000000000001")!+ private let entry = UUID(uuidString: "20000000-0000-0000-0000-000000000001")!+ private let record = UUID(uuidString: "30000000-0000-0000-0000-000000000001")!+ private var pair: AssociationPair { .init(workID: work, entryID: entry, kind: .character, recordID: record) }+ private func state(_ pair: AssociationPair, source: String = "S1", target: String = "R1",+ spellings: [String] = ["Alice"]) -> AssociationCurrentPair {+ .init(pair: pair, sourceFingerprint: source, matchingFingerprint: target,+ evidence: spellings.map { .init(key: RecordNameKey.normalize($0), spelling: $0) })+ }+ private func accepted(_ state: AssociationCurrentPair, events: [AssociationLedgerEvent] = [],+ acknowledging: [UUID] = []) -> AssociationLedgerEvent {+ let core = AssociationAcceptance(pair: state.pair, spellingKeys: state.evidence.map(\.key),+ reconsideredRejectionIDs: acknowledging)+ let event = AssociationLedgerEvent(payload: .accept(core))+ let inventory = AssociationLedgerInventory(events: events + [event])+ return event.validated(by: inventory.receipt(for: state))+ }+ @Test func acceptanceNeedsCompleteCurrentReceipt() {+ let current = state(pair)+ let event = accepted(current)+ #expect(AssociationLedgerInventory(events: [event]).activeAcceptanceIDs(for: current) == [event.id])+ #expect(AssociationLedgerInventory(events: [event]).activeAcceptanceIDs(for: state(pair, source: "S2")).isEmpty)+ }+ @Test func unseenAcceptanceCannotBypassRemovalAndReturn() {+ let current = state(pair)+ let event = accepted(current)+ let barriers = [AssociationLedgerEvent(payload: .invalidate(.entry(workID: work, entryID: entry))),+ AssociationLedgerEvent(payload: .invalidate(.entry(workID: work, entryID: entry)))]+ #expect(AssociationLedgerInventory(events: barriers + [event]).activeAcceptanceIDs(for: current).isEmpty)+ }+ @Test func partialWholeReceiptsNeverCompose() {+ let first = accepted(state(pair, source: "S2"))+ let second = first.validated(by: AssociationLedgerInventory(events: [first]).receipt(for: state(pair, target: "R2")))+ #expect(AssociationLedgerInventory(events: [first, second]).activeAcceptanceIDs(for: state(pair, source: "S2", target: "R2")).isEmpty)+ }+ @Test func rejectionIsSpellingScopedAndAcknowledgementDoesNotReviveOldRoot() {+ let a = state(pair)+ let old = accepted(a)+ let rejection = AssociationLedgerEvent(payload: .reject(.init(pair: pair, spellingKeys: ["alice"])))+ let b = accepted(state(pair, spellings: ["Bob"]), events: [old, rejection])+ let newer = accepted(a, events: [old, rejection, b], acknowledging: [rejection.id])+ let inventory = AssociationLedgerInventory(events: [old, rejection, b, newer])+ #expect(inventory.activeAcceptanceIDs(for: a) == [newer.id])+ #expect(inventory.activeAcceptanceIDs(for: state(pair, spellings: ["Bob"])) == [b.id])+ #expect(!inventory.isSuppressed(pair: pair, spellingKey: "alice"))+ }+ @Test func invalidAcknowledgementCannotClearAnotherPair() {+ let rejection = AssociationLedgerEvent(payload: .reject(.init(pair: pair, spellingKeys: ["alice"])))+ let other = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let event = accepted(state(other), events: [rejection], acknowledging: [rejection.id])+ let inventory = AssociationLedgerInventory(events: [rejection, event])+ #expect(inventory.isSuppressed(pair: pair, spellingKey: "alice"))+ #expect(inventory.activeAcceptanceIDs(for: state(other)).isEmpty)+ }+ @Test func conflictingImmutableCopiesQuarantineIdentity() {+ let original = accepted(state(pair))+ let contradiction = AssociationLedgerEvent(id: original.id, payload: .invalidate(.work(work)))+ #expect(AssociationLedgerInventory(events: [original, contradiction]).activeAcceptanceIDs(for: state(pair)).isEmpty)+ }+ @Test func rebindWaitsForCompleteHistoricalParentsAndSurvivesTheirRetirement() {+ let parent = accepted(state(pair))+ let destination = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let rebind = AssociationLedgerEvent(payload: .accept(.init(pair: destination, spellingKeys: ["alice"],+ rebind: .init(operation: .entryMerge(workID: work, fromEntryID: entry, toEntryID: destination.entryID), predecessorIDs: [parent.id]))))+ let inventory = AssociationLedgerInventory(events: [parent, rebind])+ let child = rebind.validated(by: inventory.receipt(for: state(destination)))+ #expect(AssociationLedgerInventory(events: [child]).activeAcceptanceIDs(for: state(destination)).isEmpty)+ let retired = AssociationLedgerEvent(payload: .retire(.init(pair: pair, acceptanceIDs: [parent.id])))+ let complete = AssociationLedgerInventory(events: [parent, child, retired])+ #expect(complete.activeAcceptanceIDs(for: state(destination)) == [child.id])+ #expect(complete.activeAcceptanceIDs(for: state(pair)).isEmpty)+ }+ @Test func opposingRebindDestinationsAreReviewable() {+ let parent = accepted(state(pair))+ func child() -> (AssociationCurrentPair, AssociationLedgerEvent) {+ let p = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let e = AssociationLedgerEvent(payload: .accept(.init(pair: p, spellingKeys: ["alice"],+ rebind: .init(operation: .entryMerge(workID: work, fromEntryID: entry, toEntryID: p.entryID), predecessorIDs: [parent.id]))))+ return (state(p), e.validated(by: AssociationLedgerInventory(events: [parent, e]).receipt(for: state(p))))+ }+ let a = child(), b = child()+ let inventory = AssociationLedgerInventory(events: [parent, a.1, b.1])+ #expect(inventory.activeAcceptanceIDs(for: a.0).isEmpty)+ #expect(inventory.activeAcceptanceIDs(for: b.0).isEmpty)+ #expect(inventory.activeAcceptanceIDs(for: state(pair)).isEmpty)+ }+ @Test func typedRebindRejectsUnrelatedIdentityAxes() {+ let parent = accepted(state(pair))+ let destination = AssociationPair(workID: UUID(), entryID: UUID(), kind: .place, recordID: UUID())+ let child = AssociationLedgerEvent(payload: .accept(.init(pair: destination, spellingKeys: ["alice"],+ rebind: .init(operation: .entryMerge(workID: work,+ fromEntryID: entry, toEntryID: destination.entryID), predecessorIDs: [parent.id]))))+ let inventory = AssociationLedgerInventory(events: [parent, child])+ #expect(inventory.invalidIDs.contains(child.id))+ #expect(inventory.activeAcceptanceIDs(for: state(pair)) == [parent.id])+ }+ @Test func opposingRebindInvalidityPropagatesBeforeAcknowledgements() {+ let parent = accepted(state(pair))+ let destination = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let other = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let rejection = AssociationLedgerEvent(payload: .reject(.init(pair: destination, spellingKeys: ["alice"])))+ func child(_ target: AssociationPair, acknowledgements: [UUID] = []) -> AssociationLedgerEvent {+ .init(payload: .accept(.init(pair: target, spellingKeys: ["alice"], reconsideredRejectionIDs: acknowledgements,+ rebind: .init(operation: .entryMerge(workID: work,+ fromEntryID: entry, toEntryID: target.entryID), predecessorIDs: [parent.id]))))+ }+ let a = child(destination, acknowledgements: [rejection.id]), b = child(other)+ let descendantPair = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let descendant = AssociationLedgerEvent(payload: .accept(.init(pair: descendantPair, spellingKeys: ["alice"],+ rebind: .init(operation: .entryMerge(workID: work,+ fromEntryID: destination.entryID, toEntryID: descendantPair.entryID), predecessorIDs: [a.id]))))+ let inventory = AssociationLedgerInventory(events: [descendant, parent, rejection, a, b])+ #expect(inventory.invalidIDs.isSuperset(of: [a.id, b.id, descendant.id]))+ #expect(inventory.isSuppressed(pair: destination, spellingKey: "alice"))+ }+ @Test func conflictingSiblingCannotUndoKnownBatchRetirement() {+ let a = accepted(state(pair)), b = accepted(state(pair))+ let retirement = AssociationLedgerEvent(payload: .retire(.init(pair: pair, acceptanceIDs: [a.id, b.id])))+ let contradiction = AssociationLedgerEvent(id: b.id, payload: .invalidate(.work(work)))+ for events in [[a, b, retirement, contradiction], [contradiction, retirement, a, b], [a, retirement]] {+ let inventory = AssociationLedgerInventory(events: events)+ #expect(inventory.activeAcceptanceIDs(for: state(pair)).isEmpty)+ }+ }+ @Test func acknowledgingOneSpellingDoesNotClearOtherSpellingInSameRejection() {+ let rejection = AssociationLedgerEvent(payload: .reject(.init(pair: pair, spellingKeys: ["alice", "bob"])))+ let a = accepted(state(pair), events: [rejection], acknowledging: [rejection.id])+ let inventory = AssociationLedgerInventory(events: [rejection, a])+ #expect(!inventory.isSuppressed(pair: pair, spellingKey: "alice"))+ #expect(inventory.isSuppressed(pair: pair, spellingKey: "bob"))+ #expect(inventory.activeAcceptanceIDs(for: state(pair)) == [a.id])+ }+ @Test func opposingTypedMappingsKeepParentAndDescendantsInactive() {+ let parent = accepted(state(pair))+ let aPair = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let bPair = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ func child(_ destination: AssociationPair) -> AssociationLedgerEvent {+ .init(payload: .accept(.init(pair: destination, spellingKeys: ["alice"],+ rebind: .init(operation: .entryMerge(workID: work,+ fromEntryID: entry, toEntryID: destination.entryID), predecessorIDs: [parent.id]))))+ }+ let a = child(aPair), b = child(bPair)+ let finalPair = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let descendant = AssociationLedgerEvent(payload: .accept(.init(pair: finalPair, spellingKeys: ["alice"],+ rebind: .init(operation: .entryMerge(workID: work,+ fromEntryID: aPair.entryID, toEntryID: finalPair.entryID), predecessorIDs: [a.id]))))+ let inventory = AssociationLedgerInventory(events: [parent, a, b, descendant])+ #expect(inventory.invalidIDs.isSuperset(of: [a.id, b.id, descendant.id]))+ #expect(inventory.activeAcceptanceIDs(for: state(pair)).isEmpty)+ }+ @Test func historicalClearDoesNotResurrectWhenMembershipRetires() {+ let root = accepted(state(pair))+ let text = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [root.id], text: " exact\ntext ")+ let clear = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [root.id], parentHeadIDs: [text.id], operation: .clear)+ let retirement = AssociationLedgerEvent(payload: .retire(.init(pair: pair, acceptanceIDs: [root.id])))+ let inventory = AssociationLedgerInventory(events: [root, retirement])+ #expect(inventory.activeAcceptanceIDs(for: state(pair)).isEmpty)+ let notes = AssociationNoteFold(notes: [clear, text], ledger: inventory)+ #expect(notes.heads(for: pair).map(\.id) == [clear.id])+ #expect(notes.textHeads(for: pair, activeAcceptanceIDs: []).isEmpty)+ #expect(notes.rawNotes.count == 2)+ }+ @Test func newAcceptanceDoesNotAttachOldNote() {+ let old = accepted(state(pair)), newer = accepted(state(pair))+ let text = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [old.id], text: "Preserve me")+ let fold = AssociationNoteFold(notes: [text], ledger: .init(events: [old, newer]))+ #expect(fold.textHeads(for: pair, activeAcceptanceIDs: [newer.id]).isEmpty)+ #expect(fold.detachedTextHeads(activeAcceptanceIDs: [newer.id]).map(\.text) == ["Preserve me"])+ }+ @Test func missingParentConsumesNothingAndMalformedRawTextSurvives() {+ let root = accepted(state(pair))+ let text = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [root.id], text: "Original")+ let invalid = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [root.id], parentHeadIDs: [text.id, UUID()], operation: .clear)+ let fold = AssociationNoteFold(notes: [text, invalid], ledger: .init(events: [root]))+ #expect(fold.heads(for: pair).map(\.id) == [text.id])+ #expect(fold.invalidIDs.contains(invalid.id))+ #expect(fold.rawNotes.count == 2)+ }+ @Test func ordinaryRecoveryCannotConsumeAcrossPairs() {+ let root = accepted(state(pair))+ let text = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [root.id], text: "Original")+ let other = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let recovery = AssociationNoteValue(pair: other, attachmentAcceptanceIDs: [root.id], parentHeadIDs: [text.id], operation: .recover, text: "Original")+ let fold = AssociationNoteFold(notes: [text, recovery], ledger: .init(events: [root]))+ #expect(fold.heads(for: pair).map(\.id) == [text.id])+ #expect(fold.invalidIDs.contains(recovery.id))+ }+ @Test func concurrentTextAndClearPreserveUnseenTextHead() {+ let root = accepted(state(pair))+ let first = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [root.id], text: "First")+ let clear = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [root.id], parentHeadIDs: [first.id], operation: .clear)+ let unseen = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [root.id], parentHeadIDs: [first.id], text: "Unseen")+ let fold = AssociationNoteFold(notes: [unseen, clear, first], ledger: .init(events: [root]))+ #expect(Set(fold.heads(for: pair).map(\.id)) == [clear.id, unseen.id])+ #expect(fold.textHeads(for: pair, activeAcceptanceIDs: [root.id]).map(\.text) == ["Unseen"])+ }+ @Test func exactUnicodeVariantsOfOneImmutableNoteRemainRawAndQuarantined() {+ let root = accepted(state(pair))+ let first = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [root.id], text: "Ren\u{00e9}e")+ var other = first; other.text = "Rene\u{0301}e"+ #expect(first.text == other.text) // Swift canonical-equivalence baseline.+ #expect(first != other)+ let fold = AssociationNoteFold(notes: [first, other], ledger: .init(events: [root]))+ #expect(fold.invalidIDs.contains(first.id))+ #expect(fold.heads(for: pair).isEmpty)+ #expect(fold.rawNotes.map { Array($0.text.utf8) }.count == 2)+ #expect(Array(fold.rawNotes[0].text.utf8) != Array(fold.rawNotes[1].text.utf8))+ }+ @Test func systemNoteRebindCannotNormalizeAuthoredText() {+ let parent = accepted(state(pair))+ let destination = AssociationPair(workID: work, entryID: UUID(), kind: .character, recordID: record)+ let child = AssociationLedgerEvent(payload: .accept(.init(pair: destination, spellingKeys: ["alice"],+ rebind: .init(operation: .entryMerge(workID: work,+ fromEntryID: entry, toEntryID: destination.entryID), predecessorIDs: [parent.id]))))+ let first = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [parent.id], text: "Ren\u{00e9}e")+ let rebound = AssociationNoteValue(pair: destination, attachmentAcceptanceIDs: [child.id], parentHeadIDs: [first.id],+ operation: .rebind, text: "Rene\u{0301}e", rebindAcceptanceID: child.id)+ let fold = AssociationNoteFold(notes: [first, rebound], ledger: .init(events: [parent, child]))+ #expect(fold.invalidIDs.contains(rebound.id))+ #expect(fold.heads(for: pair).map(\.id) == [first.id])+ #expect(fold.rawNotes.count == 2)+ }+ @Test func barrierDigestIsTypedOrderIndependentAndIdempotent() {+ let a = AssociationLedgerEvent(payload: .invalidate(.entry(workID: work, entryID: entry)))+ let b = AssociationLedgerEvent(payload: .invalidate(.record(workID: work, kind: .character, recordID: record)))+ let events = [accepted(state(pair)), a, b]+ let first = AssociationLedgerInventory(events: events).receipt(for: state(pair))+ for order in [events.reversed().map { $0 }, [b, a] + events] {+ #expect(AssociationLedgerInventory(events: order).receipt(for: state(pair)) == first)+ }+ #expect(first.sourceBarrierDigest != first.recordBarrierDigest)+ }+ @Test func coverageChangesWhenMatchingDirectoryOrBarriersChange() {+ let empty = AssociationLedgerInventory(events: [])+ let a = empty.coverageDigest(workID: work, entryID: entry, sourceFingerprint: "S", matchingDirectory: "D1")+ #expect(a != empty.coverageDigest(workID: work, entryID: entry, sourceFingerprint: "S", matchingDirectory: "D2"))+ let invalidation = AssociationLedgerEvent(payload: .invalidate(.record(workID: work, kind: .place, recordID: record)))+ #expect(a != AssociationLedgerInventory(events: [invalidation]).coverageDigest(workID: work, entryID: entry, sourceFingerprint: "S", matchingDirectory: "D1"))+ }+ @Test func largeWorkFixtureUsesOneGroupedInventory() {+ // 600 chapters × 120-record directory, two accepted links/chapter.+ // This pure grouped-inventory fixture precedes the selected SwiftData+ // adapter measurement; it makes no database performance claim.+ let records = (0..<120).map { _ in UUID() }+ let pairs = (0..<600).flatMap { index -> [AssociationPair] in+ let chapter = UUID()+ return [0, 1].map { offset in+ AssociationPair(workID: work, entryID: chapter, kind: .character,+ recordID: records[(index + offset) % records.count])+ }+ }+ let events = pairs.map { accepted(state($0)) }+ let inventory = AssociationLedgerInventory(events: events)+ #expect(inventory.activeAcceptanceIDs(for: state(pairs[1199])).count == 1)+ #expect(inventory.eventCount == 1200)+ }+ @Test func exactUnicodeEvidenceHasTotalOrderAndStableReceipts() {+ let nfc = "Café", nfd = "Cafe\u{301}"+ let evidence = RecordMentionGrounding.evidence(names: [nfc], in: "\(nfc) met \(nfd).")+ let expected = [nfc, nfd].sorted { $0.utf8.lexicographicallyPrecedes($1.utf8) }+ #expect(evidence.map { Array($0.spelling.utf8) } == expected.map { Array($0.utf8) })+ let first = state(pair, spellings: [nfc, nfd])+ let reversed = state(pair, spellings: [nfd, nfc])+ let event = accepted(first)+ let inventory = AssociationLedgerInventory(events: [event])+ #expect(inventory.receipt(for: first) == inventory.receipt(for: reversed))+ #expect(inventory.receipt(for: reversed).evidence.map { Array($0.spelling.utf8) } == expected.map { Array($0.utf8) })+ #expect(inventory.activeAcceptanceIDs(for: reversed) == [event.id])+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationNoteAPITests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationNoteAPITests.swiftnew file mode 100644index 00000000..5617a56d--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationNoteAPITests.swift@@ -0,0 +1,279 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Association note APIs", .serialized)+struct AssociationNoteAPITests {+ private func fixture(strategy: any RepositorySaveStrategy = ModelContextSaveStrategy()) async throws -> (M5Fixture, AssociationPair) {+ let fixture = try await M5Fixture(saveStrategy: strategy)+ let pair = AssociationPair(workID: UUID(), entryID: UUID(), kind: .character, recordID: UUID())+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding association note fixture") { context in+ let work = Work(id: pair.workID, displayTitle: "Synthetic Work", timestamp: M5Fixture.epoch)+ let entry = Entry(id: pair.entryID, captureTitle: "Chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Alice arrived.")+ try entry.authorTarget(.init(kind: .chapter))+ let record = CharacterRecord(id: pair.recordID, name: "Alice", nameKey: "alice", work: nil)+ context.insert(work); context.insert(entry); context.insert(record); entry.work = work; LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch); record.work = work+ try context.save()+ }+ _ = try await fixture.repository.commitDecision(request(pair))+ return (fixture, pair)+ }+ private func request(_ pair: AssociationPair) -> DecisionRequest {+ .init(workID: pair.workID, kind: pair.kind, action: .accept, displayedKeys: ["alice"],+ displayedTargetID: pair.recordID, proposedName: "Alice",+ mentions: [.init(entryID: pair.entryID, noteFingerprint: CharacterCoverageFingerprint.of("Alice arrived."), spellingKeys: ["alice"])])+ }+ private func replaceNote(_ value: String, fixture: M5Fixture, pair: AssociationPair) async throws {+ let entry = try await fixture.repository.entry(id: pair.entryID)+ _ = try await fixture.repository.updateEntry(id: pair.entryID, basis: .init(entry: entry), note: value, rating: nil)+ }+ @Test func exactSaveReopenDoesNotChangeMembershipOrCoverage() async throws {+ let (fixture, pair) = try await fixture()+ let before = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [pair.workID]).first)+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ let text = "Cafe\u{301} exact text"+ #expect(try await fixture.repository.saveAssociationNote(basis: basis, text: text) == .committed)+ let reopened = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ #expect(reopened.acceptanceIDs == basis.acceptanceIDs)+ #expect(reopened.validationReceipt == basis.validationReceipt)+ #expect(reopened.heads.map { Array($0.text.utf8) } == [Array(text.utf8)])+ let after = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [pair.workID]).first)+ #expect(after.sources.map(\.mentionEligibilityDigest) == before.sources.map(\.mentionEligibilityDigest))+ withExtendedLifetime(fixture) {}+ }+ @Test func staleHeadBasisRefusesWithoutConsumingUnseenText() async throws {+ let (fixture, pair) = try await fixture()+ let initial = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ _ = try await fixture.repository.saveAssociationNote(basis: initial, text: "Original")+ let stale = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ _ = try await fixture.repository.saveAssociationNote(basis: stale, text: "Arrived elsewhere")+ let draft = "Cafe\u{301} unsaved draft"+ #expect(try await fixture.repository.saveAssociationNote(basis: stale, text: draft) == .reviewRequired)+ #expect(try await fixture.repository.clearAssociationNote(basis: stale) == .reviewRequired)+ let current = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ #expect(current.heads.map(\.text) == ["Arrived elsewhere"])+ #expect(Array(draft.utf8) == Array("Cafe\u{301} unsaved draft".utf8))+ withExtendedLifetime(fixture) {}+ }+ @Test func clearRemainsConsumedAfterMembershipRetiresAndReturns() async throws {+ let (fixture, pair) = try await fixture()+ _ = try await fixture.repository.saveAssociationNote(basis: try #require(try await fixture.repository.associationNoteBasis(pair: pair)), text: "Old text")+ _ = try await fixture.repository.clearAssociationNote(basis: try #require(try await fixture.repository.associationNoteBasis(pair: pair)))+ try await replaceNote("Nobody arrived.", fixture: fixture, pair: pair)+ #expect(try await fixture.repository.detachedAssociationNotes().isEmpty)+ try await replaceNote("Alice arrived.", fixture: fixture, pair: pair)+ _ = try await fixture.repository.commitDecision(request(pair))+ #expect(try await fixture.repository.detachedAssociationNotes().isEmpty)+ #expect(try #require(try await fixture.repository.associationNoteBasis(pair: pair)).heads.isEmpty)+ withExtendedLifetime(fixture) {}+ }+ @Test func newAcceptanceRequiresExplicitSamePairSelectedRecovery() async throws {+ let (fixture, pair) = try await fixture()+ _ = try await fixture.repository.saveAssociationNote(basis: try #require(try await fixture.repository.associationNoteBasis(pair: pair)), text: "Kept exact text")+ let old = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ let oldHead = try #require(old.heads.first)+ try await replaceNote("Nobody arrived.", fixture: fixture, pair: pair)+ try await replaceNote("Alice arrived.", fixture: fixture, pair: pair)+ _ = try await fixture.repository.commitDecision(request(pair))+ let current = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ #expect(current.acceptanceIDs.isDisjoint(with: old.acceptanceIDs))+ #expect(current.heads.isEmpty)+ #expect(try await fixture.repository.detachedAssociationNotes().contains { $0.raw.id == oldHead.id && $0.canRecover })+ var unknown = oldHead; unknown.id = UUID()+ #expect(try await fixture.repository.recoverAssociationNotes(basis: current, selectedHeads: [unknown], text: oldHead.text) == .reviewRequired)+ #expect(try await fixture.repository.recoverAssociationNotes(basis: current, selectedHeads: [oldHead], text: oldHead.text) == .committed)+ #expect(try #require(try await fixture.repository.associationNoteBasis(pair: pair)).heads.map(\.text) == [oldHead.text])+ #expect(try await fixture.repository.detachedAssociationNotes().isEmpty)+ withExtendedLifetime(fixture) {}+ }+ @Test func malformedMetadataNeverCreatesEmptyWritableBasis() async throws {+ let (fixture, pair) = try await fixture()+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding malformed raw authored variant") { context in+ let row = PairNoteVersion()+ row.workID = pair.workID; row.originPairData = try JSONBlob.encode(pair)+ row.attachmentAcceptIDsData = try JSONBlob.encode(Array(basis.acceptanceIDs))+ row.parentHeadIDsData = Data([0xff]); row.text = "Cafe\u{301} recoverable raw"+ row.originalContextData = try JSONBlob.encode("Original chapter")+ context.insert(row); try context.save()+ }+ #expect(try await fixture.repository.associationNoteBasis(pair: pair) == nil)+ #expect(try await fixture.repository.saveAssociationNote(basis: basis, text: "Attempt") == .invalidMetadata)+ let variants = try await fixture.repository.detachedAssociationNotes()+ #expect(variants.count == 1)+ #expect(variants.first?.canRecover == false)+ #expect(variants.first.map { Array($0.raw.text.utf8) } == Array("Cafe\u{301} recoverable raw".utf8))+ withExtendedLifetime(fixture) {}+ }+ @Test func failedNoteSaveLeavesHeadBasisAndMembershipUnchanged() async throws {+ let strategy = InstrumentedSaveStrategy()+ let (fixture, pair) = try await fixture(strategy: strategy)+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ strategy.resetCounts(); strategy.shouldFail = true+ do { _ = try await fixture.repository.saveAssociationNote(basis: basis, text: "Exact draft"); Issue.record("injected save must fail") }+ catch { }+ strategy.shouldFail = false+ #expect(strategy.attemptCount == 1 && strategy.successCount == 0)+ let current = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ #expect(current.headIDs == basis.headIDs)+ #expect(current.acceptanceIDs == basis.acceptanceIDs)+ #expect(current.validationReceipt == basis.validationReceipt)+ withExtendedLifetime(fixture) {}+ }+ @Test func sameIDCurrentHeadBodyReplacementRefusesCapturedSave() async throws {+ let (fixture, pair) = try await fixture()+ _ = try await fixture.repository.saveAssociationNote(basis: try #require(try await fixture.repository.associationNoteBasis(pair: pair)), text: "Original")+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "simulating sole-head body replacement") { context in+ let row = try #require(try context.fetch(FetchDescriptor<PairNoteVersion>()).first)+ row.text = "Unseen replacement"; try context.save()+ }+ #expect(try await fixture.repository.saveAssociationNote(basis: basis, text: "Draft") == .reviewRequired)+ #expect(try #require(try await fixture.repository.associationNoteBasis(pair: pair)).heads.map(\.text) == ["Unseen replacement"])+ withExtendedLifetime(fixture) {}+ }+ @Test func exactContextOnlyHeadReplacementRefusesCapturedClear() async throws {+ let (fixture, pair) = try await fixture()+ _ = try await fixture.repository.saveAssociationNote(basis: try #require(try await fixture.repository.associationNoteBasis(pair: pair)), text: "Original")+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding exact context") { context in+ let row = try #require(try context.fetch(FetchDescriptor<PairNoteVersion>()).first)+ row.originalContextData = try JSONBlob.encode("Café"); try context.save()+ }+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "replacing only context scalars") { context in+ let row = try #require(try context.fetch(FetchDescriptor<PairNoteVersion>()).first)+ row.originalContextData = try JSONBlob.encode("Cafe\u{301}"); try context.save()+ }+ #expect(try await fixture.repository.clearAssociationNote(basis: basis) == .reviewRequired)+ let current = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ #expect(current.heads.map { Array($0.originalContext.utf8) } == [Array("Cafe\u{301}".utf8)])+ withExtendedLifetime(fixture) {}+ }+ @Test func selectedDetachedBodyReplacementRefusesRecovery() async throws {+ let (fixture, pair) = try await fixture()+ _ = try await fixture.repository.saveAssociationNote(basis: try #require(try await fixture.repository.associationNoteBasis(pair: pair)), text: "Original")+ let loaded = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ let head = try #require(loaded.heads.first)+ try await replaceNote("Nobody arrived.", fixture: fixture, pair: pair)+ try await replaceNote("Alice arrived.", fixture: fixture, pair: pair)+ _ = try await fixture.repository.commitDecision(request(pair))+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "changing selected detached body") { context in+ let row = try #require(try context.fetch(FetchDescriptor<PairNoteVersion>()).first)+ row.text = "Changed detached text"; try context.save()+ }+ #expect(try await fixture.repository.recoverAssociationNotes(basis: basis, selectedHeads: [head], text: head.text) == .reviewRequired)+ #expect(try #require(try await fixture.repository.associationNoteBasis(pair: pair)).heads.isEmpty)+ #expect(try await fixture.repository.detachedAssociationNotes().contains { $0.raw.text == "Changed detached text" })+ withExtendedLifetime(fixture) {}+ }+ @Test func contradictoryRawUnicodeVariantsHaveSeparatePresentationIdentities() async throws {+ let (fixture, pair) = try await fixture()+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ let id = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding exact contradictory note variants") { context in+ for text in ["Café", "Cafe\u{301}"] {+ context.insert(try PairNoteVersion(note: .init(id: id, pair: pair,+ attachmentAcceptanceIDs: Array(basis.acceptanceIDs), text: text, originalContext: "Original chapter")))+ }+ try context.save()+ }+ let variants = try await fixture.repository.detachedAssociationNotes()+ #expect(variants.count == 2 && Set(variants.map(\.id)).count == 2)+ #expect(variants.allSatisfy { !$0.canRecover && $0.head == nil })+ #expect(Set(variants.map { Array($0.raw.text.utf8) }) == Set([Array("Café".utf8), Array("Cafe\u{301}".utf8)]))+ #expect(try await fixture.repository.associationNoteBasis(pair: pair) == nil)+ withExtendedLifetime(fixture) {}+ }++ @Test func concurrentTextAfterClearRemainsHeadAndStaleSaveRefuses() async throws {+ let (fixture, pair) = try await fixture()+ _ = try await fixture.repository.saveAssociationNote(basis: try #require(try await fixture.repository.associationNoteBasis(pair: pair)), text: "Original")+ let stale = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ _ = try await fixture.repository.clearAssociationNote(basis: stale)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "arriving concurrent note save") { context in+ let unseen = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: Array(stale.acceptanceIDs),+ parentHeadIDs: Array(stale.headIDs), text: "Unseen concurrent text", originalContext: stale.originalContext)+ context.insert(try PairNoteVersion(note: unseen)); try context.save()+ }+ let both = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ #expect(both.heads.count == 2)+ #expect(both.heads.contains { $0.operation == .clear })+ #expect(both.heads.contains { $0.text == "Unseen concurrent text" })+ #expect(try await fixture.repository.saveAssociationNote(basis: stale, text: "Stale draft") == .reviewRequired)+ #expect(try #require(try await fixture.repository.associationNoteBasis(pair: pair)).heads == both.heads)+ withExtendedLifetime(fixture) {}+ }++ @Test func finiteCombineConversionPreservesBothExactHeadsAtUnsupportedFinalKind() async throws {+ let strategy = InstrumentedSaveStrategy()+ let (fixture, pair) = try await fixture(strategy: strategy)+ try await replaceNote("Alice arrived.", fixture: fixture, pair: pair)+ let targetID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding second active record and distinct authored head") { context in+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first { $0.id == pair.workID })+ context.insert(CharacterRecord(id: targetID, name: "Ally", nameKey: "ally", aliases: ["Alice"], work: work)); try context.save()+ }+ let other = AssociationPair(workID: pair.workID, entryID: pair.entryID, kind: .character, recordID: targetID)+ _ = try await fixture.repository.commitDecision(.init(workID: pair.workID, kind: .character, action: .accept,+ displayedKeys: ["ally"], displayedTargetID: targetID, proposedName: "Ally", mentions: [+ .init(entryID: pair.entryID, noteFingerprint: CharacterCoverageFingerprint.of("Alice arrived."), spellingKeys: ["alice"])]))+ let firstText = "Cafe\u{301} Alice observation", secondText = "Café Ally observation"+ _ = try await fixture.repository.saveAssociationNote(basis: try #require(try await fixture.repository.associationNoteBasis(pair: pair)), text: firstText)+ _ = try await fixture.repository.saveAssociationNote(basis: try #require(try await fixture.repository.associationNoteBasis(pair: other)), text: secondText)+ let source = RecordEditBasis(kind: .character, recordID: pair.recordID, name: "Alice", note: "", aliases: [], facts: [])+ let target = RecordEditBasis(kind: .character, recordID: targetID, name: "Ally", note: "", aliases: ["Alice"], facts: [])+ let operations: [RecordEditOperation] = [.combine(source: source, target: target),+ .convert(basis: target, to: .place, draft: .init(kind: .place, name: "Harbor"))]+ strategy.resetCounts(); strategy.shouldFail = true+ do { _ = try await fixture.repository.commitRecordEdits(workID: pair.workID, operations: operations); Issue.record("injected identity-chain save must fail") }+ catch { }+ strategy.shouldFail = false+ #expect(try #require(try await fixture.repository.associationNoteBasis(pair: pair)).heads.map { ExactScalarString($0.text) } == [ExactScalarString(firstText)])+ #expect(try #require(try await fixture.repository.associationNoteBasis(pair: other)).heads.map { ExactScalarString($0.text) } == [ExactScalarString(secondText)])+ guard case .committed(let ids) = try await fixture.repository.commitRecordEdits(workID: pair.workID, operations: operations) else {+ Issue.record("verified identity chain must commit"); return+ }+ let final = AssociationPair(workID: pair.workID, entryID: pair.entryID, kind: .place, recordID: try #require(ids.last))+ #expect(try await fixture.repository.associationNoteBasis(pair: final) == nil)+ let detached = try await fixture.repository.detachedAssociationNotes().filter { $0.pair == final }+ #expect(detached.count == 2 && detached.allSatisfy { !$0.canRecover })+ #expect(Set(detached.map { Data($0.raw.text.utf8) }) == Set([Data(firstText.utf8), Data(secondText.utf8)]))+ try await replaceNote("Harbor remains.", fixture: fixture, pair: pair)+ _ = try await fixture.repository.commitDecision(.init(workID: pair.workID, kind: .place, action: .accept,+ displayedKeys: ["harbor"], displayedTargetID: final.recordID, proposedName: "Harbor", mentions: [+ .init(entryID: pair.entryID, noteFingerprint: CharacterCoverageFingerprint.of("Harbor remains."), spellingKeys: ["harbor"])]))+ let fresh = try #require(try await fixture.repository.associationNoteBasis(pair: final))+ #expect(fresh.heads.isEmpty)+ #expect(try await fixture.repository.recoverAssociationNotes(basis: fresh,+ selectedHeads: detached.compactMap(\.head), text: "Explicit reader resolution") == .committed)+ #expect(try #require(try await fixture.repository.associationNoteBasis(pair: final)).heads.map(\.text) == ["Explicit reader resolution"])+ withExtendedLifetime(fixture) {}+ }++ @Test func validDetachedHeadFromAnotherPairCannotBeRecoveredIntoCurrentPair() async throws {+ let (fixture, pairA) = try await fixture()+ let pairB = AssociationPair(workID: pairA.workID, entryID: UUID(), kind: pairA.kind, recordID: pairA.recordID)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding another ordinary chapter pair") { context in+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first { $0.id == pairA.workID })+ let entry = Entry(id: pairB.entryID, captureTitle: "Other chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Alice arrived.")+ try entry.authorTarget(.init(kind: .chapter)); context.insert(entry); entry.work = work; LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch); try context.save()+ }+ _ = try await fixture.repository.commitDecision(request(pairB))+ _ = try await fixture.repository.saveAssociationNote(basis: try #require(try await fixture.repository.associationNoteBasis(pair: pairB)), text: "Other chapter exact text")+ let loadedB = try #require(try await fixture.repository.associationNoteBasis(pair: pairB))+ let headB = try #require(loadedB.heads.first)+ try await replaceNote("No supported names.", fixture: fixture, pair: pairB)+ let basisA = try #require(try await fixture.repository.associationNoteBasis(pair: pairA))+ #expect(try await fixture.repository.recoverAssociationNotes(basis: basisA,+ selectedHeads: [headB], text: headB.text) == .reviewRequired)+ #expect(try await fixture.repository.associationNoteBasis(pair: pairA) == basisA)+ #expect(try await fixture.repository.associationNoteBasis(pair: pairB) == nil)+ #expect(try await fixture.repository.detachedAssociationNotes().contains { $0.head == headB && $0.pair == pairB })+ withExtendedLifetime(fixture) {}+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationPendingReviewTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationPendingReviewTests.swiftnew file mode 100644index 00000000..b6858078--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationPendingReviewTests.swift@@ -0,0 +1,273 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Durable source-scoped pending mention reviews", .serialized)+struct AssociationPendingReviewTests {+ private struct IDs: Sendable { let work = UUID(), entry = UUID(), ada = UUID(), bryn = UUID() }+ private final class SwitchSave: RepositorySaveStrategy, @unchecked Sendable {+ private let lock = NSLock()+ private var fail = false+ func arm() { lock.withLock { fail = true } }+ func save(_ context: ModelContext) throws {+ let shouldFail = lock.withLock { let value = fail; fail = false; return value }+ if shouldFail { throw CocoaError(.fileWriteUnknown) }+ try context.save()+ }+ }+ private func fixture(alias: Bool = false, save: any RepositorySaveStrategy = ModelContextSaveStrategy()) async throws -> (M5Fixture, IDs) {+ let fixture = try await M5Fixture(saveStrategy: save), ids = IDs()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding synthetic pending review") { context in+ let work = Work(id: ids.work, displayTitle: "Synthetic pending Work", timestamp: M5Fixture.epoch)+ let chapter = Entry(id: ids.entry, captureTitle: "Chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Ada visits Bryn and Cora.")+ try chapter.authorTarget(.init(kind: .chapter)); context.insert(work); context.insert(chapter)+ chapter.work = work; LibraryRepository.applyManualAssignment(to: chapter, at: M5Fixture.epoch)+ context.insert(CharacterRecord(id: ids.ada, name: "Ada", nameKey: "ada", work: work))+ context.insert(CharacterRecord(id: ids.bryn, name: alias ? "Briar" : "Bryn", nameKey: alias ? "briar" : "bryn",+ aliases: alias ? ["Bryn"] : [], work: work))+ try context.save()+ }+ return (fixture, ids)+ }+ private func candidate(_ fixture: M5Fixture, _ ids: IDs) async throws -> ExtractionCandidate {+ try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ }+ private func source(_ fixture: M5Fixture, _ ids: IDs) async throws -> CharacterExtractionSource {+ try #require(try await candidate(fixture, ids).sources.first { $0.ref == .entry(ids.entry) })+ }+ private func completed(_ source: CharacterExtractionSource) -> CompletedSource {+ .init(ref: source.ref, fingerprint: source.fingerprint, mentionEligibilityDigest: source.mentionEligibilityDigest)+ }+ private func request(_ fixture: M5Fixture, _ ids: IDs, key: String = "bryn", target: UUID? = nil) async throws -> AssociationPendingReviewRequest {+ let current = try await candidate(fixture, ids)+ return .init(marker: .init(workID: ids.work, entryID: ids.entry,+ sourceGuard: try #require(current.mentionIndex.sourceGuards[ids.entry]),+ items: [.init(key: .init(kind: .character, nameKey: key), targetID: target ?? (key == "bryn" ? ids.bryn : nil), spellingKeys: [key])]),+ originalEligibilityBase: current.mentionIndex.coverageBases[ids.entry], originalEligibilityDigest: current.mentionIndex.eligibilityByEntry[ids.entry])+ }+ private func decide(_ fixture: M5Fixture, _ ids: IDs, saved: AssociationPendingReviewResult,+ name: String = "Bryn", key: String = "bryn", kind: RecordKind = .character,+ target: UUID?, action: DecisionAction = .accept) async throws {+ let current = try await source(fixture, ids)+ let request = DecisionRequest(workID: ids.work, kind: kind, action: action, displayedKeys: [key],+ displayedTargetID: target, proposedName: name,+ completedSources: [.init(ref: .entry(ids.entry), fingerprint: current.fingerprint, mentionEligibilityDigest: saved.completionDigest)],+ mentions: [.init(entryID: ids.entry, noteFingerprint: current.fingerprint, spellingKeys: [key])],+ reviewAcknowledgements: [.init(workID: ids.work, entryID: ids.entry, references: saved.references)],+ reviewedKey: .init(kind: .character, nameKey: key))+ guard case .committed = try await fixture.repository.commitDecision(request) else { Issue.record("Expected explicit decision"); return }+ }++ @Test func markerIsIdempotentCoverageOnlyAndOldCompletionCannotReplay() async throws {+ let (fixture, ids) = try await fixture()+ let original = try await source(fixture, ids)+ _ = try await fixture.repository.advanceCoverage(workID: ids.work, sources: [completed(original)])+ #expect(try await source(fixture, ids).isCovered)+ let before = try await candidate(fixture, ids)+ let registration = try await request(fixture, ids)+ let saved = try #require(try await fixture.repository.recordPendingMentionReviews([registration]).first)+ #expect(saved.completionDigest != nil)+ #expect(try await !source(fixture, ids).isCovered)+ let now = try await candidate(fixture, ids)+ #expect(now.mentionIndex.sourceGuards == before.mentionIndex.sourceGuards)+ #expect(now.mentionIndex.activePairs == before.mentionIndex.activePairs)+ #expect(now.sources.first { $0.ref == .entry(ids.entry) }?.coveredFingerprint == original.fingerprint)+ let snapshot = try await fixture.repository.backupV20Snapshot()+ _ = try await fixture.repository.recordPendingMentionReviews([registration])+ _ = try await fixture.repository.advanceCoverage(workID: ids.work, sources: [completed(original), completed(try await source(fixture, ids))])+ #expect(try await fixture.repository.backupV20Snapshot() == snapshot)+ #expect(try await !source(fixture, ids).isCovered)+ try await decide(fixture, ids, saved: saved, target: ids.bryn)+ #expect(try await source(fixture, ids).isCovered)+ withExtendedLifetime(fixture) {}+ }++ @Test("Explicit Keep/Skip and reclassification acknowledge only captured original keys", arguments: [0, 1, 2, 3])+ func explicitDecisionClosesItsOwnPendingKey(mode: Int) async throws {+ let (fixture, ids) = try await fixture()+ let isNew = mode == 2+ let registration = try await request(fixture, ids, key: isNew ? "cora" : "bryn")+ let saved = try #require(try await fixture.repository.recordPendingMentionReviews([registration]).first)+ try await decide(fixture, ids, saved: saved, name: isNew ? "Cora" : "Bryn", key: isNew ? "cora" : "bryn",+ kind: mode == 3 ? .place : .character, target: isNew || mode == 3 ? nil : ids.bryn,+ action: mode == 1 || mode == 2 ? .skip : .accept)+ #expect(try await candidate(fixture, ids).mentionIndex.pendingReviewReferences[ids.entry, default: []].isEmpty)+ _ = try await fixture.repository.advanceCoverage(workID: ids.work, sources: [completed(try await source(fixture, ids))])+ #expect(try await source(fixture, ids).isCovered)+ withExtendedLifetime(fixture) {}+ }++ @Test func decidingAnUnrelatedNameCannotAcknowledgeB() async throws {+ let (fixture, ids) = try await fixture()+ let saved = try #require(try await fixture.repository.recordPendingMentionReviews([try await request(fixture, ids)]).first)+ try await decide(fixture, ids, saved: saved, name: "Ada", key: "ada", target: ids.ada)+ #expect(try await !source(fixture, ids).isCovered)+ #expect(try await candidate(fixture, ids).mentionIndex.pendingReviewReferences[ids.entry]?.map(\.key.nameKey) == ["bryn"])+ withExtendedLifetime(fixture) {}+ }++ @Test("Directory churn or missing targets cannot clear B; genuine support/revision loss can", arguments: [0, 1, 2, 3, 4, 5])+ func relevanceIsIndependentOfGlobalDirectoryChurn(mode: Int) async throws {+ let (fixture, ids) = try await fixture(alias: mode == 4)+ _ = try await fixture.repository.recordPendingMentionReviews([try await request(fixture, ids)])+ switch mode {+ case 0:+ _ = try await fixture.repository.commitRecordEdits(workID: ids.work, operations: [.create(.init(kind: .character, name: "Unrelated C"))])+ case 1, 4:+ let row = try #require(try await fixture.repository.workDetail(id: ids.work).characters.first { $0.id == ids.bryn })+ _ = try await fixture.repository.commitRecordEdits(workID: ids.work, operations: [.update(basis: row.editBasis,+ draft: .init(kind: .character, name: mode == 1 ? "Bryn of the Harbor" : "Briar", aliases: []))])+ case 2:+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "simulating absent pending target") { context in+ for row in try context.fetch(FetchDescriptor<CharacterRecord>()) where row.id == ids.bryn { context.delete(row) }+ try context.save()+ }+ case 3:+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "simulating contradictory pending target") { context in+ let other = Work(displayTitle: "Off-scope synthetic Work", timestamp: M5Fixture.epoch)+ context.insert(other); context.insert(CharacterRecord(id: ids.bryn, name: "Other", nameKey: "bryn", work: other)); try context.save()+ }+ default:+ let entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "No known names.", rating: nil)+ }+ _ = try await fixture.repository.advanceCoverage(workID: ids.work, sources: [completed(try await source(fixture, ids))])+ #expect(try await source(fixture, ids).isCovered == (mode >= 4))+ withExtendedLifetime(fixture) {}+ }++ @Test func failedMarkerSaveRollsBackAndSameSettlementRetriesOnce() async throws {+ let save = SwitchSave(), (fixture, ids) = try await fixture(save: save)+ let registration = try await request(fixture, ids)+ let before = try await fixture.repository.backupV20Snapshot()+ save.arm()+ await #expect(throws: (any Error).self) { try await fixture.repository.recordPendingMentionReviews([registration]) }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ _ = try await fixture.repository.recordPendingMentionReviews([registration])+ let once = try await fixture.repository.backupV20Snapshot()+ _ = try await fixture.repository.recordPendingMentionReviews([registration])+ #expect(try await fixture.repository.backupV20Snapshot() == once)+ #expect(once.associationEvents.filter { $0.id == registration.markerID }.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test("Conflicting/malformed pending identities and acknowledgements stay conservative", arguments: [0, 1, 2])+ func physicalConflictCannotResurrectCoverage(mode: Int) async throws {+ let (fixture, ids) = try await fixture()+ let registration = try await request(fixture, ids)+ let saved = try #require(try await fixture.repository.recordPendingMentionReviews([registration]).first)+ if mode == 2 { try await decide(fixture, ids, saved: saved, target: ids.bryn); #expect(try await source(fixture, ids).isCovered) }+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "arriving conflicting coverage metadata") { context in+ let rows = try context.fetch(FetchDescriptor<AssociationEvent>())+ let original = try #require(rows.first { row in+ if mode != 2 { return row.id == registration.markerID }+ if case .reviewAcknowledgement = row.ledgerValue?.payload { return true }; return false+ })+ let duplicate = AssociationEvent()+ duplicate.id = original.id; duplicate.workID = original.workID; duplicate.entryID = original.entryID+ duplicate.recordKindRaw = original.recordKindRaw; duplicate.recordID = original.recordID+ duplicate.eventData = original.eventData; duplicate.validationData = original.validationData; duplicate.recordedAt = original.recordedAt+ if mode == 0 {+ var conflicting = registration.marker; conflicting.items[0].key.nameKey = "cora"+ duplicate.eventData = try JSONBlob.encode(AssociationEventPayload.pendingReview(conflicting))+ } else { duplicate.workID = UUID(); duplicate.eventData = Data([0xff]) }+ context.insert(duplicate); try context.save()+ }+ _ = try await fixture.repository.advanceCoverage(workID: ids.work, sources: [completed(try await source(fixture, ids))])+ #expect(try await !source(fixture, ids).isCovered)+ if mode == 2 { #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry).first?.activeAcceptanceIDs.isEmpty == false) }+ withExtendedLifetime(fixture) {}+ }++ @Test func changedOriginalContextIsNotBlessedAndArchiveReplayRetainsPendingKeys() async throws {+ let (fixture, ids) = try await fixture()+ let stale = try await request(fixture, ids)+ let entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Bryn remains with Ada.", rating: nil)+ let refusedBasis = try #require(try await fixture.repository.recordPendingMentionReviews([stale]).first)+ #expect(refusedBasis.completionDigest == nil)+ let current = try await request(fixture, ids)+ _ = try await fixture.repository.recordPendingMentionReviews([current])+ let payload = try await fixture.repository.backupV20Snapshot()+ let plan = try BackupImporter.plan(from: BackupV20Codec.encode(payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch)))+ let restored = try await M5Fixture()+ _ = try await restored.repository.confirmImport(plan: plan)+ #expect(try await !source(restored, ids).isCovered)+ _ = try await restored.repository.advanceCoverage(workID: ids.work, sources: [completed(try await source(restored, ids))])+ #expect(try await !source(restored, ids).isCovered)+ let first = try await restored.repository.backupV20Snapshot()+ _ = try await restored.repository.confirmImport(plan: plan)+ #expect(try await restored.repository.backupV20Snapshot() == first)+ #expect(first.associationEvents.filter { $0.id == current.markerID }.count == 1)+ withExtendedLifetime((fixture, restored)) {}+ }+ @Test("Only an exact original Keep witness can resolve redundant settlement", arguments: [0, 1, 2, 3, 4, 5])+ func redundantKeepRequiresExactTypedWitness(mode: Int) async throws {+ let (fixture, ids) = try await fixture()+ let key = mode == 4 ? "cora" : "bryn"+ let first = try await request(fixture, ids, key: key)+ let saved = try #require(try await fixture.repository.recordPendingMentionReviews([first]).first)+ var second = first+ second.markerID = UUID()+ if mode == 1 { second.marker.items[0].spellingKeys = ["ada", "bryn"] }+ if mode == 2 {+ let otherID = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding a distinct supported typed target") { context in+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ context.insert(CharacterRecord(id: otherID, name: "Other", nameKey: "other-bryn", aliases: ["Bryn"], work: work)); try context.save()+ }+ second.marker.items[0].targetID = otherID+ }+ if mode != 3 { _ = try await fixture.repository.recordPendingMentionReviews([second]) }+ try await decide(fixture, ids, saved: saved, name: mode == 4 ? "Cora" : "Bryn", key: key,+ kind: mode == 5 ? .place : .character,+ target: mode == 4 || mode == 5 ? nil : ids.bryn, action: mode == 3 ? .skip : .accept)+ if mode == 3 {+ second = try await request(fixture, ids)+ _ = try await fixture.repository.recordPendingMentionReviews([second])+ }+ _ = try await fixture.repository.advanceCoverage(workID: ids.work, sources: [completed(try await source(fixture, ids))])+ #expect(try await source(fixture, ids).isCovered == (mode == 0 || mode == 4))+ let pending = try await candidate(fixture, ids).mentionIndex.pendingReviewReferences[ids.entry, default: []]+ #expect(pending.contains { $0.markerID == second.markerID } == !(mode == 0 || mode == 4))+ withExtendedLifetime(fixture) {}+ }++ @Test func removedAliasUsesExistingRerouteRefusalBeforeFeaturePreflight() async throws {+ let (fixture, ids) = try await fixture(alias: true)+ let registration = try await request(fixture, ids)+ let saved = try #require(try await fixture.repository.recordPendingMentionReviews([registration]).first)+ let row = try #require(try await fixture.repository.workDetail(id: ids.work).characters.first { $0.id == ids.bryn })+ let edit = try await fixture.repository.commitRecordEdits(workID: ids.work, operations: [.update(basis: row.editBasis,+ draft: .init(kind: .character, name: "Briar", aliases: []))])+ guard case .committed = edit else { Issue.record("Expected alias removal"); return }+ let changed = try #require(try await fixture.repository.workDetail(id: ids.work).characters.first { $0.id == ids.bryn })+ #expect(changed.aliases.isEmpty)+ let current = try await source(fixture, ids)+ let before = try await fixture.repository.backupV20Snapshot()+ let result = try await fixture.repository.commitDecision(.init(workID: ids.work, kind: .character,+ action: .accept, displayedKeys: ["bryn"], displayedTargetID: ids.bryn, proposedName: "Bryn",+ completedSources: [completed(current)],+ mentions: [.init(entryID: ids.entry, noteFingerprint: current.fingerprint, spellingKeys: ["bryn"])],+ reviewAcknowledgements: [.init(workID: ids.work, entryID: ids.entry, references: saved.references)],+ reviewedKey: .init(kind: .character, nameKey: "bryn")))+ #expect(result == .refused(.reRouted(to: nil)))+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }++ @Test func contradictoryKnownTargetAcknowledgementSuppliesNoKeepWitness() {+ let work = UUID(), entry = UUID(), original = UUID(), different = UUID()+ let item = AssociationPendingReviewItem(key: .init(kind: .character, nameKey: "bryn"), targetID: original, spellingKeys: ["bryn"])+ let marker = AssociationLedgerEvent(payload: .pendingReview(.init(workID: work, entryID: entry, sourceGuard: "guard", items: [item])))+ let reference = AssociationReviewReference(markerID: marker.id, key: item.key)+ let acknowledgement = AssociationLedgerEvent(payload: .reviewAcknowledgement(.init(workID: work, entryID: entry,+ references: [reference], outcome: .kept(kind: .character, recordID: different))))+ let inventory = AssociationPendingReviewInventory(events: [marker, acknowledgement])+ #expect(inventory.isAcknowledged(reference))+ #expect(inventory.keepWitnesses.isEmpty)+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationPendingSuppressionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationPendingSuppressionTests.swiftnew file mode 100644index 00000000..0b5c50bf--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationPendingSuppressionTests.swift@@ -0,0 +1,112 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Pending creation rejection relevance", .serialized)+struct AssociationPendingSuppressionTests {+ private struct IDs: Sendable { let work = UUID(), entry = UUID(), known = UUID() }+ private func fixture() async throws -> (M5Fixture, IDs) {+ let fixture = try await M5Fixture(), ids = IDs()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding pending rejection scope") { context in+ let work = Work(id: ids.work, displayTitle: "Synthetic scope Work", timestamp: M5Fixture.epoch)+ let entry = Entry(id: ids.entry, captureTitle: "Synthetic chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Ada meets Cora.")+ try entry.authorTarget(.init(kind: .chapter)); context.insert(work); context.insert(entry); entry.work = work+ LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch)+ context.insert(CharacterRecord(id: ids.known, name: "Ada", nameKey: "ada", work: work)); try context.save()+ }+ return (fixture, ids)+ }+ private func candidate(_ fixture: M5Fixture, _ ids: IDs) async throws -> ExtractionCandidate {+ try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ }+ private func registration(_ fixture: M5Fixture, _ ids: IDs, kind: RecordKind, key: String = "cora", target: UUID? = nil) async throws -> AssociationPendingReviewRequest {+ let current = try await candidate(fixture, ids)+ return .init(marker: .init(workID: ids.work, entryID: ids.entry,+ sourceGuard: try #require(current.mentionIndex.sourceGuards[ids.entry]),+ items: [.init(key: .init(kind: kind, nameKey: key), targetID: target, spellingKeys: [key])]),+ originalEligibilityBase: current.mentionIndex.coverageBases[ids.entry], originalEligibilityDigest: current.mentionIndex.eligibilityByEntry[ids.entry])+ }+ private func suppress(_ fixture: M5Fixture, _ ids: IDs, key: String, kind: RecordKind = .character) async throws {+ _ = try await fixture.repository.commitDecision(.init(workID: ids.work, kind: kind, action: .skip,+ displayedKeys: [key], proposedName: key))+ }++ @Test func foldedSkipMakesSyntheticPlaceCandidateIrrelevantWithoutAcknowledgingIt() async throws {+ let (fixture, ids) = try await fixture()+ let character = try await registration(fixture, ids, kind: .character)+ let place = try await registration(fixture, ids, kind: .place)+ let saved = try await fixture.repository.recordPendingMentionReviews([character, place])+ let source = try #require(try await candidate(fixture, ids).sources.first)+ _ = try await fixture.repository.commitDecision(.init(workID: ids.work, returnedKinds: [.character, .place],+ action: .skip, displayedKeys: ["cora"], proposedName: "Cora", completedSources: [source.completedSource],+ reviewAcknowledgements: [.init(workID: ids.work, entryID: ids.entry,+ references: try #require(saved.first { $0.references.contains { $0.markerID == character.markerID } }).references)],+ reviewedKey: .init(kind: .character, nameKey: "cora")))+ let afterSkip = try await candidate(fixture, ids)+ #expect(afterSkip.mentionIndex.pendingReviewReferences[ids.entry, default: []].isEmpty)+ let after = try await fixture.repository.backupV20Snapshot()+ let ledger = AssociationLedgerInventory(events: after.associationEvents.compactMap(\.value))+ #expect(!ledger.pendingReviews.isAcknowledged(.init(markerID: place.markerID, key: .init(kind: .place, nameKey: "cora"))))+ // Registration and the candidate reader agree on relevance without minting acknowledgement events.+ let registrationAgain = try #require(try await fixture.repository.recordPendingMentionReviews([place]).first)+ #expect(registrationAgain.references.isEmpty)+ #expect(try await fixture.repository.backupV20Snapshot() == after)+ _ = try await fixture.repository.advanceCoverage(workID: ids.work,+ sources: [try #require(try await candidate(fixture, ids).sources.first).completedSource])+ #expect(try await candidate(fixture, ids).sources.first?.isCovered == true)+ withExtendedLifetime(fixture) {}+ }++ @Test func candidateRejectionIsTypedAndDoesNotHideOtherKindPending() async throws {+ let (fixture, ids) = try await fixture()+ let marker = try await registration(fixture, ids, kind: .place)+ _ = try await fixture.repository.recordPendingMentionReviews([marker])+ try await suppress(fixture, ids, key: "cora")+ let current = try await candidate(fixture, ids)+ #expect(current.mentionIndex.pendingReviewReferences[ids.entry]?.map(\.key.kind) == [.place])+ _ = try await fixture.repository.advanceCoverage(workID: ids.work, sources: [try #require(current.sources.first).completedSource])+ #expect(try await candidate(fixture, ids).sources.first?.isCovered == false)+ withExtendedLifetime(fixture) {}+ }++ @Test("Any typed match keeps targetless obligations, including retained/alias/ambiguous/torn endpoints", arguments: [0, 1, 2, 3, 4])+ func candidateRejectionNeverBansAnExistingMatch(mode: Int) async throws {+ let (fixture, ids) = try await fixture()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "changing typed recognition directory") { context in+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first)+ let record = try #require(try context.fetch(FetchDescriptor<CharacterRecord>()).first)+ if mode == 1 { record.name = "Adaline" }+ if mode == 2 { record.name = "Adaline"; record.nameKey = "adaline"; record.aliases = ["Ada"] }+ if mode == 3 { context.insert(CharacterRecord(name: "Ada", nameKey: "ada", work: work)) }+ if mode == 4 {+ let other = Work(displayTitle: "Other synthetic Work", timestamp: M5Fixture.epoch); context.insert(other)+ context.insert(CharacterRecord(id: ids.known, name: "Ada", nameKey: "ada", work: other))+ }+ try context.save()+ }+ let marker = try await registration(fixture, ids, kind: .character, key: "ada")+ _ = try await fixture.repository.recordPendingMentionReviews([marker])+ try await suppress(fixture, ids, key: "ada")+ let current = try await candidate(fixture, ids)+ #expect(current.mentionIndex.pendingReviewReferences[ids.entry]?.map(\.key.nameKey) == ["ada"])+ _ = try await fixture.repository.advanceCoverage(workID: ids.work, sources: [try #require(current.sources.first).completedSource])+ #expect(try await candidate(fixture, ids).sources.first?.isCovered == false)+ withExtendedLifetime(fixture) {}+ }++ @Test func missingOriginalTargetCannotBecomeRejectedNewCandidate() async throws {+ let (fixture, ids) = try await fixture()+ let marker = try await registration(fixture, ids, kind: .character, key: "ada", target: ids.known)+ _ = try await fixture.repository.recordPendingMentionReviews([marker])+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "simulating missing original identity") { context in+ for row in try context.fetch(FetchDescriptor<CharacterRecord>()) { context.delete(row) }+ try context.save()+ }+ try await suppress(fixture, ids, key: "ada")+ let current = try await candidate(fixture, ids)+ #expect(current.mentionIndex.pendingReviewReferences[ids.entry]?.map(\.key.nameKey) == ["ada"])+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationPublicationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationPublicationTests.swiftnew file mode 100644index 00000000..6035e843--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationPublicationTests.swift@@ -0,0 +1,66 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Chapter association value publication", .serialized)+struct AssociationPublicationTests {+ private func fixture() async throws -> (M5Fixture, [AssociationPair]) {+ let fixture = try await M5Fixture()+ let work = UUID(), entry = UUID(), character = UUID(), place = UUID()+ try await fixture.repository.seedM5Rows(sites: [.init(hostname: "publication.test")],+ works: [.init(id: work, displayTitle: "Publication book", hostname: "publication.test")],+ entries: [.init(id: entry, captureTitle: "Chapter", hostname: "publication.test", path: "one",+ note: "Alice visits Harbor.", workID: work)],+ characters: [.init(id: character, name: "Alice", workID: work)],+ places: [.init(id: place, name: "Harbor", workID: work)])+ let pairs = [AssociationPair(workID: work, entryID: entry, kind: .character, recordID: character),+ AssociationPair(workID: work, entryID: entry, kind: .place, recordID: place)]+ for pair in pairs {+ let name = pair.kind == .character ? "Alice" : "Harbor"+ _ = try await fixture.repository.commitDecision(.init(workID: work, kind: pair.kind, action: .accept,+ displayedKeys: [RecordNameKey.normalize(name)], displayedTargetID: pair.recordID, proposedName: name,+ mentions: [.init(entryID: entry, noteFingerprint: CharacterCoverageFingerprint.of("Alice visits Harbor."),+ spellingKeys: [RecordNameKey.normalize(name)])]))+ }+ return (fixture, pairs)+ }+ @Test func entryDetailPublishesBothKindsAndExactLinkNotesSeparatelyFromFactCitations() async throws {+ let (fixture, pairs) = try await fixture()+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pairs[0]))+ let text = "Cafe\u{301} private link observation"+ #expect(try await fixture.repository.saveAssociationNote(basis: basis, text: text) == .committed)+ let detail = try await fixture.repository.entryTeachingDetail(id: pairs[0].entryID)+ #expect(Set(detail.chapterAssociations.map(\.pair)) == Set(pairs))+ #expect(detail.chapterAssociations.allSatisfy { !$0.activeAcceptanceIDs.isEmpty })+ #expect(detail.citingCharacters.isEmpty && detail.citingPlaces.isEmpty)+ let character = try #require(detail.chapterAssociations.first { $0.pair.kind == .character })+ #expect(character.activeAcceptanceIDs == basis.acceptanceIDs)+ #expect(character.noteHeads.map { Data($0.text.utf8) } == [Data(text.utf8)])+ #expect(detail.entry.note == "Alice visits Harbor.")+ let extraction = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [pairs[0].workID]).first)+ #expect(extraction.sources.allSatisfy { !$0.text.contains("private link observation") })+ withExtendedLifetime(fixture) {}+ }+ @Test func metadataOnlyContradictionChangesPublishedLinkWithoutChangingChapterOrFacts() async throws {+ let (fixture, pairs) = try await fixture()+ let pair = pairs[0]+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ _ = try await fixture.repository.saveAssociationNote(basis: basis, text: "Preserved exact text")+ let before = try await fixture.repository.entryTeachingDetail(id: pair.entryID)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "arriving contradictory association metadata only") { context in+ let id = try #require(basis.acceptanceIDs.first)+ let conflict = AssociationLedgerEvent(id: id, payload: .accept(.init(pair: pair, spellingKeys: ["other"])))+ context.insert(try AssociationEvent(event: conflict, recordedAt: M5Fixture.epoch)); try context.save()+ }+ let after = try await fixture.repository.entryTeachingDetail(id: pair.entryID)+ #expect(after.entry == before.entry)+ #expect(after.citingCharacters == before.citingCharacters && after.citingPlaces == before.citingPlaces)+ #expect(!after.chapterAssociations.contains { $0.pair == pair && !$0.activeAcceptanceIDs.isEmpty })+ #expect(try await fixture.repository.detachedAssociationNotes().contains {+ $0.raw.text == "Preserved exact text" && !$0.canRecover+ })+ #expect(after.chapterAssociations.contains { $0.pair == pairs[1] && !$0.activeAcceptanceIDs.isEmpty })+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationRankingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationRankingTests.swiftnew file mode 100644index 00000000..366bf4cb--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationRankingTests.swift@@ -0,0 +1,308 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Saved chapter support ranking", .serialized)+struct AssociationRankingTests {+ private struct IDs: Sendable {+ let work = UUID(), outside = UUID()+ let ada = UUID(), bryn = UUID(), zulu = UUID(), empty = UUID()+ let entries = [UUID(), UUID(), UUID()]+ var records: [(UUID, String)] { [(ada, "Ada"), (bryn, "Bryn"), (zulu, "Zulu"), (empty, "Empty")] }+ }+ private func fixture(links: [String: [Int]], numbered: Bool = true) async throws -> (M5Fixture, IDs) {+ let fixture = try await M5Fixture(), ids = IDs()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding saved support ranking") { context in+ let work = Work(id: ids.work, displayTitle: "Ranked Work", timestamp: M5Fixture.epoch)+ let outside = Work(id: ids.outside, displayTitle: "Other Work", timestamp: M5Fixture.epoch)+ context.insert(work); context.insert(outside)+ var records: [String: CharacterRecord] = [:]+ for (id, name) in ids.records {+ let row = CharacterRecord(id: id, name: name, nameKey: name.lowercased(), work: work)+ context.insert(row); records[name] = row+ }+ let empty = AssociationLedgerInventory(events: [])+ for index in 0..<3 {+ let entry = Entry(id: ids.entries[index], captureTitle: numbered ? "Chapter \(index * 5 + 1)" : "Unnumbered note \(index)",+ captureTitleSource: .manual, rawURLString: "", hostname: "", entryIdentityKey: "",+ timestamp: M5Fixture.epoch.addingTimeInterval(Double(index)), note: "Ada, Bryn and Zulu. Zulu again.")+ try entry.authorTarget(.init(kind: .chapter, title: numbered ? entry.captureTitle : nil)); context.insert(entry); entry.work = work+ LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch)+ for (name, positions) in links where positions.contains(index) {+ let record = records[name]!+ let pair = AssociationPair(workID: ids.work, entryID: entry.id, kind: .character, recordID: record.id)+ let current = AssociationCurrentPair(pair: pair, sourceFingerprint: AssociationEndpointInventory.sourceFingerprint(entry),+ matchingFingerprint: AssociationEndpointInventory.targetFingerprint(record),+ evidence: RecordMentionGrounding.evidence(names: [name], in: entry.note))+ let event = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: [name.lowercased()])), validation: empty.receipt(for: current))+ context.insert(try AssociationEvent(event: event, recordedAt: M5Fixture.epoch))+ }+ }+ // A separately scoped acceptance must not turn this Work's Empty+ // character into a supported character, even under a forged address.+ let outsidePair = AssociationPair(workID: ids.outside, entryID: ids.entries[2], kind: .character, recordID: ids.empty)+ context.insert(try AssociationEvent(event: .init(payload: .accept(.init(pair: outsidePair, spellingKeys: ["empty"]))), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ return (fixture, ids)+ }+ private func names(_ fixture: M5Fixture, _ ids: IDs) async throws -> [String] {+ try await fixture.repository.workDetail(id: ids.work).characters.map(\.name)+ }+ private func pair(_ ids: IDs, record: UUID, entry: Int = 2) -> AssociationPair {+ .init(workID: ids.work, entryID: ids.entries[entry], kind: .character, recordID: record)+ }++ private struct PhysicalRecordValue: Encodable {+ let kind: RecordKind+ let id: UUID+ let name: String+ let retainedKey: String+ let aliases: [String]+ let note: String+ let factsData: Data?+ let owner: UUID?+ let createdBits: UInt64+ let modifiedBits: UInt64+ }+ private struct PhysicalHistoryState: Equatable, Sendable {+ let records: [Data]+ let events: [Data]+ let notes: [Data]+ }+ /// Divergent physical record copies are intentionally not exportable.+ /// Keep every raw value and duplicate rather than weakening that policy.+ private func physicalHistoryState(_ repository: LibraryRepository) async throws -> PhysicalHistoryState {+ try await repository.withLockedContext(mode: .shared, operation: "reading exact ranking fixture rows") { context in+ let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]+ func rows<Row: RecordRow>(_ type: Row.Type) throws -> [Data] {+ try context.fetch(FetchDescriptor<Row>()).map { row in+ try encoder.encode(PhysicalRecordValue(kind: Row.kind, id: row.recordID, name: row.name,+ retainedKey: row.nameKey, aliases: row.aliases, note: row.note, factsData: row.factsData,+ owner: row.ownerWorkID, createdBits: row.createdAt.timeIntervalSinceReferenceDate.bitPattern,+ modifiedBits: row.modifiedAt.timeIntervalSinceReferenceDate.bitPattern))+ }+ }+ let records = try rows(CharacterRecord.self) + rows(Place.self)+ let events = try context.fetch(FetchDescriptor<AssociationEvent>()).map { try encoder.encode(AssociationRawEvent($0)) }+ let notes = try context.fetch(FetchDescriptor<PairNoteVersion>()).map { try encoder.encode(AssociationRawNote($0)) }+ return .init(records: records.sorted { $0.lexicographicallyPrecedes($1) },+ events: events.sorted { $0.lexicographicallyPrecedes($1) }, notes: notes.sorted { $0.lexicographicallyPrecedes($1) })+ }+ }++ @Test func zeroFactCastUsesSavedRecencyAndBreadthOnEveryRankingSurface() async throws {+ let (fixture, ids) = try await fixture(links: ["Ada": [0], "Bryn": [0, 1, 2], "Zulu": [2]])+ let before = try await fixture.repository.backupV20Snapshot()+ let expected = ["Bryn", "Zulu", "Ada", "Empty"]+ #expect(try await names(fixture, ids) == expected)+ let share = try await fixture.repository.shareWorkContext(workID: ids.work, excludingEntryID: ids.entries[2], currentChapterSequence: nil, currentChapterTitle: nil)+ #expect(share.characters.map(\.name) == expected)+ let copy = try await fixture.repository.recordCopyContext(sourceWorkID: ids.work)+ #expect(copy.records.filter { $0.kind == .character }.map(\.name) == expected)+ #expect(try await fixture.repository.backupV20Snapshot() == before, "Ranking is a read; it must not mint facts, acceptance or coverage")+ withExtendedLifetime(fixture) {}+ }++ @Test func emptyCastKeepsPlacesAndSourceHistoryAcrossEveryRankingSurface() async throws {+ let (fixture, ids) = try await fixture(links: [:])+ let placeIDs = (0..<64).map { _ in UUID() }+ let expectedNames = (0..<64).map { String(format: "Place %02d", $0) }+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding place-only ranking history") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ let outside = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.outside })+ for row in try CharacterRecord.rows(of: [work], context: context) { context.delete(row) }+ context.insert(CharacterRecord(name: "Outside character", nameKey: "outside character", work: outside))+ work.genericNotes = "Exact place-only Work note."+ for (index, id) in placeIDs.enumerated() {+ context.insert(Place(id: id, name: expectedNames[index], nameKey: expectedNames[index].lowercased(), workID: ids.work))+ let pair = AssociationPair(workID: ids.work, entryID: ids.entries[index % ids.entries.count], kind: .place, recordID: id)+ context.insert(try AssociationEvent(event: .init(payload: .accept(.init(pair: pair,+ spellingKeys: [expectedNames[index].lowercased()]))), recordedAt: M5Fixture.epoch))+ context.insert(try AssociationEvent(event: .init(payload: .invalidate(.record(workID: ids.work,+ kind: .place, recordID: id))), recordedAt: M5Fixture.epoch))+ context.insert(try AssociationEvent(event: .init(payload: .pendingReview(.init(workID: ids.work,+ entryID: pair.entryID, sourceGuard: "historical source guard", items: [+ .init(key: .init(kind: .place, nameKey: expectedNames[index].lowercased()),+ targetID: id, spellingKeys: [expectedNames[index].lowercased()])]))), recordedAt: M5Fixture.epoch))+ }+ let conflict = UUID()+ for owner in [ids.work, ids.outside] {+ context.insert(try AssociationEvent(event: .init(id: conflict,+ payload: .invalidate(.work(owner))), recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ let before = try await fixture.repository.backupV20Snapshot()+ let detail = try await fixture.repository.workDetail(id: ids.work)+ #expect(detail.characters.isEmpty)+ #expect(detail.places.map(\.id) == placeIDs && detail.places.map(\.name) == expectedNames)+ let share = try await fixture.repository.shareWorkContext(workID: ids.work, currentChapterSequence: nil, currentChapterTitle: nil)+ #expect(share.characters.isEmpty && share.workNote == "Exact place-only Work note.")+ #expect(share.lastNote == nil, "Without a chapter anchor, only the Work note is offered")+ let anchor = try await fixture.repository.entry(id: ids.entries[2])+ let preceding = try await fixture.repository.entry(id: ids.entries[1])+ let anchorTitle = try #require(anchor.authoredTarget?.title)+ let precedingTitle = try #require(preceding.authoredTarget?.title)+ let anchored = try await fixture.repository.shareWorkContext(workID: ids.work,+ currentChapterSequence: anchor.chapterSequence, currentChapterTitle: anchorTitle)+ #expect(anchored.characters.isEmpty && anchored.workNote == share.workNote)+ #expect(anchored.lastNote?.title == precedingTitle && anchored.lastNote?.note == preceding.note)+ #expect(anchored.lastNote?.lastSharedAt == preceding.lastSharedAt)+ let copy = try await fixture.repository.recordCopyContext(sourceWorkID: ids.work)+ #expect(copy.records.allSatisfy { $0.kind == .place && $0.unavailableReason == nil })+ #expect(copy.records.map(\.id) == placeIDs && copy.records.map(\.name) == expectedNames)+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: [false, true])+ func offWorkCharacterCopyCannotConferSavedSupportOnAnyRankingSurface(conflictingName: Bool) async throws {+ let (fixture, ids) = try await fixture(links: ["Bryn": [0], "Zulu": [2]])+ #expect(try await names(fixture, ids).first == "Zulu")+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding off-Work character copy") { context in+ let outside = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.outside })+ context.insert(CharacterRecord(id: ids.zulu, name: conflictingName ? "Other name" : "Zulu", nameKey: "zulu", work: outside))+ try context.save()+ }+ let before = try await physicalHistoryState(fixture.repository)+ let detail = try await fixture.repository.workDetail(id: ids.work)+ #expect(detail.characters.first?.id == ids.bryn)+ let share = try await fixture.repository.shareWorkContext(workID: ids.work, currentChapterSequence: nil, currentChapterTitle: nil)+ #expect(share.characters.first?.id == ids.bryn)+ let copy = try await fixture.repository.recordCopyContext(sourceWorkID: ids.work)+ #expect(copy.records.first { $0.kind == .character }?.id == ids.bryn)+ #expect(copy.records.first { $0.kind == .character && $0.id == ids.zulu }?.unavailableReason != nil)+ let links = try await fixture.repository.chapterAssociations(entryID: ids.entries[0])+ #expect(links.contains { $0.pair.recordID == ids.bryn && !$0.activeAcceptanceIDs.isEmpty })+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entries[2])+ .filter { $0.pair.recordID == ids.zulu }.allSatisfy { $0.activeAcceptanceIDs.isEmpty })+ #expect(try await physicalHistoryState(fixture.repository) == before)+ withExtendedLifetime(fixture) {}+ }++ @Test func LiteralTextWithoutAcceptanceAndDuplicateReceiptsDoNotAddSupport() async throws {+ let (fixture, ids) = try await fixture(links: ["Ada": [2], "Zulu": [2]])+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "duplicating a saved support receipt") { context in+ let events = try context.fetch(FetchDescriptor<AssociationEvent>())+ let row = try #require(events.first { $0.recordID == ids.zulu })+ let raw = try #require(AssociationRawEvent(row).value)+ context.insert(try AssociationEvent(event: .init(payload: raw.payload, validation: raw.validation), recordedAt: M5Fixture.epoch))+ try context.save()+ }+ #expect(try await names(fixture, ids) == ["Ada", "Zulu", "Bryn", "Empty"])+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["removedMention", "rejected", "retired"])+ func inactiveSavedLinkLosesOnlyItsLinkContribution(change: String) async throws {+ let (fixture, ids) = try await fixture(links: ["Ada": [1], "Zulu": [2]])+ #expect(try await names(fixture, ids).first == "Zulu")+ let pair = pair(ids, record: ids.zulu)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "removing saved ranking support") { context in+ if change == "removedMention" {+ let entry = try #require(context.fetch(FetchDescriptor<Entry>()).first { $0.id == pair.entryID })+ entry.note = "Ada and Bryn only."+ } else {+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [ids.work], includeNotes: false)+ let event: AssociationLedgerEvent+ if change == "rejected" { event = .init(payload: .reject(.init(pair: pair, spellingKeys: ["zulu"]))) }+ else {+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: [pair])+ let current = try #require(endpoints.current(pair))+ event = .init(payload: .retire(.init(pair: pair, acceptanceIDs: Array(storage.ledger.activeAcceptanceIDs(for: current)))))+ }+ context.insert(try AssociationEvent(event: event, recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ #expect(try await names(fixture, ids).first == "Ada")+ withExtendedLifetime(fixture) {}+ }++ @Test func unnumberedLinklessChaptersUseFirstCaptureAndReshareDoesNotReviveOldSupport() async throws {+ let (fixture, ids) = try await fixture(links: ["Ada": [0], "Zulu": [2]], numbered: false)+ #expect(try await names(fixture, ids).prefix(2) == ["Zulu", "Ada"])+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "resharing old linkless chapter") { context in+ let entry = try #require(context.fetch(FetchDescriptor<Entry>()).first { $0.id == ids.entries[0] })+ entry.lastSharedAt = M5Fixture.epoch.addingTimeInterval(1000); try context.save()+ }+ #expect(try await names(fixture, ids).prefix(2) == ["Zulu", "Ada"])+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["tornSource", "tornTarget", "moved", "standalone"])+ func incoherentOrIneligibleEndpointsCannotConferLinkSupport(change: String) async throws {+ let (fixture, ids) = try await fixture(links: ["Ada": [1], "Zulu": [2]])+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "changing ranking endpoint") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ let entry = try #require(context.fetch(FetchDescriptor<Entry>()).first { $0.id == ids.entries[2] })+ switch change {+ case "tornTarget": context.insert(CharacterRecord(id: ids.zulu, name: "Zulu", nameKey: "zulu", aliases: ["Zed"], work: work))+ case "tornSource":+ let conflict = Entry(id: entry.id, captureTitle: entry.captureTitle, captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Zulu changed.")+ context.insert(conflict); conflict.work = work+ case "moved":+ let destination = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.outside })+ entry.work = destination+ default: try entry.authorTarget(.init(kind: .note))+ }+ try context.save()+ }+ #expect(try await names(fixture, ids).first == "Ada")+ withExtendedLifetime(fixture) {}+ }++ @Test func legacyFactsRemainHistoricalEvidenceAndPlaceRankingStaysUnchanged() async throws {+ let (fixture, ids) = try await fixture(links: ["Zulu": [2]])+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "adding historical facts and place controls") { context in+ _ = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ let ada = try #require(CharacterRecord.rows(ids: [ids.ada], context: context).first)+ ada.facts = [RecordFact(statement: "Historical generic evidence", quote: "Stored old quotation", nameKey: "ada", source: .genericNotes),+ RecordFact(statement: "Historical dangling evidence", quote: "Stored old quotation", nameKey: "ada", source: .entry(UUID()))]+ let first = Place(name: "Alpha", nameKey: "alpha", workID: ids.work)+ let other = Place(name: "Zulu place", nameKey: "zulu place", facts: [RecordFact(statement: "Saved place evidence", quote: "Stored place", nameKey: "zulu place", source: .genericNotes)], workID: ids.work)+ context.insert(first); context.insert(other); try context.save()+ }+ let result = try await fixture.repository.workDetail(id: ids.work)+ #expect(result.characters.map(\.name).prefix(2) == ["Ada", "Zulu"])+ #expect(result.places.map(\.name) == ["Zulu place", "Alpha"])+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["contradictoryBody", "malformedOffWorkCopy"])+ func badAcceptanceCopiesQuarantineOnlyTheirOwnCharacterSupport(change: String) async throws {+ let (fixture, ids) = try await fixture(links: ["Bryn": [0], "Zulu": [2]])+ #expect(try await names(fixture, ids).first == "Zulu")+ let affectedPair = pair(ids, record: ids.zulu)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "arriving corrupt acceptance copy") { context in+ let rows = try context.fetch(FetchDescriptor<AssociationEvent>())+ let original = try #require(rows.first { $0.workID == ids.work && $0.recordID == ids.zulu })+ let value = try #require(AssociationRawEvent(original).value)+ let bad: AssociationEvent+ if change == "contradictoryBody" {+ // Coherent indexed identity, different acceptance body at the+ // same application event UUID: neither twin is trustworthy.+ bad = try AssociationEvent(event: .init(id: value.id,+ payload: .accept(.init(pair: affectedPair, spellingKeys: ["bryn"]))), recordedAt: M5Fixture.epoch)+ } else {+ bad = try AssociationEvent(event: value, recordedAt: M5Fixture.epoch)+ bad.workID = ids.outside+ bad.eventData = Data([0xff, 0x00])+ }+ context.insert(bad); try context.save()+ }+ let expected = ["Bryn", "Ada", "Empty", "Zulu"]+ #expect(try await names(fixture, ids) == expected)+ let share = try await fixture.repository.shareWorkContext(workID: ids.work,+ currentChapterSequence: nil, currentChapterTitle: nil)+ #expect(share.characters.map(\.name) == expected)+ let copy = try await fixture.repository.recordCopyContext(sourceWorkID: ids.work)+ #expect(copy.records.filter { $0.kind == .character }.map(\.name) == expected)+ let associations = try await fixture.repository.chapterAssociations(entryID: ids.entries[0])+ #expect(associations.contains { $0.pair.recordID == ids.bryn && !$0.activeAcceptanceIDs.isEmpty })+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationRankingValueTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationRankingValueTests.swiftnew file mode 100644index 00000000..6029a56f--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationRankingValueTests.swift@@ -0,0 +1,53 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite("Saved chapter support ranking values")+struct AssociationRankingValueTests {+ private func group(_ name: String, id: UUID = UUID(), facts: [RecordFact] = []) -> CharacterGroup {+ LibraryRepository.recordGroup(id: id, rows: [CharacterRecord(id: id, name: name, nameKey: name.lowercased(), facts: facts)])!+ }+ private func fact(_ entry: UUID, _ quote: String) -> RecordFact {+ .init(statement: quote, quote: quote, nameKey: "ada", source: .entry(entry))+ }+ @Test func linkIsAnEntryFloorAndNeverAddsToExistingFactDensity() {+ let old = UUID(), recent = UUID()+ let index = StoryPositionIndex(entries: [+ .init(id: old, placement: nil, firstCapturedAt: .distantPast),+ .init(id: recent, placement: nil, firstCapturedAt: .distantFuture)])+ let facts = [fact(recent, "one"), fact(recent, "two")]+ let baseline = RecordRanking.score(facts: facts, index: index)+ #expect(RecordRanking.score(facts: facts, index: index, chapterEntryIDs: [recent]) == baseline)+ #expect(RecordRanking.score(facts: facts, index: index, chapterEntryIDs: [old, recent]) == baseline + RecordRanking.weight(distance: 1))+ #expect(RecordRanking.score(facts: [], index: index, chapterEntryIDs: [UUID()]) == 0)+ }+ @Test func linksAtEqualStoryPlacementShareOneConcaveBucket() {+ let first = UUID(), second = UUID()+ let placement = ChapterPlacement.of(chapterSequence: "7", chapterTitle: nil)+ let index = StoryPositionIndex(entries: [+ .init(id: first, placement: placement, firstCapturedAt: .distantPast),+ .init(id: second, placement: placement, firstCapturedAt: .distantFuture)])+ #expect(RecordRanking.score(facts: [], index: index, chapterEntryIDs: [first, second]) == RecordRanking.perBucket(2))+ // One fact and its link are one Entry's evidence, not two units.+ #expect(RecordRanking.score(facts: [fact(first, "one")], index: index, chapterEntryIDs: [first, second]) == RecordRanking.perBucket(2))+ }+ @Test func savedSupportOrderIsDeterministicAcrossPermutationsAndBothRankingEntryPoints() {+ let old = UUID(), recent = UUID()+ let entries: [StoryPositionIndex.EntryInput] = [+ .init(id: old, placement: nil, firstCapturedAt: .distantPast),+ .init(id: recent, placement: nil, firstCapturedAt: .distantFuture)]+ let first = group("Equal", id: UUID(uuidString: "00000000-0000-4000-8000-000000000001")!)+ let second = group("Equal", id: UUID(uuidString: "00000000-0000-4000-8000-000000000002")!)+ let third = group("Zulu"), empty = group("Ada")+ let support = [first.id: Set([recent]), second.id: Set([recent]), third.id: Set([old])]+ let groups = [first, second, third, empty], expected = groups.map(\.id)+ for permutation in [groups, Array(groups.reversed()), [third, first, empty, second]] {+ for inputs in [entries, Array(entries.reversed())] {+ let index = StoryPositionIndex(entries: inputs)+ let keyed = Dictionary(uniqueKeysWithValues: permutation.map { ($0.id, $0) })+ #expect(RecordRanking.rank(keyed, index: index, chapterSupport: support).map(\.group.id) == expected)+ #expect(RecordRanking.rankGroups(keyed, index: index, chapterSupport: support).map(\.id) == expected)+ }+ }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationResolutionTests.swiftnew file mode 100644index 00000000..775b0b47--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationResolutionTests.swift@@ -0,0 +1,391 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Association explicit duplicate resolution", .serialized)+struct AssociationResolutionTests {+ private struct Seed {+ let fixture: M5Fixture+ let work: UUID+ let destinationWork: UUID+ let source: UUID+ let destination: UUID+ let character: UUID+ let place: UUID+ let roots: [AssociationPair: UUID]+ }+ private let exactText = " Cafe\u{301} exact annotation\n🌟 "+ private func seed(mode: String = "entry", kind: RecordKind = .character,+ save: any RepositorySaveStrategy = ModelContextSaveStrategy()) async throws -> Seed {+ let fixture = try await M5Fixture(saveStrategy: save)+ let workID = UUID(), targetWorkID = mode == "work" ? UUID() : workID+ let sourceID = UUID(), destinationID = UUID(), characterID = UUID(), placeID = UUID()+ let roots = try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding explicit resolution associations") { context in+ let site = Site(hostname: "resolution.test"); context.insert(site)+ func work(_ id: UUID, offset: Double, notes: String) -> Work {+ let value = Work.create(in: context, id: id, title: "Resolution book", hostname: site.hostname,+ site: site, timestamp: M5Fixture.epoch.addingTimeInterval(offset))+ value.lastParsedTitle = "Resolution book"; value.titleProvenance = .parsed; value.genericNotes = notes+ return value+ }+ let destinationWork = work(targetWorkID, offset: 0, notes: "Survivor notes")+ let sourceWork = mode == "work" ? work(workID, offset: 40, notes: "Other notes") : destinationWork+ func entry(_ id: UUID, offset: Double, note: String) throws -> Entry {+ let value = Entry(id: id, captureTitle: "Chapter", captureTitleSource: .manual,+ rawURLString: "https://resolution.test/chapter", hostname: site.hostname,+ entryIdentityKey: "https://resolution.test/chapter", timestamp: M5Fixture.epoch.addingTimeInterval(offset), note: note)+ value.conservativeIdentityKey = value.rawURLString+ if mode != "entry" { try value.authorTarget(.init(kind: .chapter)) }+ context.insert(value); value.work = sourceWork; value.site = site+ LibraryRepository.applyManualAssignment(to: value, at: M5Fixture.epoch)+ return value+ }+ _ = try entry(sourceID, offset: 60, note: "Ada visits Harbor.")+ if mode == "entry" { _ = try entry(destinationID, offset: 0, note: "Harbor.") }+ context.insert(CharacterRecord(id: characterID, name: "Ada", nameKey: "ada", work: sourceWork))+ context.insert(Place(id: placeID, name: "Harbor", nameKey: "harbor", workID: sourceWork.id))+ if mode == "work" {+ context.insert(CharacterSuppression(work: sourceWork, nameKey: "blocked"))+ context.insert(PlaceSuppression(workID: sourceWork.id, nameKey: "blocked"))+ }+ let kinds: [RecordKind] = mode == "work" ? [.character, .place] : [kind]+ let pairs = kinds.map { AssociationPair(workID: sourceWork.id, entryID: sourceID, kind: $0,+ recordID: $0 == .character ? characterID : placeID) }+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: Set(pairs))+ var result: [AssociationPair: UUID] = [:]+ for pair in pairs {+ let current = try #require(endpoints.current(pair))+ var event = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: current.evidence.map(\.key))))+ event.validation = AssociationLedgerInventory(events: [event]).receipt(for: current)+ context.insert(try AssociationEvent(event: event, recordedAt: M5Fixture.epoch))+ context.insert(try PairNoteVersion(note: .init(pair: pair, attachmentAcceptanceIDs: [event.id],+ text: exactText, originalContext: "Original exact chapter")))+ result[pair] = event.id+ }+ try context.save(); return result+ }+ return .init(fixture: fixture, work: workID, destinationWork: targetWorkID, source: sourceID,+ destination: destinationID, character: characterID, place: placeID, roots: roots)+ }+ private func contract(_ seed: Seed, type: DuplicateRecordType) async throws -> DuplicateResolutionContract {+ let key = try await seed.fixture.repository.withLockedContext(mode: .shared, operation: "reading explicit duplicate set") { context in+ let scan = try DuplicateScan.run(context: context)+ switch type {+ case .entry: return try #require(scan.entrySets.first { $0.classification == .divergent }?.key)+ case .work: return try #require(scan.workSets.first { $0.classification == .divergent }?.key)+ case .character: return try #require(scan.characterSets.first { $0.classification == .divergent }?.key)+ case .place: return try #require(scan.placeSets.first { $0.classification == .divergent }?.key)+ case .titleRule, .urlRule: throw CocoaError(.fileReadUnknown)+ }+ }+ return try await seed.fixture.repository.projectDuplicateResolution(setKey: key)+ }+ private func choose(_ contract: DuplicateResolutionContract, text: String) throws -> VariantID {+ switch contract {+ case .entry(_, let variants, _, _): return try #require(variants.first { $0.note == text }?.id)+ case .work(_, let variants, _, _): return try #require(variants.first { $0.genericNotes == text }?.id)+ case .character(_, let variants, _, _), .place(_, let variants, _, _):+ return try #require(variants.first { $0.name == text }?.id)+ }+ }+ private func active(_ seed: Seed, entry: UUID) async throws -> [ChapterAssociationSnapshot] {+ try await seed.fixture.repository.chapterAssociations(entryID: entry).filter { !$0.activeAcceptanceIDs.isEmpty }+ }+ @Test(arguments: [RecordKind.character, .place])+ func supportedEntryResolutionRebindsExactHeads(kind: RecordKind) async throws {+ let value = try await seed(kind: kind)+ let projected = try await contract(value, type: .entry)+ #expect(try await value.fixture.repository.commitDuplicateResolution(projected,+ choosing: choose(projected, text: "Ada visits Harbor.")) == .committed(survivorID: value.destination))+ let moved = try #require(try await active(value, entry: value.destination).first { $0.pair.kind == kind })+ #expect(moved.activeAcceptanceIDs.isDisjoint(with: Set(value.roots.values)))+ #expect(moved.noteHeads.first.map { ExactScalarString($0.text) } == ExactScalarString(exactText))+ #expect(moved.noteHeads.first?.originalContext == "Original exact chapter")+ #expect(try await active(value, entry: value.source).isEmpty)+ withExtendedLifetime(value.fixture) {}+ }+ @Test(arguments: [RecordKind.character, .place], ["noMention", "otherWork"])+ func unsupportedEntryDestinationKeepsDetachedLineage(kind: RecordKind, destinationMode: String) async throws {+ let value = try await seed(kind: kind)+ let destinationID = value.destination, characterID = value.character, placeID = value.place+ try await value.fixture.repository.withLockedContext(mode: .exclusive, operation: "choosing unsupported chapter content") { context in+ let destination = try #require(context.fetch(FetchDescriptor<Entry>()).first { $0.id == destinationID })+ destination.note = "No known names."+ if destinationMode == "otherWork" {+ let other = Work(displayTitle: "Independent Work", timestamp: M5Fixture.epoch)+ context.insert(other); destination.work = other+ LibraryRepository.applyManualAssignment(to: destination, at: M5Fixture.epoch)+ }+ try context.save()+ }+ let projected = try await contract(value, type: .entry)+ _ = try await value.fixture.repository.commitDuplicateResolution(projected, choosing: choose(projected, text: "No known names."))+ #expect(try await active(value, entry: value.destination).isEmpty)+ let detached = try await value.fixture.repository.detachedAssociationNotes()+ #expect(try await active(value, entry: value.source).isEmpty)+ let hasExactLineage = detached.contains { (note: DetachedAssociationNoteSnapshot) -> Bool in+ guard let pair = note.pair, let head = note.head, pair.kind == kind,+ ExactScalarString(note.raw.text) == ExactScalarString(exactText) else { return false }+ if destinationMode == "noMention" {+ return pair.entryID == value.destination && !head.parentHeadIDs.isEmpty+ }+ return pair.entryID == value.source+ }+ #expect(hasExactLineage)+ if destinationMode == "otherWork" {+ let owner = try await value.fixture.repository.withLockedContext(mode: .shared, operation: "checking no invented record ownership") { context in+ (try CharacterRecord.rows(ids: [characterID], context: context).map(\.ownerWorkID),+ try Place.rows(ids: [placeID], context: context).map(\.ownerWorkID))+ }+ #expect(owner.0 == [value.work] && owner.1 == [value.work])+ }+ withExtendedLifetime(value.fixture) {}+ }+ @Test func workResolutionTransfersBothTypedOwnersAndSuppression() async throws {+ let value = try await seed(mode: "work")+ let characterID = value.character, placeID = value.place+ let projected = try await contract(value, type: .work)+ #expect(try await value.fixture.repository.commitDuplicateResolution(projected,+ choosing: projected.preselected) == .committed(survivorID: value.destinationWork))+ let links = try await active(value, entry: value.source)+ #expect(Set(links.map { $0.pair.kind }) == [.character, .place])+ #expect(links.allSatisfy { $0.pair.workID == value.destinationWork+ && $0.noteHeads.first.map { ExactScalarString($0.text) } == ExactScalarString(exactText) })+ let ownership = try await value.fixture.repository.withLockedContext(mode: .shared, operation: "checking moved typed record owners") { context in+ (try CharacterRecord.rows(ids: [characterID], context: context).map(\.ownerWorkID),+ try Place.rows(ids: [placeID], context: context).map(\.ownerWorkID),+ try context.fetch(FetchDescriptor<CharacterSuppression>()).map { $0.work?.id },+ try context.fetch(FetchDescriptor<PlaceSuppression>()).map(\.workID))+ }+ #expect(ownership.0 == [value.destinationWork] && ownership.1 == [value.destinationWork])+ #expect(ownership.2 == [value.destinationWork] && ownership.3 == [value.destinationWork])+ withExtendedLifetime(value.fixture) {}+ }+ private func insertVariant(_ value: Seed, kind: RecordKind, name: String) async throws {+ let workID = value.work, characterID = value.character, placeID = value.place+ try await value.fixture.repository.withLockedContext(mode: .exclusive, operation: "arriving divergent record copy") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == workID })+ if kind == .character { context.insert(CharacterRecord(id: characterID, name: name, nameKey: "ada", work: work)) }+ else { context.insert(Place(id: placeID, name: name, nameKey: "harbor", workID: work.id)) }+ try context.save()+ }+ }+ @Test(arguments: [RecordKind.character, .place])+ func recordResolutionFencesOldReceiptAcrossNameRoundTrip(kind: RecordKind) async throws {+ let value = try await seed(mode: "record", kind: kind)+ try await insertVariant(value, kind: kind, name: "Briar")+ var projected = try await contract(value, type: kind == .character ? .character : .place)+ _ = try await value.fixture.repository.commitDuplicateResolution(projected, choosing: choose(projected, text: "Briar"))+ try await insertVariant(value, kind: kind, name: kind == .character ? "Ada" : "Harbor")+ projected = try await contract(value, type: kind == .character ? .character : .place)+ _ = try await value.fixture.repository.commitDuplicateResolution(projected,+ choosing: choose(projected, text: kind == .character ? "Ada" : "Harbor"))+ #expect(try await active(value, entry: value.source).isEmpty)+ let detached = try await value.fixture.repository.detachedAssociationNotes()+ #expect(detached.contains { ExactScalarString($0.raw.text) == ExactScalarString(exactText) })+ withExtendedLifetime(value.fixture) {}+ }+ private struct PhysicalRecordValue: Codable {+ let kind: RecordKind+ let id: UUID+ let name: String+ let retainedKey: String+ let aliases: [String]+ let note: String+ let factsData: Data?+ let owner: UUID?+ let createdBits: UInt64+ let modifiedBits: UInt64+ }+ private struct RawRollbackState: Equatable, Sendable {+ let records: [Data]+ let events: [Data]+ let notes: [Data]+ }+ /// Export correctly refuses divergent record copies. This synthetic oracle+ /// retains every physical value and its multiplicity instead of exporting.+ private func rawRollbackState(_ repository: LibraryRepository) async throws -> RawRollbackState {+ try await repository.withLockedContext(mode: .shared, operation: "reading exact synthetic rollback rows") { context in+ let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys]+ func rows<Row: RecordRow>(_ type: Row.Type) throws -> [Data] {+ try context.fetch(FetchDescriptor<Row>()).map { row in+ try encoder.encode(PhysicalRecordValue(kind: Row.kind, id: row.recordID, name: row.name,+ retainedKey: row.nameKey, aliases: row.aliases, note: row.note, factsData: row.factsData,+ owner: row.ownerWorkID, createdBits: row.createdAt.timeIntervalSinceReferenceDate.bitPattern,+ modifiedBits: row.modifiedAt.timeIntervalSinceReferenceDate.bitPattern))+ }+ }+ let records = try rows(CharacterRecord.self) + rows(Place.self)+ let events = try context.fetch(FetchDescriptor<AssociationEvent>()).map { try encoder.encode(AssociationRawEvent($0)) }+ let notes = try context.fetch(FetchDescriptor<PairNoteVersion>()).map { try encoder.encode(AssociationRawNote($0)) }+ return .init(records: records.sorted { $0.lexicographicallyPrecedes($1) },+ events: events.sorted { $0.lexicographicallyPrecedes($1) }, notes: notes.sorted { $0.lexicographicallyPrecedes($1) })+ }+ }+ @Test(arguments: ["entry", "work", "record"])+ func failedResolutionRollsBackAcrossDiskReopen(mode: String) async throws {+ let save = FailingSaveStrategy(), value = try await seed(mode: mode, save: save)+ if mode == "record" { try await insertVariant(value, kind: .character, name: "Briar") }+ let projected = try await contract(value, type: mode == "work" ? .work : mode == "record" ? .character : .entry)+ let before = mode == "record" ? nil : try await value.fixture.repository.backupV20Snapshot()+ let rawBefore = try await rawRollbackState(value.fixture.repository)+ save.fail = true+ await #expect(throws: LibraryRepositoryError.self) {+ _ = try await value.fixture.repository.commitDuplicateResolution(projected, choosing: projected.preselected)+ }+ save.fail = false+ #expect(try await rawRollbackState(value.fixture.repository) == rawBefore)+ if let before { #expect(try await value.fixture.repository.backupV20Snapshot() == before) }+ await value.fixture.repository.shutdown()+ let reopened = try await LibraryRepository.openForApp(.init(rootDirectory: value.fixture.directory)).repository+ #expect(try await rawRollbackState(reopened) == rawBefore)+ if let before { #expect(try await reopened.backupV20Snapshot() == before) }+ await reopened.shutdown()+ withExtendedLifetime(value.fixture) {}+ }+ @Test(arguments: [false, true])+ func entryResolutionLinksOnlyFinalChosenOrAppendedContent(appending: Bool) async throws {+ let value = try await seed()+ let projected = try await contract(value, type: .entry)+ _ = try await value.fixture.repository.commitDuplicateResolution(projected,+ choosing: choose(projected, text: appending ? "Ada visits Harbor." : "Harbor."), appendingOtherNotes: appending)+ let links = try await active(value, entry: value.destination)+ #expect(Set(links.map { $0.pair.kind }) == (appending ? [.character, .place] : [.place]))+ if !appending {+ let detached = try await value.fixture.repository.detachedAssociationNotes()+ let hasExactDestinationNote = detached.contains { (note: DetachedAssociationNoteSnapshot) -> Bool in+ guard let pair = note.pair, note.head != nil else { return false }+ return pair.entryID == value.destination && ExactScalarString(note.raw.text) == ExactScalarString(exactText)+ }+ #expect(hasExactDestinationNote)+ }+ withExtendedLifetime(value.fixture) {}+ }+ /// Seed the old literal receipt explicitly: fixture authority must not+ /// silently change if current endpoint read policy changes in production.+ private func insertLegacyLiteralRoot(_ value: Seed, kind: RecordKind, note: String,+ name: String? = nil, aliases: [String] = [],+ rejectedKeys: [String] = [], text: String) async throws -> UUID {+ let workID = value.work, entryID = value.source+ let recordID = kind == .character ? value.character : value.place+ return try await value.fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding exact legacy literal receipt") { context in+ if kind == .character {+ for row in try CharacterRecord.rows(ids: [recordID], context: context) {+ if let name { row.name = name; row.nameKey = RecordNameKey.normalize(name) }+ row.aliases = aliases+ }+ } else {+ for row in try Place.rows(ids: [recordID], context: context) {+ if let name { row.name = name; row.nameKey = RecordNameKey.normalize(name) }+ row.aliases = aliases+ }+ }+ let entry = try #require(context.fetch(FetchDescriptor<Entry>()).first { $0.id == entryID })+ entry.note = note+ let pair = AssociationPair(workID: workID, entryID: entryID, kind: kind, recordID: recordID)+ if !rejectedKeys.isEmpty {+ context.insert(try AssociationEvent(event: .init(payload: .reject(.init(pair: pair, spellingKeys: rejectedKeys))), recordedAt: M5Fixture.epoch))+ }+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: [pair])+ let source = try #require(endpoints.sources[entryID])+ let target = try #require(endpoints.targets[.init(kind: kind, id: recordID)])+ let evidence = RecordMentionGrounding.evidence(names: target.names, in: source.note)+ #expect(!evidence.isEmpty)+ let current = AssociationCurrentPair(pair: pair, sourceFingerprint: source.fingerprint,+ matchingFingerprint: target.fingerprint, evidence: evidence)+ var event = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: evidence.map(\.key))))+ let observed = try context.fetch(FetchDescriptor<AssociationEvent>()).compactMap(\.ledgerValue)+ event.validation = AssociationLedgerInventory(events: observed + [event]).receipt(for: current)+ context.insert(try AssociationEvent(event: event, recordedAt: M5Fixture.epoch))+ context.insert(try PairNoteVersion(note: .init(pair: pair, attachmentAcceptanceIDs: [event.id],+ text: text, originalContext: "Exact legacy context")))+ try context.save()+ return event.id+ }+ }++ @Test(arguments: [RecordKind.character, .place])+ func casedSubstringRebindKeepsDetachedChildWithoutCurrentReceipt(kind: RecordKind) async throws {+ let value = try await seed(kind: kind)+ let destinationID = value.destination+ try await value.fixture.repository.withLockedContext(mode: .exclusive, operation: "choosing cased substring-only destination") { context in+ let entry = try #require(context.fetch(FetchDescriptor<Entry>()).first { $0.id == destinationID })+ entry.note = "Adam visits Harbormaster."; try context.save()+ }+ let projected = try await contract(value, type: .entry)+ _ = try await value.fixture.repository.commitDuplicateResolution(projected,+ choosing: choose(projected, text: "Adam visits Harbormaster."))+ #expect(try await active(value, entry: value.destination).isEmpty)+ let detached = try await value.fixture.repository.detachedAssociationNotes()+ let hasExactChild = detached.contains { (note: DetachedAssociationNoteSnapshot) -> Bool in+ guard let pair = note.pair, let head = note.head else { return false }+ return pair.entryID == destinationID && pair.kind == kind && !head.parentHeadIDs.isEmpty+ && ExactScalarString(note.raw.text) == ExactScalarString(exactText)+ && head.originalContext == "Original exact chapter"+ }+ #expect(hasExactChild)+ withExtendedLifetime(value.fixture) {}+ }++ @Test(arguments: [RecordKind.character, .place])+ func uncasedParticleSupportSurvivesUntilActualNameLoss(kind: RecordKind) async throws {+ let value = try await seed(mode: "record", kind: kind)+ let text = " Uncased exact\n🌟 "+ let rootID = try await insertLegacyLiteralRoot(value, kind: kind, note: "太郎 and 太郎を見た。", name: "太郎", text: text)+ let before = try #require(try await active(value, entry: value.source).first { $0.pair.kind == kind })+ #expect(before.activeAcceptanceIDs == [rootID])+ var entry = try await value.fixture.repository.entry(id: value.source)+ _ = try await value.fixture.repository.updateEntry(id: value.source, basis: .init(entry: entry), note: "太郎を見た。", rating: nil)+ let after = try #require(try await active(value, entry: value.source).first { $0.pair.kind == kind })+ #expect(after.activeAcceptanceIDs == before.activeAcceptanceIDs)+ #expect(after.noteHeads == before.noteHeads)+ entry = try await value.fixture.repository.entry(id: value.source)+ _ = try await value.fixture.repository.updateEntry(id: value.source, basis: .init(entry: entry), note: "Nobody remains.", rating: nil)+ #expect(try await active(value, entry: value.source).isEmpty)+ let detached = try await value.fixture.repository.detachedAssociationNotes()+ #expect(detached.contains { ExactScalarString($0.raw.text) == ExactScalarString(text) })+ withExtendedLifetime(value.fixture) {}+ }++ @Test(arguments: [RecordKind.character, .place], [false, true])+ func unchangedLegacyLiteralReceiptAndNotesStayByteExact(kind: RecordKind, substringOnly: Bool) async throws {+ let value = try await seed(mode: "record", kind: kind)+ let note: String+ let alias: String+ if kind == .character { note = substringOnly ? "Adam." : "Ada and Addiewood."; alias = "Addie" }+ else { note = substringOnly ? "Harbormaster." : "Harbor and Bayfield."; alias = "Bay" }+ let rootID = try await insertLegacyLiteralRoot(value, kind: kind, note: note, aliases: [alias], text: "Legacy byte exact\n🌟")+ let before = try #require(try await active(value, entry: value.source).first { $0.pair.kind == kind })+ #expect(before.activeAcceptanceIDs == [rootID])+ let bytes = try await rawRollbackState(value.fixture.repository)+ let entry = try await value.fixture.repository.entry(id: value.source)+ _ = try await value.fixture.repository.updateEntry(id: value.source, basis: .init(entry: entry), note: note, rating: .up)+ let after = try #require(try await active(value, entry: value.source).first { $0.pair.kind == kind })+ #expect(after.activeAcceptanceIDs == before.activeAcceptanceIDs && after.noteHeads == before.noteHeads)+ #expect(try await rawRollbackState(value.fixture.repository) == bytes)+ withExtendedLifetime(value.fixture) {}+ }++ @Test func rejectedWholeAliasDoesNotConcealCasedMentionLoss() async throws {+ let value = try await seed(mode: "record")+ let text = "Rejected alias detachment\n exact"+ let rootID = try await insertLegacyLiteralRoot(value, kind: .character, note: "Ada.", aliases: ["Addie"],+ rejectedKeys: ["addie"], text: text)+ let before = try #require(try await active(value, entry: value.source).first { $0.pair.kind == .character })+ #expect(before.activeAcceptanceIDs == [rootID])+ let entry = try await value.fixture.repository.entry(id: value.source)+ _ = try await value.fixture.repository.updateEntry(id: value.source, basis: .init(entry: entry), note: "Adam and Addie.", rating: nil)+ #expect(try await active(value, entry: value.source).isEmpty)+ let detached = try await value.fixture.repository.detachedAssociationNotes()+ #expect(detached.contains { ExactScalarString($0.raw.text) == ExactScalarString(text) })+ let pair = before.pair+ let suppressed = try await value.fixture.repository.withLockedContext(mode: .shared, operation: "checking standing alias rejection") { context in+ try AssociationStorageInventory.read(context: context, workIDs: [pair.workID], includeNotes: false)+ .ledger.isSuppressed(pair: pair, spellingKey: "addie")+ }+ #expect(suppressed)+ withExtendedLifetime(value.fixture) {}+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationStorageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationStorageTests.swiftnew file mode 100644index 00000000..89c8c55a--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/AssociationStorageTests.swift@@ -0,0 +1,154 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Association physical storage", .serialized)+struct AssociationStorageTests {+ private func container() throws -> ModelContainer {+ let schema = Schema(versionedSchema: AsterismSchemaV21.self)+ return try ModelContainer(for: schema, configurations: [+ ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)])+ }+ private func pair(work: UUID = UUID()) -> AssociationPair {+ .init(workID: work, entryID: UUID(), kind: .character, recordID: UUID())+ }+ private func current(_ pair: AssociationPair, source: String = "S1") -> AssociationCurrentPair {+ .init(pair: pair, sourceFingerprint: source, matchingFingerprint: "R1", evidence: [.init(key: "alice", spelling: "Alice")])+ }+ private func accept(_ pair: AssociationPair) -> AssociationLedgerEvent {+ let event = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: ["alice"])))+ return event.validated(by: AssociationLedgerInventory(events: [event]).receipt(for: current(pair)))+ }+ @Test func malformedOffWorkPhysicalCopyQuarantinesEncounteredIdentity() throws {+ let container = try container(), context = ModelContext(container), pair = pair()+ let event = accept(pair)+ let good = try AssociationEvent(event: event, recordedAt: .distantPast)+ let bad = try AssociationEvent(event: event, recordedAt: .distantPast)+ bad.workID = UUID(); bad.eventData = Data([0xff, 0x00])+ context.insert(good); context.insert(bad); try context.save()+ let read = try AssociationStorageInventory.read(context: context, workIDs: [pair.workID])+ #expect(read.eventRows.count == 2)+ #expect(read.ledger.invalidIDs.contains(event.id))+ #expect(read.ledger.activeAcceptanceIDs(for: current(pair)).isEmpty)+ #expect(read.rawEvents.contains { $0.eventData == Data([0xff, 0x00]) })+ }+ @Test func completeReceiptVariantsRemainWholeAcrossPendingAndSavedRows() throws {+ let container = try container(), context = ModelContext(container), pair = pair()+ let first = accept(pair)+ let variant = first.validated(by: AssociationLedgerInventory(events: [first]).receipt(for: current(pair, source: "S2")))+ context.insert(try AssociationEvent(event: first, recordedAt: .distantPast))+ try context.save()+ context.insert(try AssociationEvent(event: variant, recordedAt: .distantPast))+ let read = try AssociationStorageInventory.read(context: context, workIDs: [pair.workID])+ #expect(read.rawEvents.count == 2)+ #expect(read.ledger.activeAcceptanceIDs(for: current(pair)) == [first.id])+ #expect(read.ledger.activeAcceptanceIDs(for: current(pair, source: "S2")) == [first.id])+ }+ @Test func malformedNoteMetadataKeepsExactRawTextAndQuarantinesValidTwin() throws {+ let container = try container(), context = ModelContext(container), pair = pair()+ let event = accept(pair)+ context.insert(try AssociationEvent(event: event, recordedAt: .distantPast))+ let value = AssociationNoteValue(pair: pair, attachmentAcceptanceIDs: [event.id], text: " authored\nRen\u{00e9}e ")+ let good = try PairNoteVersion(note: value), bad = try PairNoteVersion(note: value)+ bad.parentHeadIDsData = Data("not JSON".utf8)+ bad.text = " authored\nRene\u{0301}e "+ context.insert(good); context.insert(bad); try context.save()+ let read = try AssociationStorageInventory.read(context: context, workIDs: [pair.workID])+ #expect(read.notes.invalidIDs.contains(value.id))+ #expect(read.notes.heads(for: pair).isEmpty)+ #expect(read.rawNotes.count == 2)+ #expect(Set(read.rawNotes.map { Data($0.text.utf8) }).count == 2)+ #expect(read.rawNotes.contains { $0.parentHeadIDsData == Data("not JSON".utf8) })+ }+ @Test func crossWorkRebindLoadsCompleteHistoricalParentScope() throws {+ let container = try container(), context = ModelContext(container), old = pair()+ let destination = AssociationPair(workID: UUID(), entryID: old.entryID, kind: old.kind, recordID: old.recordID)+ let parent = accept(old)+ var child = AssociationLedgerEvent(payload: .accept(.init(pair: destination, spellingKeys: ["alice"],+ rebind: .init(operation: .workMerge(fromWorkID: old.workID,+ toWorkID: destination.workID), predecessorIDs: [parent.id]))))+ child = child.validated(by: AssociationLedgerInventory(events: [parent, child]).receipt(for: current(destination)))+ context.insert(try AssociationEvent(event: parent, recordedAt: .distantPast))+ context.insert(try AssociationEvent(event: child, recordedAt: .distantPast)); try context.save()+ let read = try AssociationStorageInventory.read(context: context, workIDs: [destination.workID])+ #expect(read.rawEvents.count == 2)+ #expect(read.ledger.activeAcceptanceIDs(for: current(destination)) == [child.id])+ #expect(read.ledger.activeAcceptanceIDs(for: current(old)).isEmpty)+ #expect(read.eventFetchCount == 4)+ }+ @Test func largeSelectedWorkUsesBatchedPhysicalIdentityReads() throws {+ let container = try container(), context = ModelContext(container), work = UUID()+ let records = (0..<120).map { _ in UUID() }+ var selected: AssociationPair?+ for workID in [work, UUID()] {+ for index in 0..<600 {+ let entry = UUID()+ for offset in 0..<2 {+ let pair = AssociationPair(workID: workID, entryID: entry, kind: .character,+ recordID: records[(index + offset) % records.count])+ context.insert(try AssociationEvent(event: accept(pair), recordedAt: .distantPast))+ if workID == work { selected = pair }+ }+ }+ }+ try context.save()+ let read = try AssociationStorageInventory.read(context: context, workIDs: [work], includeNotes: false)+ #expect(read.rawEvents.count == 1200)+ #expect(read.eventFetchCount == 2) // Work selection + all physical copies.+ #expect(read.noteFetchCount == 0)+ #expect(read.ledger.activeAcceptanceIDs(for: current(try #require(selected))).count == 1)+ }+ @Test func largeSelectedMutationUsesOneGroupedInventoryAndKeepsOtherWorkUntouched() throws {+ let container = try container(), context = ModelContext(container)+ let selectedWork = UUID(), untouchedWork = UUID()+ let empty = AssociationLedgerInventory(events: [])+ var selectedEntry = UUID()+ for workID in [selectedWork, untouchedWork] {+ let work = Work(id: workID, displayTitle: "Synthetic large Work", timestamp: .distantPast)+ context.insert(work)+ let records = (0..<120).map { index in+ let row = CharacterRecord(name: "Person\(index)", nameKey: "person\(index)", work: work)+ context.insert(row); return row+ }+ for index in 0..<600 {+ let chosen = [records[index % 120], records[(index + 1) % 120]]+ let entry = Entry(captureTitle: "Chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: .distantPast,+ note: chosen.map(\.name).joined(separator: " and "))+ try entry.authorTarget(.init(kind: .chapter)); context.insert(entry); entry.work = work+ if workID == selectedWork { selectedEntry = entry.id }+ for record in chosen {+ let pair = AssociationPair(workID: workID, entryID: entry.id, kind: .character, recordID: record.id)+ let current = AssociationCurrentPair(pair: pair,+ sourceFingerprint: AssociationEndpointInventory.sourceFingerprint(entry),+ matchingFingerprint: AssociationEndpointInventory.targetFingerprint(record),+ evidence: RecordMentionGrounding.evidence(names: [record.name], in: entry.note))+ let core = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: current.evidence.map(\.key))),+ validation: empty.receipt(for: current))+ context.insert(try AssociationEvent(event: core, recordedAt: .distantPast))+ }+ }+ }+ try context.save()+ let editedID = selectedEntry+ let entry = try #require(try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { $0.id == editedID })).first)+ let start = ContinuousClock.now+ let before = try AssociationMutation.capture(context: context, workIDs: [selectedWork], entryIDs: [editedID])+ #expect(before.storage.rawEvents.count == 1200)+ #expect(before.storage.eventFetchCount == 2)+ #expect(before.endpoints.endpointFetchCount == 3)+ #expect(before.active.count == 2)+ entry.note += "."+ _ = try before.finish(context: context, timestamp: .distantPast)+ try context.save()+ print("T2468 selected600chapter/120record mutation: \(start.duration(to: .now)); 1200 selected events,2 event fetches,3 endpoint fetches")+ let after = try AssociationStorageInventory.read(context: context, workIDs: [selectedWork])+ let endpoints = try AssociationEndpointInventory.read(context: context, pairs: before.pairs)+ for (pair, ids) in before.active {+ #expect(after.ledger.activeAcceptanceIDs(for: try #require(endpoints.current(pair))) == ids)+ }+ #expect(try context.fetchCount(FetchDescriptor<AssociationEvent>(predicate: #Predicate { $0.workID == untouchedWork })) == 1200)+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swiftindex 204ce06a..13f88409 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupExportDegradedRefusalTests.swift@@ -897,7 +897,7 @@ struct BackupExportDegradedRefusalTests { metadata: BackupV18Metadata(appBuild: "1", exportedAt: DegradedExportFixture.epoch)) let decoded = try BackupV18Codec.decode(encoded) - let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none) let container = try ModelContainer(for: schema, configurations: [configuration])
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swiftindex 338b3a50..78f21b83 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupImportTransactionTests.swift@@ -683,7 +683,7 @@ private func createReadyEmptyV3Store(at configuration: LibraryConfiguration) thr at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -692,7 +692,7 @@ private func createReadyEmptyV3Store(at configuration: LibraryConfiguration) thr ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV20MigrationPlan.self,+ migrationPlan: AsterismV21MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -706,7 +706,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -715,7 +715,7 @@ private func createReadyPopulatedV3Store(at configuration: LibraryConfiguration) ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV20MigrationPlan.self,+ migrationPlan: AsterismV21MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -758,7 +758,7 @@ private func createReadySiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -767,7 +767,7 @@ private func createReadySiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV20MigrationPlan.self,+ migrationPlan: AsterismV21MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)@@ -802,7 +802,7 @@ private func createReadyDuplicateSiteStore( at: configuration.storeURL.deletingLastPathComponent(), withIntermediateDirectories: true )- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let storeConfig = ModelConfiguration( "AsterismV3", schema: schema,@@ -811,7 +811,7 @@ private func createReadyDuplicateSiteStore( ) let container = try ModelContainer( for: schema,- migrationPlan: AsterismV20MigrationPlan.self,+ migrationPlan: AsterismV21MigrationPlan.self, configurations: [storeConfig] ) let context = ModelContext(container)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swiftindex a5deb034..9d9f7279 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ArchiveTests.swift@@ -1954,7 +1954,7 @@ struct BackupV18ExportTests { private var carrier: Work! init() throws {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) container = try ModelContainer( for: schema, configurations: [@@ -2226,7 +2226,7 @@ struct BackupV18ImportTests { #expect(reason.contains("format \(pair.format)")) #expect(reason.contains("schema \(pair.schema)")) // Req 13.1 names both pairs: the archive's and the one this build reads.- #expect(reason.contains("(\(BackupV19Document.formatVersion)/\(BackupV19Document.schemaVersion))"))+ #expect(reason.contains("(\(BackupV20Document.formatVersion)/\(BackupV20Document.schemaVersion))")) } @Test("A mismatched pair around 16/17 is unsupported")@@ -2573,7 +2573,7 @@ struct BackupV18ImportTests { /// which is what Req 1.8 promises a restore does. @Test("Re-applying the same archive cover writes nothing, and a broken blob heals") func reapplyingTheSameCoverWritesNothing() throws {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let container = try ModelContainer( for: schema, configurations: [@@ -3875,7 +3875,7 @@ struct BackupV18ImportTests { /// the third is exactly where the two differ (Q23). @Test("Re-applying the same archive citations writes nothing; undecodable and absent blobs heal") func reapplyingTheSameCitationsWritesNothing() throws {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let container = try ModelContainer( for: schema, configurations: [@@ -3966,7 +3966,7 @@ struct BackupV18ImportTests { /// on both sides of an undecodable row and skip the heal. @Test("Re-applying the same archive facts writes nothing; undecodable bytes heal") func reapplyingTheSameFactsWritesNothing() throws {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swiftindex b09b29ce..ee0c6016 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV18ImportMatrixTests.swift@@ -209,7 +209,7 @@ struct BackupV18ImportMatrixTests { } #expect(reason.contains("format 15")) #expect(reason.contains("schema 16"))- #expect(reason.contains("(19/20)"))+ #expect(reason.contains("(20/21)")) // And it writes nothing (Req 5.3). The refusal is at `plan`, which runs // outside the repository actor and holds no lease, so there is no plan
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV19ChapterTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV19ChapterTests.swiftindex d51568ee..e2f85e07 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV19ChapterTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BackupV19ChapterTests.swift@@ -26,6 +26,58 @@ struct BackupV19ChapterTests { #expect(!FileManager.default.fileExists(atPath: staging.path)) #expect(try await fixture.repository.archiveEntryNotes(id: entry) == Set(["First", "Second"])) }+ @Test("Archive legacy chapter fields stay separate from effective authored targets", arguments: [false, true])+ func authoredTargetDoesNotReplaceRawChapterTuple(asNote: Bool) throws {+ let row = Entry(id: UUID(), captureTitle: "Synthetic capture", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch,+ note: "Preserved authored content")+ if asNote {+ row.chapterTitle = "Legacy Cafe\u{301} chapter"+ row.editCitations { $0.chapterTitle = .manual }+ }+ try row.authorTarget(.init(kind: asNote ? .note : .chapter, title: "Current authored title"))+ try LibraryValidator.validateEntryTuple(entry: row, works: [])+ let rawTitle = row.chapterTitle+ let rawCitation = try row.citations.chapterTitle+ let rawTarget = row.authoredTargetData+ let group = try #require(LibraryRepository.entryGroup(id: row.id, rows: [row], canonicalWorkIDs: [:]))+ let snapshot = try LibraryRepository.snapshot(group)+ #expect(snapshot.chapterTitle == (asNote ? nil : "Current authored title"))+ let archived = try LibraryRepository.mapV18EntryRecord(group, citations: EntryCitationsCache([row]))+ #expect(archived.chapterTitle.map { Data($0.utf8) } == rawTitle.map { Data($0.utf8) })+ #expect(archived.citations.chapterTitle == rawCitation)+ let restored = ArchiveRecordBuilders.makeEntry(archived)+ LibraryRepository.applyChapterArchive(.init(predecessor: archived, authoredTargetData: rawTarget), to: restored)+ #expect(restored.authoredTargetData == rawTarget)+ try LibraryValidator.validateEntryTuple(entry: restored, works: [])+ #expect(row.authoredTargetData == rawTarget && row.chapterTitle == rawTitle,+ "Export projection cannot rewrite the source tuple")+ }++ @Test("Split archive chapter value and citation come from the authored carrier")+ func splitChapterTupleUsesCarrierInsteadOfBareRepresentative() throws {+ let id = UUID(), url = "https://example.com/synthetic-chapter"+ let representative = Entry(id: id, captureTitle: "Bare capture", captureTitleSource: .host,+ rawURLString: url, hostname: "example.com", entryIdentityKey: url, timestamp: M5Fixture.epoch)+ let carrier = Entry(id: id, captureTitle: "Other capture", captureTitleSource: .host,+ rawURLString: url, hostname: "example.com", entryIdentityKey: url,+ timestamp: M5Fixture.epoch.addingTimeInterval(1), note: "Authored carrier note")+ representative.conservativeIdentityKey = url+ carrier.conservativeIdentityKey = url+ carrier.chapterTitle = "Carrier Cafe\u{301} chapter"+ carrier.editCitations { $0.chapterTitle = .manual }+ try LibraryValidator.validateEntryTuple(entry: representative, works: [])+ try LibraryValidator.validateEntryTuple(entry: carrier, works: [])+ let group = try #require(LibraryRepository.entryGroup(id: id, rows: [carrier, representative], canonicalWorkIDs: [:]))+ #expect(group.isSplit && !group.isTorn)+ #expect(group.representative === representative && group.carrier === carrier)+ let archived = try LibraryRepository.mapV18EntryRecord(group, citations: EntryCitationsCache([representative, carrier]))+ #expect(archived.chapterTitle.map { Data($0.utf8) } == carrier.chapterTitle.map { Data($0.utf8) })+ #expect(archived.citations.chapterTitle.kind == .manual)+ #expect(archived.note == carrier.note)+ try LibraryValidator.validateEntryTuple(entry: ArchiveRecordBuilders.makeEntry(archived), works: [])+ }+ @Test("Released 18/19 restores without inventing authored targets, sources or work defaults") func predecessorRestore() async throws { let encoded = try BackupV18Codec.encode(payload: BackupV18Fixtures.payload(), metadata: BackupV18Fixtures.metadata())@@ -51,22 +103,22 @@ struct BackupV19ChapterTests { let contract = try await source.repository.projectEntryCorrection(entryID: loser, destinationID: survivor) #expect(try await source.repository.commitEntryCorrection(contract, target: .init(kind: .chapter, designation: "12")) == .committed(entryID: survivor))- let payload = try await source.repository.backupV19Snapshot()- #expect(payload.entries.count == 2)- #expect(payload.entries.first { $0.id == loser }?.mergedIntoEntryID == survivor)- #expect(payload.entrySources.contains { $0.urlString == "https://example.com/a" })- let encoded = try BackupV19Codec.encode(payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))- let decoded = try BackupV19Codec.decode(encoded)+ let payload = try await source.repository.backupV20Snapshot()+ #expect(payload.library.entries.count == 2)+ #expect(payload.library.entries.first { $0.id == loser }?.mergedIntoEntryID == survivor)+ #expect(payload.library.entrySources.contains { $0.urlString == "https://example.com/a" })+ let encoded = try BackupV20Codec.encode(payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let decoded = try BackupV20Codec.decode(encoded) #expect(decoded.payload == payload)- #expect(decoded.backupFormatVersion == 19 && decoded.databaseSchemaVersion == 20)+ #expect(decoded.backupFormatVersion == 20 && decoded.databaseSchemaVersion == 21) let plan = try BackupImporter.plan(from: encoded) let restored = try await M5Fixture() _ = try await restored.repository.confirmImport(plan: plan) #expect(try await restored.repository.entry(id: loser).id == survivor)- let first = try await restored.repository.backupV19Snapshot()+ let first = try await restored.repository.backupV20Snapshot() _ = try await restored.repository.confirmImport(plan: plan)- #expect(try await restored.repository.backupV19Snapshot() == first)- #expect(first.entries.count == 2 && first.entrySources.count == payload.entrySources.count)+ #expect(try await restored.repository.backupV20Snapshot() == first)+ #expect(first.library.entries.count == 2 && first.library.entrySources.count == payload.library.entrySources.count) } @Test("Contradictory authored target with legacy identity refuses the new archive")@@ -106,16 +158,16 @@ struct BackupV19ChapterTests { draft: .init(sourceURL: "https://amazon.com/book", rating: .up)) else { Issue.record("Manual rating-only note must save"); return }- let payload = try await source.repository.backupV19Snapshot()- #expect(payload.sites.isEmpty && payload.memberships.isEmpty)- let encoded = try BackupV19Codec.encode(payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let payload = try await source.repository.backupV20Snapshot()+ #expect(payload.library.sites.isEmpty && payload.library.memberships.isEmpty)+ let encoded = try BackupV20Codec.encode(payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch)) let restored = try await M5Fixture() _ = try await restored.repository.confirmImport(plan: BackupImporter.plan(from: encoded)) #expect(try await restored.repository.entry(id: entry.id).rating == .up)- let result = try await restored.repository.backupV19Snapshot()- #expect(result.entries.first?.rawURL.isEmpty == true)- #expect(result.entrySources.first?.urlString == "https://amazon.com/book")- #expect(result.sites.isEmpty && result.memberships.isEmpty)+ let result = try await restored.repository.backupV20Snapshot()+ #expect(result.library.entries.first?.rawURL.isEmpty == true)+ #expect(result.library.entrySources.first?.urlString == "https://amazon.com/book")+ #expect(result.library.sites.isEmpty && result.library.memberships.isEmpty) } @Test("A valid imported late source is retained when local combined content needs review")@@ -128,23 +180,24 @@ struct BackupV19ChapterTests { .init(id: survivor, captureTitle: "Second", hostname: "example.com", path: "b", workID: work)]) let contract = try await fixture.repository.projectEntryCorrection(entryID: loser, destinationID: survivor) _ = try await fixture.repository.commitEntryCorrection(contract, target: .init(kind: .chapter, designation: "12"))- let original = try await fixture.repository.backupV19Snapshot()+ let original = try await fixture.repository.backupV20Snapshot() let sourceID = UUID() let incoming = BackupV19EntrySource(id: sourceID, entryID: loser, urlString: "https://example.com/late", hostname: "example.com", createdAt: M5Fixture.epoch, modifiedAt: M5Fixture.epoch)- let payload = BackupV19Payload(entries: original.entries, works: original.works, sites: original.sites,- titlePatterns: original.titlePatterns, urlRules: original.urlRules, workTypes: original.workTypes,- memberships: original.memberships, distinctPairs: original.distinctPairs, characters: original.characters,- suppressions: original.suppressions, places: original.places, placeSuppressions: original.placeSuppressions,- series: original.series, links: original.links, creators: original.creators, creatorRoles: original.creatorRoles,- credits: original.credits, noEpisodeActions: original.noEpisodeActions, entrySources: original.entrySources + [incoming])- let encoded = try BackupV19Codec.encode(payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch))+ let payload = BackupV19Payload(entries: original.library.entries, works: original.library.works, sites: original.library.sites,+ titlePatterns: original.library.titlePatterns, urlRules: original.library.urlRules, workTypes: original.library.workTypes,+ memberships: original.library.memberships, distinctPairs: original.library.distinctPairs, characters: original.library.characters,+ suppressions: original.library.suppressions, places: original.library.places, placeSuppressions: original.library.placeSuppressions,+ series: original.library.series, links: original.library.links, creators: original.library.creators, creatorRoles: original.library.creatorRoles,+ credits: original.library.credits, noEpisodeActions: original.library.noEpisodeActions, entrySources: original.library.entrySources + [incoming])+ let currentPayload = BackupV20Payload(library: payload, associationEvents: original.associationEvents, pairNoteVersions: original.pairNoteVersions)+ let encoded = try BackupV20Codec.encode(payload: currentPayload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch)) let plan = try BackupImporter.plan(from: encoded) try await fixture.repository.seedArchiveLateEdit(entryID: loser) _ = try await fixture.repository.confirmImport(plan: plan) #expect(try await fixture.repository.entry(id: loser).changesAfterCombine) #expect(try await fixture.repository.archiveHasSource(id: sourceID, owner: loser))- await #expect(throws: (any Error).self) { try await fixture.repository.backupV19Snapshot() }+ await #expect(throws: (any Error).self) { try await fixture.repository.backupV20Snapshot() } } @Test("Evidence order is byte-stable for scalar-distinct Unicode labels")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swiftindex 30c8fd13..bcd849f3 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapActionTests.swift@@ -125,7 +125,7 @@ struct BootstrapActionTests { // are not what "empty" means here: the guard asks whether anything of the // *reader's* would be certified sight unseen. #expect(result == .ready(.seededEmpty))- #expect(try root.markerText() == "20",+ #expect(try root.markerText() == "21", "a crash between store creation and the marker is repaired, not terminal") withExtendedLifetime(root) {} }@@ -269,7 +269,7 @@ struct BootstrapActionTests { // the owner's library (Decision 5) — and the container construction is // what fails. try Data("this is not a sqlite store".utf8).write(to: root.storeURL, options: .atomic)- try root.writeMarker("20\n")+ try root.writeMarker("21\n") let before = try root.digest() await #expect(throws: (any Error).self) {@@ -309,10 +309,10 @@ private enum RefusedState: String, CaseIterable, Sendable { switch self { case .storeRecordedBelowV5: try root.installStoreRecordedAtFourZeroZero()- try root.writeMarker("20\n")+ try root.writeMarker("21\n") case .readinessMarkerWithoutAStore: try root.createStoreDirectory()- try root.writeMarker("20\n")+ try root.writeMarker("21\n") case .historicalMarkerWithoutAStore: try root.createStoreDirectory() try root.writeHistoricalMarker()
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swiftindex dcc67c28..07f1ad10 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapClassifierTests.swift@@ -92,7 +92,7 @@ struct BootstrapClassifierTests { func readyMarkerGovernsOverAHistoricalMarker() throws { let root = try ClassifierRoot() try root.seedBornAtLiveStore()- try root.writeMarker("20\n")+ try root.writeMarker("21\n") try root.writeHistoricalMarker() #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready)@@ -106,7 +106,7 @@ struct BootstrapClassifierTests { func readyMarkerGovernsOverALeftoverArtefact() throws { let root = try ClassifierRoot() try root.seedBornAtLiveStore()- try root.writeMarker("20\n")+ try root.writeMarker("21\n") try root.writeMigrationArtefact() #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready)@@ -360,7 +360,7 @@ struct BootstrapClassifierTests { // it, which is `.indeterminate` — and `.indeterminate` proceeds. try root.createStoreDirectory() try Data("not a database".utf8).write(to: root.storeURL, options: .atomic)- try root.writeMarker("20\n")+ try root.writeMarker("21\n") try #require(StoreMetadata.recordedVersion(at: root.storeURL) == .indeterminate) #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready,@@ -430,7 +430,7 @@ private struct Cell: Sendable, CustomStringConvertible { case .fifteen: try root.writeMarker("15\n") case .sixteen: try root.writeMarker("16\n") case .seventeen: try root.writeMarker("17\n")- case .twenty: try root.writeMarker("20\n")+ case .twenty: try root.writeMarker("21\n") case .unrecognisedText: try root.writeMarker("99\n") case .nonUTF8: try root.writeMarkerBytes(ClassifierRoot.nonUTF8MarkerBytes) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swiftindex 53ea52c0..854011a3 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/BootstrapStateCoverageTests.swift@@ -279,7 +279,7 @@ private enum PreCertificationState: String, CaseIterable, Sendable { /// The bytes a certified library's readiness marker holds. Frozen persisted state /// — `FrozenLibraryPathTests` is where that is pinned; here it is the value the /// ready cases compare against.-private let readyMarkerBytes = "20\n"+private let readyMarkerBytes = "21\n" /// The counts of a library seeded with exactly one `Site`. ///
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swiftindex 3c3361af..36a25602 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CatchUpArchiveTests.swift@@ -166,6 +166,6 @@ struct CatchUpArchiveTests { return } #expect(reason.contains("format 15/schema 16"))- #expect(reason.contains("(19/20)"))+ #expect(reason.contains("(20/21)")) } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swiftindex b4a2db72..92c99d61 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CertificationPathTests.swift@@ -107,7 +107,7 @@ struct CertificationPathTests { // unopenable rather than because the marker was read first. try Data("16\n".utf8).write(to: cfg.readinessMarkerURL, options: .atomic) _ = try await LibraryRepository.openForApp(cfg)- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["20.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["21.0.0"], "the same store converts once the marker check passes") withExtendedLifetime(dir) {} }@@ -119,7 +119,7 @@ struct CertificationPathTests { let (dir, cfg) = try config() let (result, _) = try await LibraryRepository.openForApp(cfg) #expect(result == .ready(.zero))- #expect(try markerContent(cfg) == "20",+ #expect(try markerContent(cfg) == "21", "an empty store has nothing to bring forward and is certified at birth (Q26)") withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCorrectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCorrectionTests.swiftindex 46be28e0..e7a3a6f1 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCorrectionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterCorrectionTests.swift@@ -35,7 +35,7 @@ struct ChapterCorrectionTests { } @Test("Clean retained losers do not count as current no-episode notes") func combinedNoEpisodeFacts() throws {- let container = try ModelContainer(for: Schema(AsterismSchemaV20.models),+ let container = try ModelContainer(for: Schema(AsterismSchemaV21.models), configurations: ModelConfiguration(isStoredInMemoryOnly: true)) let context = ModelContext(container) let work = Work(displayTitle: "Book", timestamp: M5Fixture.epoch)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterIdentityTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterIdentityTests.swiftindex 32ddf316..97a2faf7 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterIdentityTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterIdentityTests.swift@@ -214,7 +214,7 @@ private struct ChapterIdentityFixture { let container: ModelContainer let context: ModelContext init() throws {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) container = try ModelContainer(for: schema, configurations: [ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterMetadataMigrationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterMetadataMigrationTests.swiftindex 2849a13b..f0780650 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterMetadataMigrationTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ChapterMetadataMigrationTests.swift@@ -7,7 +7,7 @@ import Testing struct ChapterMetadataMigrationTests { @Test("Live schema contains additive optional chapter metadata and source entity") func additiveShape() throws {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let entry = try #require(schema.entities.first { $0.name == "Entry" }) for name in ["authoredTargetData", "mergedIntoEntryID", "mergeResolutionData"] { let attribute = try #require(entry.attributes.first { $0.name == name })@@ -87,7 +87,7 @@ struct ChapterMetadataMigrationTests { } #expect(facts == entryID) await repository.shutdown()- #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "20\n")+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "21\n") } private func seed(url: URL, workID: UUID, entryID: UUID, instant: Date) throws {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterExtractionRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterExtractionRepositoryTests.swiftindex 038a93ab..ad914c8a 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterExtractionRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CharacterExtractionRepositoryTests.swift@@ -90,10 +90,10 @@ struct ExtractionCandidateReadTests { @Test("A covered revision reads as covered, and editing the note uncovers it again") func coverageIsPerRevision() async throws { let fixture = try await fixture()- let fingerprint = CharacterCoverageFingerprint.of("Hanna led the squad")+ let source = try #require(try await fixture.repository.extractionCandidates(limit: 100)+ .first { $0.workID == workA }?.sources.first { $0.ref == .entry(entry1) }) let written = try await fixture.repository.advanceCoverage(- workID: workA,- sources: [CompletedSource(ref: .entry(entry1), fingerprint: fingerprint)])+ workID: workA, sources: [source.completedSource]) #expect(written == 1) var candidate = try #require(@@ -373,8 +373,11 @@ struct RecordDecisionCommitTests { let candidate = try #require( try await fixture.repository.extractionCandidates(limit: 100).first)- #expect(candidate.uncoveredSources.map(\.ref) == [.genericNotes],- "the decision's own source covers in the same save (Q65)")+ let source = try #require(candidate.sources.first { $0.ref == .entry(entry1) })+ #expect(source.coveredFingerprint == source.fingerprint,+ "the decision's fact source covers in the same save (Q65)")+ #expect(candidate.uncoveredSources.map(\.ref) == [.genericNotes, .entry(entry1)],+ "legacy fact-only acceptance cannot certify unseen chapter associations") #expect(candidate.suppressions(of: kind).candidateKeys.isEmpty, "Req 2.5: acceptance clears the key") #expect(candidate.records(of: kind).map(\.id) == [id],@@ -719,33 +722,27 @@ struct RecordDecisionCommitTests { withExtendedLifetime(fixture) {} } - /// Coverage is one record per source revision whatever decided it (Q9): a- /// place decision covers the note as a character decision would, and the- /// next sweep does not re-read it for the other kind.- @Test(- "Coverage advances once per source, whichever kind decided it",+ /// Fact coverage remains shared across kinds. A legacy fact-only decision+ /// leaves the independent association pass eligible until its current+ /// bounded produced-none completion certifies the whole source.+ @Test("Coverage advances once per source, whichever kind decided it", arguments: RecordKind.allCases) func coverageAdvancesWhicheverKindDecided(kind: RecordKind) async throws { let fixture = try await fixture(kind)- _ = try await fixture.repository.commitDecision(acceptNewHanna(kind))- let candidate = try #require( try await fixture.repository.extractionCandidates(limit: 100).first)- #expect(candidate.uncoveredSources.map(\.ref) == [.genericNotes],- "one coverage column per source, not one per kind (Q9)")-- // And `advanceCoverage` — the produced-none path — is the same call for- // both kinds, so covering the remaining source needs no second column.+ let entry = try #require(candidate.sources.first { $0.ref == .entry(entry1) })+ #expect(entry.coveredFingerprint == entry.fingerprint,+ "one fact coverage column per source, not one per kind (Q9)")+ #expect(candidate.uncoveredSources.map(\.ref) == [.genericNotes, .entry(entry1)],+ "the legacy request supplied no chapter-association completion basis") let written = try await fixture.repository.advanceCoverage(- workID: workA,- sources: [CompletedSource(- ref: .genericNotes,- fingerprint: CharacterCoverageFingerprint.of("the cast is Hanna"))])- #expect(written == 1)+ workID: workA, sources: candidate.uncoveredSources.map(\.completedSource))+ #expect(written == 2) #expect(try await fixture.repository.extractionCandidates(limit: 100) .allSatisfy { $0.uncoveredSources.isEmpty },- "nothing is left for a sweep of either kind to re-read")+ "the bounded produced-none pass certifies both kinds together") withExtendedLifetime(fixture) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swiftindex d7e96cb2..e146e582 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CitationBlobRefreshTests.swift@@ -247,12 +247,12 @@ private final class BlobStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismCitationBlob-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swiftindex c64b5877..e256c592 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ConvergedRuleGroupValidationTests.swift@@ -367,12 +367,12 @@ private final class RuleGroupStore { let directory = FileManager.default.temporaryDirectory .appending(path: "AsterismConvergedRules-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) let container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) self.init(context: ModelContext(container)) retained = container
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swiftindex b60ef19a..f1cd07b1 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CreatorConvergenceTests.swift@@ -41,9 +41,9 @@ struct CreatorConvergenceTests { .appending(path: "CreatorConvergence-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swiftindex e8797df1..5d0edcdd 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CreditReconcilerTests.swift@@ -35,9 +35,9 @@ struct CreditReconcilerTests { .appending(path: "CreditReconciler-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swiftindex ab922fcd..6f933d40 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/CrossSiteDuplicateScanTests.swift@@ -286,12 +286,12 @@ private final class ScanStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismCrossSiteScan-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swiftindex f0fd5ced..02a0989c 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateReconcilerTestSupport.swift@@ -44,12 +44,12 @@ final class DuplicateStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismDuplicateReconciler-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) seed = ModelContext(container) if let saveStrategy {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swiftindex 1983489b..e154e731 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/DuplicateScanTests.swift@@ -597,12 +597,12 @@ private final class ScanStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismDuplicateScan-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swiftindex 42383158..d9a05d63 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/EmptyLibraryTests.swift@@ -23,7 +23,7 @@ struct EmptyLibraryTests { try await fixture.seedGoldenLibrary() let before = try await fixture.repository.emptyLibraryRowCounts()- #expect(before.count == 19, "the phase list must name every entity")+ #expect(before.count == 21, "the phase list must name every entity") #expect( before.values.allSatisfy { $0 > 0 }, "the seed leaves \(before.filter { $0.value == 0 }.keys.sorted()) empty")@@ -461,15 +461,20 @@ struct EmptyLibraryTests { let fixture = try await EmptyLibraryFixture() try await fixture.seedGoldenLibrary() - let before = try await fixture.repository.backupV18Snapshot()+ let before = try await fixture.repository.backupV20Snapshot() let report = try await fixture.repository.emptyLibrary() #expect(report.outcome == .completed) try await fixture.repository.confirmImport(plan: EmptyLibraryFixture.plan(before))- let after = try await fixture.repository.backupV18Snapshot()+ let after = try await fixture.repository.backupV20Snapshot() try BackupV18RestoreAssertions.expectExactRecordsAndFreshNoteClears(- before: before, after: after)+ before: before.library.legacyRecordsForRestoreAssertions, after: after.library.legacyRecordsForRestoreAssertions)+ #expect(after.library.entries == before.library.entries)+ #expect(after.library.works == before.library.works)+ #expect(after.library.entrySources == before.library.entrySources)+ #expect(after.associationEvents == before.associationEvents)+ #expect(after.pairNoteVersions == before.pairNoteVersions) await fixture.tearDown() } @@ -491,10 +496,10 @@ struct EmptyLibraryTests { let fixture = try await EmptyLibraryFixture(saveStrategy: strategy) try await fixture.seedGoldenLibrary() - let archive = try await fixture.repository.backupV18Snapshot()+ let archive = try await fixture.repository.backupV20Snapshot() _ = try await fixture.repository.emptyLibrary() try await fixture.repository.confirmImport(plan: EmptyLibraryFixture.plan(archive))- let restored = try await fixture.repository.backupV18Snapshot()+ let restored = try await fixture.repository.backupV20Snapshot() let stamps = try await fixture.repository.modificationStampsForTesting() strategy.arm()@@ -504,7 +509,7 @@ struct EmptyLibraryTests { #expect( strategy.dirtySaves.allSatisfy { !$0 }, "a second import of an unchanged archive must dirty no save, got \(strategy.dirtySaves)")- #expect(try await fixture.repository.backupV18Snapshot() == restored)+ #expect(try await fixture.repository.backupV20Snapshot() == restored) #expect(try await fixture.repository.modificationStampsForTesting() == stamps) await fixture.tearDown() }@@ -516,14 +521,14 @@ struct EmptyLibraryTests { let fixture = try await EmptyLibraryFixture() try await fixture.seedGoldenLibrary() - let archive = try await fixture.repository.backupV18Snapshot()+ let archive = try await fixture.repository.backupV20Snapshot() let late = try await fixture.repository.capture( CaptureDraft( captureTitle: "Chapter 9 - After the export", captureTitleSource: .safariDocument, rawURLString: "https://late.example/read?chapter=9")) - #expect(!archive.entries.contains { $0.id == late.id })+ #expect(!archive.library.entries.contains { $0.id == late.id }) _ = try await fixture.repository.emptyLibrary() let after = try await fixture.repository.emptyLibraryRowCounts() #expect(after.values.allSatisfy { $0 == 0 })@@ -813,6 +818,7 @@ private final class EmptyLibraryFixture { payload: BackupGoldenLibrary.payload, metadata: BackupGoldenLibrary.metadata))) try await repository.seedGoldenEntrySource()+ try await repository.seedGoldenAssociationRows() } /// One waiting capture, one set aside, one refusal receipt, a drain report@@ -874,6 +880,11 @@ private final class EmptyLibraryFixture { urlRulePatterns: payload.urlRules.count)) } + static func plan(_ payload: BackupV20Payload) throws -> BackupImportPlan {+ try BackupImporter.plan(from: BackupV20Codec.encode(payload: payload,+ metadata: .init(appBuild: "empty-library-test", exportedAt: BackupGoldenLibrary.created)))+ }+ deinit { try? FileManager.default.removeItem(at: directory) } } @@ -887,6 +898,19 @@ extension LibraryRepository { /// `AsterismSchemaV17.models`, so counting through it is counting the /// schema's entities — and the alternative, a second hand-written list of /// seventeen fetches, is one more thing to forget at the next bump.+ fileprivate func seedGoldenAssociationRows() async throws {+ try await withLockedContext(mode: .exclusive, operation: "seeding synthetic association inventory") { context in+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first)+ let entry = try #require(try context.fetch(FetchDescriptor<Entry>()).first)+ let record = try #require(try context.fetch(FetchDescriptor<CharacterRecord>()).first)+ let pair = AssociationPair(workID: work.id, entryID: entry.id, kind: .character, recordID: record.id)+ let event = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: ["synthetic"])))+ context.insert(try AssociationEvent(event: event, recordedAt: .distantPast))+ context.insert(try PairNoteVersion(note: .init(pair: pair, attachmentAcceptanceIDs: [event.id], text: "Synthetic authored note")))+ try context.save()+ }+ }+ fileprivate func seedGoldenEntrySource() async throws { try await withLockedContext(mode: .exclusive, operation: "seeding new source entity") { context in let entry = try #require(context.fetch(FetchDescriptor<Entry>()).first)@@ -954,3 +978,16 @@ extension LibraryRepository { hasRunDuplicatePhaseThisSession } }++// Keep the existing exhaustive released-record assertions while exercising the+// current archive's additional fields above.+private extension BackupV19Payload {+ var legacyRecordsForRestoreAssertions: BackupV18Payload {+ .init(entries: entries.map(\.predecessorRecord), works: works.map(\.predecessorRecord),+ sites: sites, titlePatterns: titlePatterns, urlRules: urlRules, workTypes: workTypes,+ memberships: memberships, distinctPairs: distinctPairs, characters: characters,+ suppressions: suppressions, places: places, placeSuppressions: placeSuppressions,+ series: series, links: links, creators: creators, creatorRoles: creatorRoles,+ credits: credits, noEpisodeActions: noEpisodeActions)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swiftindex dd38bfb0..e1392228 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/FrozenLibraryPathTests.swift@@ -76,7 +76,7 @@ struct FrozenLibraryPathTests { /// moved it from `"5"` to `"6"` (Q26), `character-extraction` from `"6"` to /// `"7"` (Q80), and it now reads `"17"`, a two-character /// generation. What is frozen is the shape and the filename beside it.- private static let markerContents = "20\n"+ private static let markerContents = "21\n" /// Everything a fresh app-role open is allowed to leave in the root, SQLite's /// own `-wal`/`-shm` companions excluded. An extra entry here is a path@@ -279,9 +279,8 @@ struct FrozenLibraryPathTests { /// name here — see the rule in the suite's doc comment. @Test("No declared identifier carries a version number it does not describe") func noIdentifierNamesAVersionItDoesNotDescribe() throws {- /// The store schemas this package declares — V16 live, V15 frozen as- /// the `from` version of the one lightweight stage — the plan that- /// stages it, and the floor the recorded-version reading refuses below.+ /// Live V21 and retained V16–V20 snapshots, every plan declaring a+ /// retained transition, and the recorded-version reading's lower floor. /// /// V5 through V14 went with the stages that named them, /// each on `retire-migration-chain` Decision 6's population precondition@@ -302,30 +301,20 @@ struct FrozenLibraryPathTests { /// both deliberately unversioned by name because they always mean the /// current generation. let declaresAStoreSchemaOrMarkerGeneration: Set<String> = [- "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20",- "AsterismV17MigrationPlan", "AsterismV18MigrationPlan", "AsterismV19MigrationPlan", "AsterismV20MigrationPlan",+ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20", "AsterismSchemaV21",+ "AsterismV17MigrationPlan", "AsterismV18MigrationPlan", "AsterismV19MigrationPlan", "AsterismV20MigrationPlan", "AsterismV21MigrationPlan", "atOrAboveV5", "belowV5", "firstV5Major", ]- /// The archive format — 15/16, the one shape the app reads and writes,- /// plus the 2/2 URL-rule origin the store still names. These name a- /// serialization version, not a store schema, and they are accurate:- /// `remove-article-mode` Req 5.1 mints format 15 over schema 16,- /// and every record this generation carries is its own rather than one- /// an earlier generation froze.- ///- /// Every earlier generation's **read and write path** is gone, 14/15- /// included, so every name that described one — the codecs, documents,- /// payloads, exporters, snapshot protocols, reference and shape- /// validators, per-generation planners, gates and materializers — is- /// absent here because it is absent from the package.- ///- /// `BackupImportPlan`, `BackupImportPayload`, `plan(from:)`,- /// `materializeArchive`, `validateImportPlanPayload` and- /// `BackupCodecError` are deliberately unversioned: each serves the- /// single format, and a digit in their names would be a digit describing- /// nothing.+ /// Current archive 20/21 and the released 19/20 and 18/19 shapes+ /// retained for bounded predecessor conversion. Versioned record+ /// names describe their unchanged wire shapes; the 2/2 URL-rule origin+ /// remains a stored value. Import planning itself is unversioned. let namesTheArchiveFormat: Set<String> = [- // 19/20 is the additive authored-target/source wire generation.+ // 20/21 preserves raw associations and notes; 19/20 and 18/19 remain+ // released shapes for bounded predecessor conversion.+ "BackupV20Codec", "BackupV20Document", "BackupV20Exporter",+ "BackupV20Metadata", "BackupV20Payload", "BackupV20SnapshotProviding",+ "CompatibleBackupV20Document", "backupV20Snapshot", "projectV19Payload", "BackupV19Codec", "BackupV19Document", "BackupV19Entry", "BackupV19EntrySource", "BackupV19Exporter", "BackupV19Metadata", "BackupV19Payload", "BackupV19ReferenceValidator", "BackupV19SnapshotProviding", "BackupV19Work", "backupV19Snapshot",@@ -394,31 +383,24 @@ struct FrozenLibraryPathTests { } #expect( declared.sorted() == [- "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20",+ "AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20", "AsterismSchemaV21", ], "the package declares versioned schemas \(declared); Req 3.3 allows only ones a plan references") - let referenced = AsterismV20MigrationPlan.schemas.map { String(describing: $0) }+ let referenced = AsterismV21MigrationPlan.schemas.map { String(describing: $0) } #expect(- referenced == ["AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20"],+ referenced == ["AsterismSchemaV16", "AsterismSchemaV17", "AsterismSchemaV18", "AsterismSchemaV19", "AsterismSchemaV20", "AsterismSchemaV21"], "the plan references \(referenced), which is not the set of declared schemas")- // One lightweight stage, and it purely **removes**: V15 → V16 drops- // one `Site` column inside `ModelContainer.init` and no table at all,- // with no data pass behind it. It is the second removing stage in the- // project's history, after V8 → V9. The V8 stage retired with the- // snapshot it named (Q18); the V9 one shipped retained (Q32 of- // `series-and-related-works`) and went in the follow-up (Q60); the V10- // through V14 ones each went in the freeze commit of the bump that- // superseded them (Q15 of `work-creators`, Q65 of `place-extraction`,- // `work-thumbnails`, `update-schedule`, and this bump).+ // Retain every released snapshot and its lightweight transition.+ // V20 → V21 adds the two initially empty feature tables. #expect(- AsterismV20MigrationPlan.stages.count == 4,- "the plan stages \(AsterismV17MigrationPlan.stages.count) migrations; V15 → V16 is one")+ AsterismV21MigrationPlan.stages.count == 5,+ "the retained V16 → V21 chain has five lightweight migrations") #expect( AsterismSchemaV16.versionIdentifier == Schema.Version(16, 0, 0), "the frozen snapshot's version stamp is the `from` side every V15 store is matched on") #expect(- AsterismSchemaV20.versionIdentifier == Schema.Version(20, 0, 0),+ AsterismSchemaV21.versionIdentifier == Schema.Version(21, 0, 0), "the live schema's version stamp is what every recorded store is compared against") }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swiftindex 341412c2..cfa41c94 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupFetchTests.swift@@ -294,12 +294,12 @@ private final class GroupStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismGroupFetch-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }@@ -441,3 +441,258 @@ struct StoryPositionInputTests { #expect(Set(inputs.map(\.id)) == [duplicated, single]) } }++// PRIVATE DRAFT: append to GroupFetchTests.swift; GroupStore remains unchanged.+// Semantic parity controls pass on the original implementation as well. The+// existing, unchanged capture budget is the performance failure, not these tests.+@Suite("Capture basis singleton selection parity", .serialized)+struct CaptureBasisSingletonParityTests {+ @Test("Singleton metadata cannot change the complete-group capture basis",+ arguments: ["bare", "authored", "configured", "removed", "unresolved",+ "tolerated-status", "publication", "malformed-publication"],+ ["missing", "untaught", "taught"])+ func singletonMetadata(profile: String, siteMode: String) async throws {+ let store = try GroupStore()+ let host = GroupStore.hostname+ if siteMode != "missing" {+ let site = Site(hostname: host)+ site.mode = siteMode == "taught" ? .taught : .untaught+ store.context.insert(site)+ if siteMode == "taught" {+ store.context.insert(try TitlePattern(version: 1, isActive: true,+ createdAt: GroupStore.epoch, definition: .wholeTitle, site: site))+ }+ }+ let work = store.addWork(title: "Parsed title")+ let other = WorkSiteMembership(hostname: "other.example", createdAt: GroupStore.epoch,+ workURLString: profile == "bare" ? nil : "https://other.example/work", work: work)+ store.context.insert(other)+ store.context.insert(WorkSiteMembership(hostname: host,+ createdAt: GroupStore.epoch.addingTimeInterval(1),+ urlIdentity: "capture-identity", urlIdentityState: .legacyUnverified, work: work))+ switch profile {+ case "authored":+ work.displayTitle = "Reader title"+ work.genericNotes = "Exact reader prose e\u{301}"+ work.genreTags = ["fantasy", "fantasy", "serial"]+ work.workStatus = .hiatus; work.readingStatus = .abandoned+ work.verdict = " unfinished "+ case "configured", "removed":+ let type = WorkTypeEntity(name: "Webtoon",+ state: profile == "removed" ? .removed : .active,+ timestamp: GroupStore.epoch)+ store.context.insert(type); work.workTypeID = type.id+ case "unresolved": work.workTypeID = UUID()+ case "tolerated-status":+ work.workStatusRaw = "future-work-state"+ work.readingStatusRaw = "future-reading-state"+ case "publication":+ work.workStatus = .hiatus+ work.releaseDays = ReleaseDay.allCases+ let pauseStart = try #require(CivilDateCodec.parse("2026-09-20"))+ let returnDate = try #require(CivilDateCodec.parse("2026-09-30"))+ work.publicationStateData = try WorkPublicationState(status: .hiatus,+ currentPause: .init(start: pauseStart, returnDate: returnDate)).canonicalData()+ case "malformed-publication": work.publicationStateData = Data([0xFF, 0x00, 0x7B])+ default: break+ }+ if profile == "bare" {+ #expect(GroupOrdering.authoredContent(of: work, types: .empty).isBare)+ }+ try store.commit()+ // Retain the actual off-host primary relationship; it is an authored+ // content input in the old group, but not this site's matching identity.+ #expect(work.primaryMembership?.hostname == "other.example")+ let actual = try await store.captureBasisParity()+ #expect(actual.works.count == 1)+ #expect(actual.works.first?.id == work.id)+ #expect(actual.works.first?.hostnames == ["other.example", host])+ #expect(actual.composedWorks.first?.identity.value == ExactScalarString("capture-identity"))+ #expect(actual.siteMode == (siteMode == "taught" ? .taught : .untaught))+ #expect((actual.activePattern != nil) == (siteMode == "taught"))+ #expect((actual.currentTitleRule != nil) == (siteMode == "taught"))+ #expect(actual.currentURLRule == nil)+ }++ @Test("Singleton and split buckets retain authored carriers and off-host physical copies")+ func mixedPhysicalBuckets() async throws {+ let store = try GroupStore()+ let singleton = store.addWork(title: "Only row")+ store.context.insert(WorkSiteMembership(hostname: GroupStore.hostname, work: singleton))+ let mixedID = UUID()+ let bare = store.addWork(id: mixedID, title: "aaa parsed")+ let authored = store.addWork(id: mixedID, title: "zzz parsed", offset: 60)+ authored.displayTitle = "Reader title"; authored.genericNotes = "reader prose"+ store.context.insert(WorkSiteMembership(hostname: GroupStore.hostname,+ urlIdentity: "mixed", urlIdentityState: .legacyUnverified, work: bare))+ // This physical twin has NO target-host membership. hostnameWorks must+ // nevertheless include it before selecting the logical group's carrier.+ store.context.insert(WorkSiteMembership(hostname: "other.example", work: authored))+ let splitID = UUID()+ let first = store.addWork(id: splitID, title: "Equal rows")+ let twin = store.addWork(id: splitID, title: "Equal rows", offset: 60)+ store.context.insert(WorkSiteMembership(hostname: GroupStore.hostname, work: first))+ store.context.insert(WorkSiteMembership(hostname: GroupStore.hostname, work: twin))+ let tornID = UUID()+ let left = store.addWork(id: tornID, title: "Torn")+ let right = store.addWork(id: tornID, title: "Torn", offset: 60)+ left.genericNotes = "one"; right.genericNotes = "two"+ store.context.insert(WorkSiteMembership(hostname: GroupStore.hostname, work: left))+ store.context.insert(WorkSiteMembership(hostname: GroupStore.hostname, work: right))+ try store.commit()+ let group = try LibraryRepository.fetchWorkGroup(id: mixedID, context: store.context)+ #expect(group.representative === bare)+ #expect(group.carrier === authored)+ let actual = try await store.captureBasisParity()+ #expect(actual.works.count == 4)+ #expect(Set(actual.works.map(\.id)) == [singleton.id, mixedID, splitID, tornID])+ #expect(actual.composedWorks.count == 4)+ let mixed = try #require(actual.works.first { $0.id == mixedID })+ #expect(mixed.displayTitle == "Reader title")+ #expect(mixed.lastParsedTitle == authored.lastParsedTitle)+ #expect(mixed.createdAt == authored.createdAt)+ let composed = try #require(actual.composedWorks.first { $0.id == mixedID })+ #expect(composed.displayTitle == "Reader title")+ #expect(composed.lastParsedTitle == bare.lastParsedTitle)+ #expect(composed.identity.value == ExactScalarString("mixed"))+ #expect(try LibraryRepository.fetchWorkGroup(id: tornID, context: store.context).isTorn)+ }++ @Test("Membership relationship fallback, orphans and empty hostnames keep existing scope",+ arguments: ["fallback", "orphan", "empty"])+ func membershipEdges(shape: String) async throws {+ let store = try GroupStore()+ let work = store.addWork(title: "Membership edge")+ if shape == "fallback" {+ let membership = WorkSiteMembership(hostname: GroupStore.hostname, work: work)+ store.context.insert(membership)+ membership.workID = nil // the existing hostnameWorks relationship fallback+ } else if shape == "orphan" {+ store.context.insert(WorkSiteMembership(hostname: GroupStore.hostname, workID: work.id))+ }+ try store.commit()+ let actual = try await store.captureBasisParity()+ #expect(actual.works.map(\.id) == (shape == "fallback" ? [work.id] : []))+ if shape == "fallback" {+ // Preserve the existing grouped-membership behavior as well: nil+ // workID admits the Work via fallback but is not grouped by UUID.+ #expect(actual.works.first?.hostnames == [])+ let composed = try #require(actual.composedWorks.first)+ #expect(composed.identity == WorkIdentitySnapshot.none)+ }+ }++ @Test("Unquarantined invalid taught patterns still refuse before Work grouping",+ arguments: [0, 2, -1])+ func invalidTaughtPatterns(activeCount: Int) async throws {+ let store = try GroupStore()+ let site = Site(hostname: GroupStore.hostname); site.mode = .taught+ store.context.insert(site)+ let count = activeCount == -1 ? 1 : activeCount+ for index in 0..<count {+ let pattern = try TitlePattern(version: index + 1, isActive: true,+ createdAt: GroupStore.epoch.addingTimeInterval(Double(index)),+ definition: .wholeTitle, site: site)+ store.context.insert(pattern)+ if activeCount == -1 { pattern.definitionData = nil }+ }+ let work = store.addWork(title: "Only row")+ store.context.insert(WorkSiteMembership(hostname: GroupStore.hostname, work: work))+ try store.commit()+ do {+ _ = try await store.captureBasisParity()+ Issue.record("Invalid taught pattern unexpectedly produced a basis")+ } catch let error as LibraryRepositoryError {+ if activeCount >= 0 {+ guard case .corruptLibrary(let operation, let reason) = error else {+ Issue.record("Expected corruptLibrary, got \(error)"); return+ }+ #expect(operation == "building capture basis")+ #expect(reason.contains("has \(activeCount) active patterns (expected 1)"))+ } else {+ // withLockedContext retains its established framework-error wrapper.+ guard case .libraryUnavailable(let operation, _) = error else {+ Issue.record("Expected wrapped unreadable definition, got \(error)"); return+ }+ #expect(operation == "capture singleton parity")+ }+ }+ }++ @Test("Real validation quarantine keeps the original raw-row conservative basis")+ func quarantineRemainsRaw() async throws {+ let store = try GroupStore()+ let site = Site(hostname: GroupStore.hostname); site.mode = .taught+ store.context.insert(site) // zero patterns: existing QuarantineScopingTests fixture+ let id = UUID()+ for offset in [0.0, 60.0] {+ let work = store.addWork(id: id, title: "Quarantined", offset: offset)+ store.context.insert(WorkSiteMembership(hostname: GroupStore.hostname, work: work))+ }+ try store.commit()+ let actual = try await store.captureBasisParity(validateQuarantine: true)+ #expect(actual.siteMode == .untaught)+ #expect(actual.activePattern == nil)+ #expect(actual.currentTitleRule == nil)+ #expect(actual.currentURLRule == nil)+ #expect(actual.works.count == 2) // quarantine must NOT take the new grouping shortcut+ #expect(actual.works.map(\.id) == [id, id])+ #expect(actual.composedWorks.isEmpty)+ }+}++private extension GroupStore {+ func captureBasisParity(validateQuarantine: Bool = false) async throws -> CaptureBasis {+ let diagnostics = validateQuarantine+ ? try LibraryValidator.validate(context: context) : LibraryDiagnostics.empty+ if validateQuarantine { #expect(diagnostics.quarantineMap()[Self.hostname] != nil) }+ let repository = LibraryRepository(configuration: LibraryConfiguration(rootDirectory: directory),+ container: container, capabilities: .multiSite, clock: FixedRepositoryClock(Self.epoch),+ saveStrategy: ModelContextSaveStrategy(), quarantined: diagnostics.quarantineMap(),+ diagnostics: diagnostics)+ do {+ let basis = try await repository.captureBasisAgainstCompleteGroups(+ hostname: Self.hostname, quarantined: validateQuarantine)+ await repository.shutdown()+ return basis+ } catch {+ await repository.shutdown()+ throw error+ }+ }+}++private extension LibraryRepository {+ func captureBasisAgainstCompleteGroups(hostname: String, quarantined: Bool) async throws -> CaptureBasis {+ try await withLockedContext(mode: .shared, operation: "capture singleton parity") { context in+ let actual = try buildCaptureBasis(hostname: hostname, context: context)+ let onHostname = try Self.hostnameWorks(hostname: hostname, context: context)+ if quarantined {+ let original = onHostname.works.map {+ Self.workBasisEntry(from: $0, hostnames: onHostname.hostnames(of: $0))+ }.sorted { $0.id.uuidString < $1.id.uuidString }+ #expect(actual.works == original)+ } else {+ // Reference is the real complete grouping seam, not a second+ // implementation of the new singleton selector or entire basis.+ let groups = Self.workGroups(onHostname.works,+ types: try Self.workTypeDirectory(context: context)).values+ .sorted { $0.id.uuidString < $1.id.uuidString }+ let expectedWorks = groups.map {+ Self.workBasisEntry(from: $0.carrier, hostnames: onHostname.hostnames(of: $0.carrier))+ }+ let siteRules = try Self.fetchSites(hostname: hostname, context: context).first?.urlRuleValues ?? []+ let expectedComposed = groups.map {+ ComposedWorkBasis(id: $0.id, displayTitle: $0.carrier.displayTitle,+ lastParsedTitle: $0.representative.lastParsedTitle,+ titleProvenance: $0.carrier.titleProvenance,+ identity: Self.identitySnapshot(of: onHostname.memberships(of: $0.representative),+ hostname: hostname, fallbackRules: siteRules))+ }+ #expect(actual.works == expectedWorks)+ #expect(actual.composedWorks == expectedComposed)+ }+ return actual+ }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swiftindex 2dafe451..a0e7f60d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/GroupOrderingTests.swift@@ -938,12 +938,12 @@ private final class OrderingStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismGroupOrdering-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swiftindex 3d0e4a3b..d77bfc75 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/IdentityResolutionTests.swift@@ -284,12 +284,12 @@ private final class ResolutionStore { } private static func makeContainer(at directory: URL) throws -> ModelContainer {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryGraphBaselineTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryGraphBaselineTests.swiftindex f2fe1b47..bc6fafb1 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryGraphBaselineTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryGraphBaselineTests.swift@@ -301,12 +301,15 @@ extension LibraryRepository { let credits = try context.fetch(FetchDescriptor<WorkCredit>()) let places = try context.fetch(FetchDescriptor<Place>()) let placeSuppressions = try context.fetch(FetchDescriptor<PlaceSuppression>())+ let associationEvents = try context.fetch(FetchDescriptor<AssociationEvent>())+ let pairNoteVersions = try context.fetch(FetchDescriptor<PairNoteVersion>()) return LibraryGraphSerializer.dump( sites: sites, entries: entries, works: works, patterns: patterns, rules: rules, workTypes: workTypes, memberships: memberships, pairs: pairs, series: series, links: links, creators: creators, creatorRoles: creatorRoles, credits: credits,- places: places, placeSuppressions: placeSuppressions)+ places: places, placeSuppressions: placeSuppressions,+ associationEvents: associationEvents, pairNoteVersions: pairNoteVersions) } } }@@ -328,7 +331,8 @@ enum LibraryGraphSerializer { memberships: [WorkSiteMembership], pairs: [WorkDistinctPair], series: [Series], links: [WorkLink], creators: [Creator], creatorRoles: [CreatorRole], credits: [WorkCredit],- places: [Place], placeSuppressions: [PlaceSuppression]+ places: [Place], placeSuppressions: [PlaceSuppression],+ associationEvents: [AssociationEvent], pairNoteVersions: [PairNoteVersion] ) -> String { var lines: [String] = [ "# Asterism library graph baseline — Requirement 2.15",@@ -420,14 +424,16 @@ enum LibraryGraphSerializer { "# catchUpConfirmationData and lastChapterOverrideData after releaseDaysRaw.", "# Both optional blobs are nil on a converted V16 row; no entity or", "# relationship changes. Hand-edited into the recorded work line.",- "format 14",+ "# format 15 adds the two V21 feature tables; existing graph data is unchanged.",+ "format 15", "counts entries=\(entries.count) works=\(works.count) sites=\(sites.count) " + "titlePatterns=\(patterns.count) urlRulePatterns=\(rules.count) " + "workTypes=\(workTypes.count) memberships=\(memberships.count) " + "distinctPairs=\(pairs.count) series=\(series.count) links=\(links.count) " + "creators=\(creators.count) creatorRoles=\(creatorRoles.count) " + "credits=\(credits.count) places=\(places.count) "- + "placeSuppressions=\(placeSuppressions.count)",+ + "placeSuppressions=\(placeSuppressions.count) "+ + "associationEvents=\(associationEvents.count) pairNoteVersions=\(pairNoteVersions.count)", ] for site in sites.sorted(by: { $0.hostname < $1.hostname }) {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swiftindex 6bccaf00..c2ea4c5d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryToleranceScanTests.swift@@ -368,12 +368,12 @@ private final class ToleranceScanStore { } private static func makeContainer(at directory: URL) throws -> ModelContainer {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) return try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swiftindex ab1c9874..95362516 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/LibraryValidatorToleranceTests.swift@@ -447,12 +447,12 @@ private final class ValidatorStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismValidatorTolerance-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swiftindex 764cf92a..91155bb8 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/LookupFirstCaptureStateTests.swift@@ -388,7 +388,7 @@ private struct LookupCaptureFixture { _ seed: (ModelContext, String) -> Void ) throws -> LookupCaptureFixture { let url = "https://example.com/chapter-1"- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swiftindex 1e7f0b26..f2ddb75f 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerContractTests.swift@@ -71,12 +71,12 @@ struct MarkerContractTests { func appAcceptsTheCurrentMarkerVersion() async throws { let (_, cfg) = try config() try await makeReadyLibrary(cfg)- #expect(try markerContent(cfg) == "20",+ #expect(try markerContent(cfg) == "21", "an empty store has nothing to bring forward, so it is certified at birth (Q26)") let (current, _) = try await LibraryRepository.openForApp(cfg) #expect(current == .ready(.seededEmpty), "a certified library opens in the app")- #expect(try markerContent(cfg) == "20", "and the open leaves the marker as it found it")+ #expect(try markerContent(cfg) == "21", "and the open leaves the marker as it found it") } /// Req 4.4: the previous generation is *opened*, not refused — the stage@@ -92,7 +92,7 @@ struct MarkerContractTests { await repository.shutdown() #expect(result == .ready(.seededEmpty))- #expect(try markerContent(cfg) == "20",+ #expect(try markerContent(cfg) == "21", "the marker moves only after the converted store has validated") } @@ -138,7 +138,7 @@ struct MarkerContractTests { func extensionAcceptsTheCurrentVersion() async throws { let (_, cfg) = try config() try await makeReadyLibrary(cfg)- #expect(try markerContent(cfg) == "20")+ #expect(try markerContent(cfg) == "21") let (result, _) = try await LibraryRepository.openForExtension(cfg) #expect(result == .ready(.seededEmpty))@@ -207,9 +207,9 @@ struct MarkerContractTests { // Control: with a "17" marker the same store is reached, opened, and // converted. Without this the assertion above could hold because the // store was unopenable rather than because the marker was read first.- try writeMarker(cfg, "20\n")+ try writeMarker(cfg, "21\n") _ = try await LibraryRepository.openForExtension(cfg)- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["20.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: cfg.storeURL) == ["21.0.0"], "the same store converts once the marker check passes") }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swiftindex 976f4056..b5804366 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MarkerGenerationSeventeenTests.swift@@ -54,7 +54,7 @@ struct MarkerGenerationSeventeenTests { func seventeenIsReady() throws { let root = try Root() try root.seedV16Library()- try root.writeMarker("20\n")+ try root.writeMarker("21\n") #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready) withExtendedLifetime(root) {}@@ -101,9 +101,9 @@ struct MarkerGenerationSeventeenTests { } #expect(counts.works == 1) #expect(counts.entries == 3)- #expect(try root.markerText() == "20")+ #expect(try root.markerText() == "21") #expect(try V4RecordedStoreFixture.recordedModelVersions(at: root.configuration.storeURL)- == ["20.0.0"], "the store the arm opened is recorded at the version it converted to")+ == ["21.0.0"], "the store the arm opened is recorded at the version it converted to") let facts = try await repository.withLockedContext( mode: .shared, operation: "reading the converted library"@@ -144,7 +144,7 @@ struct MarkerGenerationSeventeenTests { Issue.record("expected a ready library, got \(result)") return }- #expect(try root.markerText() == "20")+ #expect(try root.markerText() == "21") withExtendedLifetime(root) {} } @@ -180,7 +180,7 @@ struct MarkerGenerationSeventeenTests { Issue.record("expected the retry to reach a ready library, got \(result)") return }- #expect(try root.markerText() == "20")+ #expect(try root.markerText() == "21") withExtendedLifetime(root) {} } @@ -217,7 +217,7 @@ struct MarkerGenerationSeventeenTests { Issue.record("a diagnosable library must still open, got \(result)") return }- #expect(try root.markerText() == "20")+ #expect(try root.markerText() == "21") #expect(quarantined != nil, "the broken title rule quarantines its hostname, as on V15") withExtendedLifetime(root) {} }@@ -299,7 +299,7 @@ struct MarkerGenerationSeventeenTests { try root.seedV16Library() let (_, repository) = try await LibraryRepository.openForApp(root.configuration) await repository.shutdown()- #expect(try root.markerText() == "20")+ #expect(try root.markerText() == "21") let (result, _) = try await LibraryRepository.openForExtension(root.configuration) guard case .ready = result else {
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swiftindex ba131288..9140dddb 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipReconcilerTests.swift@@ -1052,12 +1052,12 @@ private final class ReconcileStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismMembershipReconciler-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swiftindex adb3e363..639a2eae 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MembershipValidationTests.swift@@ -345,12 +345,12 @@ private final class MembershipStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismMembershipValidation-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swiftindex 61b385a9..b5c3ab6d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MirroringBootstrapLifecycleTests.swift@@ -126,7 +126,7 @@ struct MirroringBootstrapLifecycleTests { // container is constructed, the store is marked at the current // generation — so CloudKit cannot fill an unmarked store // (Req 6.1, Q22, Q35).- #expect(call.markerVersion == "20")+ #expect(call.markerVersion == "21") #expect(call.storeExists) #expect(call.containerID == Self.fixtureContainer) #expect(call.storeURL == configuration.storeURL)@@ -149,7 +149,7 @@ struct MirroringBootstrapLifecycleTests { mirroring: recordingHooks(configuration, log: log, bootstrapBox: bootstrapBox)) #expect(log.callCount == 1)- #expect(log.calls.first?.markerVersion == "20")+ #expect(log.calls.first?.markerVersion == "21") #expect(await repository.mirroring.isMirroring) // Q35/Q43 on this path too. The already-certified branch opens its own // certification container to run the validator over an existing marker,@@ -176,7 +176,7 @@ struct MirroringBootstrapLifecycleTests { #expect(result == .ready(LibraryRecordCounts( entries: 0, works: 0, sites: 1, titlePatterns: 0).withSeededWorkTypes))- #expect(log.calls.first?.markerVersion == "20")+ #expect(log.calls.first?.markerVersion == "21") #expect(await repository.mirroring.isMirroring) withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swiftindex b8a5aa6e..da159491 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ModelContractTests.swift@@ -219,7 +219,7 @@ struct ModelContractTests { func emptyLibraryPhasesCoverTheSchema() { let phased = Set( LibraryRepository.emptyLibraryPhases.flatMap { $0.entities.map(\.name) })- let declared = Set(AsterismSchemaV20.models.map { String(describing: $0) })+ let declared = Set(AsterismSchemaV21.models.map { String(describing: $0) }) #expect( phased == declared, """@@ -320,7 +320,7 @@ struct ModelContractTests { work.releaseDays = [.sunday, .monday, .sunday] #expect(work.releaseDaysRaw == ["monday", "sunday"], "the setter writes canonical order") - let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let entity = try #require(schema.entities.first { $0.name == "Work" }) #expect(entity.uniquenessConstraints.isEmpty, "Work declares a uniqueness constraint") let attributes = entity.properties.compactMap { $0 as? Schema.Attribute }@@ -374,7 +374,7 @@ struct ModelContractTests { #expect(work.thumbnailShape == nil) #expect(work.thumbnailIdentity == nil) - let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let entity = try #require(schema.entities.first { $0.name == "Work" }) #expect(entity.uniquenessConstraints.isEmpty, "Work declares a uniqueness constraint") // `properties` is `[any SchemaProperty]` and the relationships are in@@ -466,7 +466,7 @@ struct ModelContractTests { // The schema's own view: nothing unique, no relationship on either new // table, and the owner a column rather than a reference.- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) for name in ["Place", "PlaceSuppression"] { guard let entity = schema.entities.first(where: { $0.name == name }) else { Issue.record("the live schema has no \(name) entity")@@ -543,7 +543,7 @@ struct ModelContractTests { // The schema's own view: nothing unique, no relationships on any of the // three, and every foreign reference a column rather than a reference.- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) for name in ["Creator", "CreatorRole", "WorkCredit"] { guard let entity = schema.entities.first(where: { $0.name == name }) else { Issue.record("the live schema has no \(name) entity")@@ -584,7 +584,7 @@ struct ModelContractTests { // The schema's own view: nothing unique, no relationships on either new // table, and the two link ends are UUID columns rather than references.- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) for name in ["Series", "WorkLink"] { guard let entity = schema.entities.first(where: { $0.name == name }) else { Issue.record("the live schema has no \(name) entity")@@ -717,7 +717,7 @@ struct ModelContractTests { /// V8-era half of this pin needed an allowlist and this one does not. @Test("No dropped column is in the live schema") func droppedColumnsAreGoneFromTheSchema() {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) var propertiesByEntity: [String: Set<String>] = [:] for entity in schema.entities { propertiesByEntity[entity.name, default: []]@@ -798,7 +798,7 @@ struct ModelContractTests { #expect( declaringSnapshots.sorted() == [ "AsterismSchemaV16.swift", "AsterismSchemaV17.swift",- "AsterismSchemaV18.swift", "AsterismSchemaV19.swift", "AsterismSchemaV20.swift",+ "AsterismSchemaV18.swift", "AsterismSchemaV19.swift", "AsterismSchemaV20.swift", "AsterismSchemaV21.swift", ], """ the package declares versioned schemas in \(declaringSnapshots.sorted()); \@@ -1115,7 +1115,7 @@ private struct ModelFixture { /// The live schema, in memory. It was `AsterismSchemaV2` — a schema no /// library was written by, which is exactly the divergence Req 4.1 is about. init() throws {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: true,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swiftindex bb90ae1d..22897d3b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/MultiSiteReadPathTests.swift@@ -125,6 +125,8 @@ struct MultiSiteReadPathTests { // nothing, and nothing reads it — a snapshot carries stored columns // and no accessors at all. "AsterismSchemaV16.swift", "AsterismSchemaV17Models.swift", "AsterismSchemaV18Models.swift", "AsterismSchemaV19Models.swift",+ // Frozen V20 declares the same stored relationship/blob, with no live accessor.+ "AsterismSchemaV20Models.swift", // The reconcilers and the scan, which are *about* the membership // graph and read it whole per pass rather than per row. "DuplicateReconciler.swift", "DuplicateScan.swift", "MembershipReconciler.swift",@@ -208,12 +210,12 @@ private final class MembershipStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismMultiSiteRead-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeHistorySessionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeHistorySessionTests.swiftnew file mode 100644index 00000000..743e55a2--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeHistorySessionTests.swift@@ -0,0 +1,343 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("No-episode save-chunk history reuse", .serialized)+@MainActor+struct NoEpisodeHistorySessionTests {+ private func store() throws -> (ModelContainer, ModelContext) {+ let schema = Schema([NoEpisodeAction.self])+ let configuration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+ let container = try ModelContainer(for: schema, configurations: [configuration])+ let context = ModelContext(container)+ context.autosaveEnabled = false+ return (container, context)+ }+ private func fact(work: UUID = UUID(), entry: UUID = UUID()) -> NoEpisodeWriter.NoteFact {+ var calendar = Calendar(identifier: .gregorian)+ calendar.timeZone = TimeZone(secondsFromGMT: 0)!+ return .init(entryID: entry, workID: work, sharedAt: Date(timeIntervalSince1970: 0), calendar: calendar)+ }+ private func insert(_ action: NoEpisodeHistory.Action, into context: ModelContext) throws {+ context.insert(NoEpisodeAction(workID: action.workID, key: action.key, payloadData: try action.canonicalData()))+ }+ private func stable(_ fact: NoEpisodeWriter.NoteFact) throws -> NoEpisodeHistory.Action {+ try .init(workID: fact.workID, key: fact.stableKey, day: fact.day.description, kind: .clear, observedClearKeys: [])+ }+ private func mark(_ fact: NoEpisodeWriter.NoteFact, observed: [String]) throws -> NoEpisodeHistory.Action {+ try .init(workID: fact.workID, key: "mark/\(UUID().uuidString)", day: fact.day.description,+ kind: .mark, observedClearKeys: observed)+ }++ @Test("unrelated-day marks cannot change departure or returning stable clears", arguments: [false, true])+ func noMatchingDayMarkPreservesDepartureAndReturn(otherDayMark: Bool) throws {+ let (container, context) = try store(); defer { _ = container }+ let old = fact(), destination = fact()+ let oldStable = try stable(old)+ try insert(oldStable, into: context)+ let outside = fact()+ let outsideMark = try mark(outside, observed: [])+ try insert(outsideMark, into: context)+ if otherDayMark {+ try insert(.init(workID: old.workID, key: "mark/\(UUID().uuidString)",+ day: "1970-01-02", kind: .mark, observedClearKeys: []), into: context)+ }+ try context.save()+ let before = try NoEpisodeIndex(context: context).allActions+ let session = NoEpisodeWriter.HistorySession(context: context)+ #expect(try !session.record(before: [old], after: []))+ #expect(try NoEpisodeIndex(context: context).allActions == before)+ #expect(!context.hasChanges)+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == before.count)+ #expect(try session.record(before: [], after: [destination]))+ let destinationHistory = try NoEpisodeIndex(context: context).history(for: destination.workID)+ #expect(destinationHistory.actions.count == 2)+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == before.count + 2)+ #expect(destinationHistory.actions.contains(try stable(destination)))+ #expect(destinationHistory.actions.filter { $0.key.hasPrefix("clear/") && $0.day == destination.day.description }.count == 1)+ #expect(try session.record(before: [destination], after: [old]))+ let returned = try NoEpisodeIndex(context: context).history(for: old.workID)+ #expect(returned.actions.contains(oldStable))+ #expect(returned.actions.count == (otherDayMark ? 3 : 2))+ #expect(returned.actions.filter { $0.key.hasPrefix("clear/") && $0.day == old.day.description }.count == 1)+ #expect(!returned.isMarked(workID: old.workID, day: old.day.description))+ if otherDayMark { #expect(returned.isMarked(workID: old.workID, day: "1970-01-02")) }+ #expect(try NoEpisodeIndex(context: context).history(for: outside.workID).actions == [outsideMark])+ let allAfter = try NoEpisodeIndex(context: context).allActions+ let inserted = Set(allAfter).subtracting(before)+ #expect(inserted.count == 3)+ #expect(inserted.allSatisfy { $0.kind == .clear && $0.day == old.day.description })+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == before.count + 3)+ try context.save()+ let saved = try NoEpisodeIndex(context: context).allActions+ let fresh = NoEpisodeWriter.HistorySession(context: context)+ #expect(try !fresh.record(before: [old], after: [old]))+ #expect(try NoEpisodeIndex(context: context).allActions == saved)+ #expect(!context.hasChanges)+ }++ @Test("departure clears fully acknowledged same-day overlap but not partial acknowledgement", arguments: [false, true])+ func departurePreservesAcknowledgementPolicy(fullyAcknowledged: Bool) throws {+ let (container, context) = try store(); defer { _ = container }+ let a = fact(), b = fact(work: a.workID)+ let stableA = try stable(a), stableB = try stable(b)+ try insert(stableA, into: context); try insert(stableB, into: context)+ let acknowledgement = try mark(a, observed: fullyAcknowledged ? [a.stableKey, b.stableKey] : [a.stableKey])+ try insert(acknowledgement, into: context); try context.save()+ let original = try NoEpisodeIndex(context: context).history(for: a.workID)+ #expect(original.isMarked(workID: a.workID, day: a.day.description) == fullyAcknowledged)+ let session = NoEpisodeWriter.HistorySession(context: context)+ #expect(try session.record(before: [a, b], after: []) == fullyAcknowledged)+ let departed = try NoEpisodeIndex(context: context).history(for: a.workID)+ #expect(departed.actions.count == (fullyAcknowledged ? 4 : 3))+ #expect(departed.actions.contains(stableA) && departed.actions.contains(stableB))+ #expect(departed.actions.contains(acknowledgement))+ #expect(departed.actions.filter { $0.key.hasPrefix("clear/") && $0.day == a.day.description }.count == (fullyAcknowledged ? 1 : 0))+ #expect(!departed.isMarked(workID: a.workID, day: a.day.description))+ if !fullyAcknowledged { #expect(departed == original && !context.hasChanges) }+ #expect(try !session.record(before: [a, b], after: []))+ #expect(try NoEpisodeIndex(context: context).history(for: a.workID) == departed)+ }++ @Test("empty calls stay lazy; first nonempty call validates globally before writing")+ func lazyEmptyThenMalformed() throws {+ let (container, context) = try store(); defer { _ = container }+ context.insert(NoEpisodeAction(workID: UUID(), key: "invalid", payloadData: Data("broken".utf8)))+ try context.save()+ var reads = 0+ let session = NoEpisodeWriter.HistorySession(context: context, fetchRows: { context in+ reads += 1+ return try context.fetch(FetchDescriptor<NoEpisodeAction>())+ })+ #expect(try !session.record(before: [], after: []))+ #expect(reads == 0)+ let value = fact()+ #expect(throws: Error.self) { try session.record(before: [value], after: [value]) }+ #expect(reads == 1)+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == 1)+ #expect(!context.hasChanges)+ }++ @Test("pending stable and random clears are visible to the next unchanged transition", arguments: [false, true])+ func pendingClearsAndNoWrite(seedStable: Bool) throws {+ let (container, context) = try store(); defer { _ = container }+ let value = fact()+ if seedStable { try insert(stable(value), into: context) }+ try insert(mark(value, observed: [value.stableKey]), into: context)+ try context.save()+ var reads = 0+ let session = NoEpisodeWriter.HistorySession(context: context, fetchRows: { context in+ reads += 1+ return try context.fetch(FetchDescriptor<NoEpisodeAction>())+ })+ #expect(try session.record(before: [value], after: [value]))+ let afterFirst = try NoEpisodeIndex(context: context).history(for: value.workID)+ #expect(afterFirst.actions.count == 3)+ #expect(afterFirst.actions.filter { $0.key.hasPrefix("clear/") }.count == 1)+ #expect(try !session.record(before: [value], after: [value]))+ #expect(try NoEpisodeIndex(context: context).history(for: value.workID) == afterFirst)+ #expect(reads == 1)+ try context.save()+ #expect(!context.hasChanges)+ let fresh = NoEpisodeWriter.HistorySession(context: context)+ #expect(try !fresh.record(before: [value], after: [value]))+ #expect(!context.hasChanges)+ }++ @Test("new destination stable and fresh clears are not repeated in the same chunk")+ func repeatedNewDestination() throws {+ let (container, context) = try store(); defer { _ = container }+ let value = fact(), sibling = fact()+ let sameWorkSibling = fact(work: value.workID, entry: sibling.entryID)+ let session = NoEpisodeWriter.HistorySession(context: context)+ #expect(try session.record(before: [], after: [value, sameWorkSibling]))+ let history = try NoEpisodeIndex(context: context).history(for: value.workID)+ #expect(history.actions.count == 4)+ #expect(history.actions.filter { $0.key.hasPrefix("clear/") }.count == 2)+ #expect(try !session.record(before: [value, sameWorkSibling], after: [value, sameWorkSibling]))+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == 4)+ }++ @Test("mark acknowledgements of absent clear rows still enter clearKeys")+ func missingObservedClearStillPreventsOverlap() throws {+ let (container, context) = try store(); defer { _ = container }+ let value = fact(), unseen = "clear/\(UUID().uuidString)"+ try insert(stable(value), into: context)+ try insert(mark(value, observed: [value.stableKey]), into: context)+ try insert(mark(value, observed: [unseen]), into: context)+ try context.save()+ let session = NoEpisodeWriter.HistorySession(context: context)+ #expect(try !session.record(before: [value], after: [value]))+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == 3)+ #expect(!context.hasChanges)+ }++ @Test("identical copies fold but unrelated contradictory physical copies refuse globally")+ func duplicateCopiesAndGlobalConflict() throws {+ let (container, context) = try store(); defer { _ = container }+ let value = fact(), other = fact()+ let action = try stable(value)+ try insert(action, into: context); try insert(action, into: context)+ try insert(mark(other, observed: []), into: context)+ try context.save()+ let session = NoEpisodeWriter.HistorySession(context: context)+ #expect(try !session.record(before: [value], after: [value]))+ let otherRow = try #require(try context.fetch(FetchDescriptor<NoEpisodeAction>()).first { $0.workID == other.workID })+ let contradiction = try NoEpisodeHistory.Action(workID: other.workID, key: otherRow.key,+ day: "1970-01-02", kind: .mark, observedClearKeys: [])+ try insert(contradiction, into: context)+ session.invalidate()+ #expect(throws: NoEpisodeHistory.HistoryError.self) { try session.record(before: [value], after: [value]) }+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == 4)+ }++ @Test("Work history move updates physical pending rows and the next writer view")+ func movedHistoryIsCurrent() throws {+ let (container, context) = try store(); defer { _ = container }+ let old = fact(), destination = UUID()+ let moved = fact(work: destination, entry: old.entryID)+ let session = NoEpisodeWriter.HistorySession(context: context)+ #expect(try session.record(before: [], after: [old]))+ try session.repointActions(from: [old.workID], to: destination)+ let history = try NoEpisodeIndex(context: context).history(for: destination)+ #expect(history.actions.count == 2)+ #expect(try NoEpisodeIndex(context: context).history(for: old.workID).actions.isEmpty)+ #expect(try session.record(before: [moved], after: [moved]))+ #expect(try !session.record(before: [moved], after: [moved]))+ #expect(try NoEpisodeIndex(context: context).history(for: destination).actions.count == 3)+ #expect(try context.fetch(FetchDescriptor<NoEpisodeAction>()).allSatisfy { $0.workID == destination })+ }++ @Test("Work moves cannot hide newly coalesced contradictory action keys")+ func movedConflictRefusesNextTransition() throws {+ let (container, context) = try store(); defer { _ = container }+ let a = fact(), b = fact(), key = "mark/\(UUID().uuidString)"+ try insert(.init(workID: a.workID, key: key, day: "1970-01-01", kind: .mark, observedClearKeys: []), into: context)+ try insert(.init(workID: b.workID, key: key, day: "1970-01-02", kind: .mark, observedClearKeys: []), into: context)+ try context.save()+ let session = NoEpisodeWriter.HistorySession(context: context)+ #expect(try session.record(before: [a], after: [a]))+ try session.repointActions(from: [a.workID], to: b.workID)+ #expect(try !session.record(before: [], after: []))+ #expect(throws: NoEpisodeHistory.HistoryError.self) {+ try session.record(before: [b], after: [b])+ }+ }++ @Test("failed save rollback and fresh replay never reuse rolled-back pending clears")+ func failedSaveRollbackReplay() throws {+ let (container, context) = try store(); defer { _ = container }+ let value = fact()+ try insert(stable(value), into: context)+ try insert(mark(value, observed: [value.stableKey]), into: context)+ try context.save()+ do {+ let failed = NoEpisodeWriter.HistorySession(context: context)+ #expect(try failed.record(before: [value], after: [value]))+ try FailingSave().save(context)+ Issue.record("Expected injected save failure")+ } catch SaveFailure.expected {+ context.rollback()+ _ = try context.fetch(FetchDescriptor<NoEpisodeAction>())+ }+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == 2)+ let replay = NoEpisodeWriter.HistorySession(context: context)+ #expect(try replay.record(before: [value], after: [value]))+ try context.save()+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == 3)+ let afterSave = NoEpisodeWriter.HistorySession(context: context)+ #expect(try !afterSave.record(before: [value], after: [value]))+ #expect(!context.hasChanges)+ }++ @Test("fresh post-save session and explicit invalidation observe out-of-band writes")+ func resetAndFreshLifecycle() throws {+ let (container, context) = try store(); defer { _ = container }+ let value = fact()+ try insert(stable(value), into: context); try context.save()+ let first = NoEpisodeWriter.HistorySession(context: context)+ #expect(try !first.record(before: [value], after: [value]))+ try insert(mark(value, observed: [value.stableKey]), into: context)+ try context.save()+ let second = NoEpisodeWriter.HistorySession(context: context)+ #expect(try second.record(before: [value], after: [value]))+ try context.save()+ let third = NoEpisodeWriter.HistorySession(context: context)+ #expect(try !third.record(before: [value], after: [value]))+ #expect(!context.hasChanges)+ }+ @Test("raw Work move after empty calls preserves deferred validation", arguments: [false, true])+ func rawMoveDoesNotValidate(warm: Bool) throws {+ let (container, context) = try store(); defer { _ = container }+ let source = UUID(), destination = UUID(), value = fact()+ try insert(stable(value), into: context)+ try context.save()+ let session = NoEpisodeWriter.HistorySession(context: context)+ if warm { #expect(try !session.record(before: [value], after: [value])) }+ context.insert(NoEpisodeAction(workID: source, key: "broken", payloadData: Data("malformed".utf8)))+ // An external writer must invalidate both raw and decoded state.+ session.invalidate()+ #expect(try !session.record(before: [], after: []))+ try session.repointActions(from: [source], to: destination)+ #expect(try !session.record(before: [], after: []))+ try context.save()+ let moved = try #require(try context.fetch(FetchDescriptor<NoEpisodeAction>()).first { $0.key == "broken" })+ #expect(moved.workID == destination)+ #expect(moved.payloadData == Data("malformed".utf8))+ let fresh = NoEpisodeWriter.HistorySession(context: context)+ #expect(throws: Error.self) { try fresh.record(before: [value], after: [value]) }+ }++ @Test("actual failed deletion chunk refaults and replays without phantom history")+ func deletionChunkRollbackReplaysFreshHistory() throws {+ let failure = FailFirstDeletingSaveStrategy()+ let store = try DuplicateStore(saveStrategy: failure)+ let site = store.addSite()+ var works: [UUID] = []+ for index in 0..<2 {+ let work = store.addWork(title: "Distinct Work \(index)", createdAt: Double(index), site: site)+ works.append(work.id)+ for copy in 0..<2 {+ store.addEntry(key: "history-chapter-\(index)", capturedAt: Double(copy + 1),+ sharedAt: 10, note: "Saved note", work: work, site: site)+ }+ }+ try store.commit()+ _ = try store.reconcile()+ let outcome = try store.reconcile(afterDerivation: { context in+ let entries = try context.fetch(FetchDescriptor<Entry>())+ let facts = NoEpisodeWriter.facts(rows: entries, calendar: .current)+ let index = try NoEpisodeIndex(context: context)+ for workID in works {+ let value = try #require(facts.first { $0.workID == workID })+ let history = try index.history(for: workID)+ try insert(mark(value, observed: Array(history.clearKeys(workID: workID,+ day: value.day.description))), into: context)+ }+ })+ #expect(failure.hasFired)+ #expect(outcome.collapsedMembers == 2)+ #expect(outcome.settlingSetKeys.isEmpty)+ try store.read { context in+ #expect(try context.fetchCount(FetchDescriptor<Entry>()) == 2)+ let index = try NoEpisodeIndex(context: context)+ for workID in works {+ let history = try index.history(for: workID)+ let mark = try #require(history.actions.first { $0.kind == .mark })+ #expect(history.actions.filter { $0.key.hasPrefix("note/") }.count == 2)+ #expect(history.actions.filter { $0.key.hasPrefix("clear/") }.count == 1)+ #expect(!history.isMarked(workID: workID, day: mark.day))+ }+ }+ let count = try store.read { try $0.fetchCount(FetchDescriptor<NoEpisodeAction>()) }+ _ = try store.reconcile()+ #expect(try store.read { try $0.fetchCount(FetchDescriptor<NoEpisodeAction>()) } == count)+ withExtendedLifetime(store) {}+ }++ private enum SaveFailure: Error { case expected }+ private struct FailingSave: RepositorySaveStrategy {+ func save(_ context: ModelContext) throws { throw SaveFailure.expected }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeImportHistorySessionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeImportHistorySessionTests.swiftnew file mode 100644index 00000000..21f779f8--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeImportHistorySessionTests.swift@@ -0,0 +1,215 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("No-episode importer chunk history reuse", .serialized)+@MainActor+struct NoEpisodeImportHistorySessionTests {+ private let epoch = Date(timeIntervalSince1970: 1_000_000)+ private var calendar: Calendar {+ var value = Calendar(identifier: .gregorian)+ value.timeZone = TimeZone(secondsFromGMT: 0)!+ return value+ }+ private func store() throws -> (ModelContainer, ModelContext) {+ let schema = Schema(versionedSchema: AsterismSchemaV21.self)+ let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+ let container = try ModelContainer(for: schema, configurations: [config])+ let context = ModelContext(container); context.autosaveEnabled = false+ return (container, context)+ }+ private func payload(count: Int = 5, assignedIndices: Set<Int>? = nil) throws -> BackupImportPayload {+ let work = UUID(), hostname = "history-import.example"+ let entries = (0..<count).map { index in+ let url = "https://\(hostname)/chapter/\(index)"+ return BackupV18Entry(id: UUID(), captureTitle: "Chapter \(index)", captureTitleSource: .host,+ rawURL: url, canonicalURL: nil, hostname: hostname, entryIdentityKey: url,+ conservativeIdentityKey: url, identityBasis: .conservative, urlWorkIdentity: nil,+ chapterSequence: nil, chapterTitle: nil, note: "Saved note \(index)", rating: nil,+ firstCapturedAt: epoch, lastSharedAt: epoch, modifiedAt: epoch, workID: assignedIndices?.contains(index) == false ? nil : work,+ intentionallyUnattached: assignedIndices?.contains(index) == false,+ citations: EntryCitations(workAssignment: .manual))+ }+ let facts = entries.filter { $0.workID != nil }.map { NoEpisodeWriter.NoteFact(entryID: $0.id, workID: work,+ sharedAt: $0.lastSharedAt, calendar: calendar) }+ var actions = try facts.map { try NoEpisodeHistory.Action(workID: work, key: $0.stableKey,+ day: $0.day.description, kind: .clear, observedClearKeys: []) }+ actions.append(try .init(workID: work, key: "mark/\(UUID().uuidString)",+ day: facts[0].day.description, kind: .mark, observedClearKeys: facts.map(\.stableKey)))+ return BackupImportPayload(entries: entries,+ works: [.init(id: work, displayTitle: "History Work", lastParsedTitle: "History Work",+ genericNotes: "", genreTags: [], titleProvenance: .parsed, workStatus: .ongoing,+ readingStatus: .reading, verdict: "", releaseDays: [], workTypeID: nil, typeName: nil,+ createdAt: epoch, modifiedAt: epoch)],+ sites: [.init(hostname: hostname, displayName: hostname, mode: .untaught)],+ titlePatterns: [], urlRules: [],+ memberships: [.init(id: UUID(), workID: work, hostname: hostname, createdAt: epoch,+ urlIdentity: nil, urlIdentityState: .none, urlIdentityRuleID: nil, workURLString: nil)],+ noEpisodeActions: try actions.map(BackupV18NoEpisodeAction.init))+ }+ private final class Reads {+ var sessions = 0+ var fetches = 0+ func session(_ context: ModelContext) -> NoEpisodeWriter.HistorySession {+ sessions += 1+ return .init(context: context, fetchRows: { context in+ self.fetches += 1+ return try context.fetch(FetchDescriptor<NoEpisodeAction>())+ })+ }+ }+ private func apply(_ payload: BackupImportPayload, to context: ModelContext,+ save: any RepositorySaveStrategy = ModelContextSaveStrategy(), reads: Reads) throws {+ _ = try LibraryRepository.upsert(payload, exportedAt: epoch, importedAt: epoch,+ context: context, batchSize: 2, saveStrategy: save, noteCalendar: calendar,+ noteHistorySessionFactory: reads.session)+ }+ private func actionRows(_ context: ModelContext) throws -> [NoEpisodeAction] {+ try context.fetch(FetchDescriptor<NoEpisodeAction>())+ }++ @Test("actual new and existing Entry chunks share one lazy read while preserving every fresh clear")+ func pendingClearsImportedMarksAndUnchangedReplay() throws {+ let (container, context) = try store(); defer { _ = container }+ let input = try payload(), reads = Reads()+ try apply(input, to: context, reads: reads)+ #expect(reads.sessions == 3)+ #expect(reads.fetches == 3)+ let first = try actionRows(context)+ #expect(first.count == 11)+ #expect(first.filter { $0.key.hasPrefix("note/") }.count == 5)+ #expect(first.filter { $0.key.hasPrefix("clear/") }.count == 5)+ let history = try NoEpisodeIndex(context: context).history(for: input.works[0].id)+ #expect(!history.isMarked(workID: input.works[0].id, day: history.actions[0].day))+ let bodies = Set(first.map(\.payloadData))+ let replay = Reads()+ try apply(input, to: context, reads: replay)+ #expect(replay.sessions == 3)+ #expect(replay.fetches == 3)+ #expect(Set(try actionRows(context).map(\.payloadData)) == bodies)+ #expect(try actionRows(context).count == 11)+ #expect(!context.hasChanges)+ }++ @Test("unchanged existing facts still clear a mark acknowledging their current clears")+ func unchangedFactsOverlapStillClears() throws {+ let (container, context) = try store(); defer { _ = container }+ let input = try payload()+ try apply(input, to: context, reads: Reads())+ let work = input.works[0].id+ let history = try NoEpisodeIndex(context: context).history(for: work)+ let day = history.actions[0].day+ let mark = try NoEpisodeHistory.Action(workID: work, key: "mark/\(UUID().uuidString)",+ day: day, kind: .mark, observedClearKeys: Array(history.clearKeys(workID: work, day: day)))+ context.insert(NoEpisodeAction(workID: work, key: mark.key, payloadData: try mark.canonicalData()))+ try context.save()+ let reads = Reads()+ try apply(input, to: context, reads: reads)+ #expect(reads.fetches == 3)+ let after = try NoEpisodeIndex(context: context).history(for: work)+ #expect(after.actions.count == 13)+ #expect(after.actions.filter { $0.key.hasPrefix("clear/") }.count == 6)+ #expect(!after.isMarked(workID: work, day: day))+ #expect(!context.hasChanges)+ }++ @Test("empty chunks remain lazy after corruption; the next nonempty chunk refuses globally")+ func emptyChunkDoesNotDecodeNewCorruption() throws {+ let (container, context) = try store(); defer { _ = container }+ let reads = Reads(), save = EntryBoundarySave(corruptAfterEntryCount: 2)+ #expect(throws: NoEpisodeHistory.HistoryError.self) {+ try apply(payload(assignedIndices: [4]), to: context, save: save, reads: reads)+ }+ #expect(save.fired)+ #expect(reads.sessions == 3)+ #expect(reads.fetches == 1)+ context.rollback()+ let fresh = ModelContext(container); fresh.autosaveEnabled = false+ #expect(try fresh.fetchCount(FetchDescriptor<Entry>()) == 4)+ #expect(try actionRows(fresh).count == 4)+ #expect(try actionRows(fresh).allSatisfy { !$0.key.hasPrefix("clear/") })+ }++ @Test("upfront global union refuses unrelated physical contradictions before chunk writes")+ func globalConflictRefusesBeforeEntries() throws {+ let (container, context) = try store(); defer { _ = container }+ let work = UUID(), key = "mark/\(UUID().uuidString)"+ for day in ["2000-01-01", "2000-01-02"] {+ let value = try NoEpisodeHistory.Action(workID: work, key: key, day: day,+ kind: .mark, observedClearKeys: [])+ context.insert(NoEpisodeAction(workID: work, key: key, payloadData: try value.canonicalData()))+ }+ try context.save()+ let reads = Reads()+ #expect(throws: NoEpisodeHistory.HistoryError.self) { try apply(payload(), to: context, reads: reads) }+ #expect(reads.sessions == 0)+ #expect(try context.fetchCount(FetchDescriptor<Entry>()) == 0)+ #expect(try actionRows(context).count == 2)+ #expect(!context.hasChanges)+ }++ @Test("second Entry chunk failure rolls back pending history and retry starts fresh")+ func secondChunkFailureAndRetry() throws {+ let (container, context) = try store(); defer { _ = container }+ let input = try payload(count: 4), reads = Reads()+ let save = EntryBoundarySave(failAtEntryCount: 4)+ #expect(throws: SaveFailure.self) { try apply(input, to: context, save: save, reads: reads) }+ #expect(save.fired)+ context.rollback()+ let fresh = ModelContext(container); fresh.autosaveEnabled = false+ #expect(try fresh.fetchCount(FetchDescriptor<Entry>()) == 2)+ #expect(try actionRows(fresh).count == 7)+ let replay = Reads()+ try apply(input, to: fresh, reads: replay)+ #expect(replay.sessions == 2)+ #expect(replay.fetches == 2)+ #expect(try fresh.fetchCount(FetchDescriptor<Entry>()) == 4)+ #expect(try actionRows(fresh).count == 9)+ #expect(try actionRows(fresh).filter { $0.key.hasPrefix("clear/") }.count == 4)+ #expect(!fresh.hasChanges)+ }++ @Test("a new global conflict committed between Entry chunks is seen by the next chunk")+ func betweenChunkCorruptionIsNotCachedAway() throws {+ let (container, context) = try store(); defer { _ = container }+ let reads = Reads(), save = EntryBoundarySave(corruptAfterEntryCount: 2)+ #expect(throws: NoEpisodeHistory.HistoryError.self) {+ try apply(payload(), to: context, save: save, reads: reads)+ }+ #expect(save.fired)+ #expect(reads.sessions == 2)+ #expect(reads.fetches == 2)+ context.rollback()+ let fresh = ModelContext(container); fresh.autosaveEnabled = false+ #expect(try fresh.fetchCount(FetchDescriptor<Entry>()) == 2)+ #expect(try actionRows(fresh).count == 10)+ #expect(try actionRows(fresh).filter { $0.key.hasPrefix("clear/") }.count == 2)+ }++ private enum SaveFailure: Error { case expected }+ private final class EntryBoundarySave: RepositorySaveStrategy, @unchecked Sendable {+ let failAtEntryCount: Int?+ let corruptAfterEntryCount: Int?+ var fired = false+ init(failAtEntryCount: Int? = nil, corruptAfterEntryCount: Int? = nil) {+ self.failAtEntryCount = failAtEntryCount+ self.corruptAfterEntryCount = corruptAfterEntryCount+ }+ func save(_ context: ModelContext) throws {+ let count = try context.fetchCount(FetchDescriptor<Entry>())+ if !fired, count == failAtEntryCount { fired = true; throw SaveFailure.expected }+ try context.save()+ if !fired, count == corruptAfterEntryCount {+ fired = true+ let work = UUID(), key = "mark/\(UUID().uuidString)"+ for day in ["2000-01-01", "2000-01-02"] {+ let action = try NoEpisodeHistory.Action(workID: work, key: key, day: day,+ kind: .mark, observedClearKeys: [])+ context.insert(NoEpisodeAction(workID: work, key: key, payloadData: try action.canonicalData()))+ }+ try context.save()+ }+ }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRawRowBucketTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRawRowBucketTests.swiftnew file mode 100644index 00000000..add4a7ff--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeRawRowBucketTests.swift@@ -0,0 +1,139 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("No-episode raw-row Work inventory", .serialized)+@MainActor+struct NoEpisodeRawRowBucketTests {+ private func store() throws -> (ModelContainer, ModelContext) {+ let schema = Schema([NoEpisodeAction.self])+ let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+ let container = try ModelContainer(for: schema, configurations: [config])+ let context = ModelContext(container); context.autosaveEnabled = false+ return (container, context)+ }+ @discardableResult+ private func add(_ work: UUID, to context: ModelContext, key: String? = nil,+ day: String = "2000-01-01") throws -> NoEpisodeAction {+ let action = try NoEpisodeHistory.Action(workID: work, key: key ?? "mark/\(UUID().uuidString)",+ day: day, kind: .mark, observedClearKeys: [])+ let row = NoEpisodeAction(workID: work, key: action.key, payloadData: try action.canonicalData())+ context.insert(row)+ return row+ }+ private func fact(_ work: UUID) -> NoEpisodeWriter.NoteFact {+ var calendar = Calendar(identifier: .gregorian); calendar.timeZone = TimeZone(secondsFromGMT: 0)!+ return .init(entryID: UUID(), workID: work, sharedAt: Date(timeIntervalSince1970: 0), calendar: calendar)+ }++ @Test("selected chained moves read all raw owners once and retain identical physical copies")+ func repeatedMovesAvoidUnrelatedOwnerTraversal() throws {+ let (container, context) = try store(); defer { _ = container }+ let a = UUID(), b = UUID(), c = UUID()+ let duplicate = "mark/\(UUID().uuidString)"+ try add(a, to: context, key: duplicate); try add(a, to: context, key: duplicate)+ try add(b, to: context); try add(c, to: context)+ for _ in 0..<20 { try add(UUID(), to: context) }+ try context.save()+ let before = try context.fetch(FetchDescriptor<NoEpisodeAction>()).map(\.payloadData)+ var reads = 0, fetches = 0+ let session = NoEpisodeWriter.HistorySession(context: context, fetchRows: {+ fetches += 1; return try $0.fetch(FetchDescriptor<NoEpisodeAction>())+ }, rawWorkID: { reads += 1; return $0.workID })+ try session.repointActions(from: [a], to: b)+ #expect(reads == 24)+ try session.repointActions(from: [b, c], to: c)+ try session.repointActions(from: [a, c], to: c)+ #expect(reads == 24)+ #expect(fetches == 1)+ let rows = try context.fetch(FetchDescriptor<NoEpisodeAction>())+ #expect(rows.count == 24)+ #expect(rows.filter { $0.workID == c }.count == 4)+ #expect(rows.allSatisfy { $0.workID != a && $0.workID != b })+ #expect(rows.map(\.payloadData).sorted(by: { $0.lexicographicallyPrecedes($1) })+ == before.sorted(by: { $0.lexicographicallyPrecedes($1) }))+ }++ @Test("record-only sessions never build the raw repoint owner inventory")+ func recordOnlyAvoidsRawOwnerTraversal() throws {+ let (container, context) = try store(); defer { _ = container }+ for _ in 0..<20 { try add(UUID(), to: context) }+ try context.save()+ var reads = 0, fetches = 0+ let value = fact(UUID())+ let session = NoEpisodeWriter.HistorySession(context: context, fetchRows: {+ fetches += 1; return try $0.fetch(FetchDescriptor<NoEpisodeAction>())+ }, rawWorkID: { reads += 1; return $0.workID })+ #expect(try session.record(before: [], after: [value]))+ #expect(try !session.record(before: [value], after: [value]))+ #expect(reads == 0)+ #expect(fetches == 1)+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == 22)+ }++ @Test("pending stable and random clears join the raw inventory before chained moves")+ func pendingInsertionsFollowMoves() throws {+ let (container, context) = try store(); defer { _ = container }+ for _ in 0..<20 { try add(UUID(), to: context) }+ try context.save()+ let a = UUID(), b = UUID(), c = UUID(), value = fact(a)+ var reads = 0+ let session = NoEpisodeWriter.HistorySession(context: context, rawWorkID: { reads += 1; return $0.workID })+ #expect(try session.record(before: [], after: [value]))+ #expect(reads == 0)+ try session.repointActions(from: [a], to: b)+ #expect(try session.record(before: [], after: [fact(b)]))+ try session.repointActions(from: [b, c], to: c)+ #expect(reads == 22)+ let rows = try context.fetch(FetchDescriptor<NoEpisodeAction>())+ #expect(rows.count == 24)+ #expect(rows.filter { $0.workID == c }.count == 4)+ #expect(rows.allSatisfy { $0.workID != a && $0.workID != b })+ #expect(try NoEpisodeIndex(context: context).history(for: c).actions.count == 4)+ }++ @Test("external invalidation reloads changed owners and new physical arrivals")+ func invalidateRefreshesRawBuckets() throws {+ let (container, context) = try store(); defer { _ = container }+ let a = UUID(), b = UUID(), c = UUID()+ let row = try add(a, to: context)+ try context.save()+ var reads = 0, fetches = 0+ let session = NoEpisodeWriter.HistorySession(context: context, fetchRows: {+ fetches += 1; return try $0.fetch(FetchDescriptor<NoEpisodeAction>())+ }, rawWorkID: { reads += 1; return $0.workID })+ try session.repointActions(from: [a], to: b)+ row.workID = a+ try add(a, to: context)+ session.invalidate()+ #expect(try !session.record(before: [], after: []))+ #expect(fetches == 1)+ try session.repointActions(from: [a], to: c)+ #expect(fetches == 2)+ #expect(reads == 3)+ #expect(try context.fetch(FetchDescriptor<NoEpisodeAction>()).allSatisfy { $0.workID == c })+ }++ @Test("raw destination conflicts preserve every copy and refuse only at the next nonempty read", arguments: [false, true])+ func rawMoveDefersGlobalConflictValidation(includeMalformed: Bool) throws {+ let (container, context) = try store(); defer { _ = container }+ let a = UUID(), b = UUID(), key = "mark/\(UUID().uuidString)"+ try add(a, to: context, key: key, day: "2000-01-01")+ try add(b, to: context, key: key, day: "2000-01-02")+ let malformed = NoEpisodeAction(workID: UUID(), key: "broken", payloadData: Data("broken".utf8))+ if includeMalformed { context.insert(malformed) }+ try context.save()+ var reads = 0+ let session = NoEpisodeWriter.HistorySession(context: context, rawWorkID: { reads += 1; return $0.workID })+ #expect(try !session.record(before: [], after: []))+ #expect(reads == 0)+ try session.repointActions(from: [a, b], to: b)+ #expect(reads == (includeMalformed ? 3 : 2))+ #expect(try context.fetch(FetchDescriptor<NoEpisodeAction>()).filter { $0.workID == b }.count == 2)+ #expect(try !session.record(before: [], after: []))+ #expect(throws: Error.self) { try session.record(before: [fact(b)], after: []) }+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == (includeMalformed ? 3 : 2))+ #expect(malformed.payloadData == Data("broken".utf8))+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swiftindex 37c306b1..d5ab7af7 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/NoEpisodeStorageTests.swift@@ -27,7 +27,7 @@ struct NoEpisodeStorageTests { func indexAndRestart() throws { let url = FileManager.default.temporaryDirectory.appending(path: "NoEpisodeStorage-\(UUID())") defer { try? FileManager.default.removeItem(at: url) }- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let config = ModelConfiguration(schema: schema, url: url) let workID = UUID() let action = try NoEpisodeHistory.Action(workID: workID, key: "mark/\(UUID().uuidString)",@@ -69,7 +69,7 @@ struct NoEpisodeStorageTests { @Test("an unrelated damaged action does not break a targeted history read") func malformedActionIsScopedToItsWork() throws {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let container = try ModelContainer( for: schema, configurations: [ModelConfiguration(isStoredInMemoryOnly: true)]) let context = ModelContext(container)
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/PerformanceReadReuseTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/PerformanceReadReuseTests.swiftnew file mode 100644index 00000000..229fa3d1--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/PerformanceReadReuseTests.swift@@ -0,0 +1,192 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Operation-local decoder and deletion source inventories", .serialized)+@MainActor+struct PerformanceReadReuseTests {+ private func store() throws -> (ModelContainer, ModelContext) {+ let schema = Schema([EntrySource.self])+ let container = try ModelContainer(for: schema, configurations: [+ ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+ ])+ let context = ModelContext(container)+ context.autosaveEnabled = false+ return (container, context)+ }+ private func source(_ id: UUID) -> EntrySource {+ EntrySource(entryID: id, urlString: "https://fixture.invalid/chapter", hostname: "fixture.invalid",+ timestamp: Date(timeIntervalSince1970: 0))+ }++ @Test("a reused decoder validates each payload and recovers after invalid input",+ arguments: ["json", "version", "day", "key", "acknowledgement", "kind"])+ func reusedDecoderRejectsThenRecovers(fault: String) throws {+ let workID = UUID(), otherWorkID = UUID()+ let valid = try NoEpisodeHistory.Action(workID: workID, key: "clear/\(UUID().uuidString)",+ day: "1970-01-01", kind: .clear, observedClearKeys: [])+ let data = try valid.canonicalData()+ var wire = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])+ switch fault {+ case "version": wire["version"] = 2+ case "day": wire["day"] = "1970-02-30"+ case "key": wire["key"] = "clear/invalid"+ case "acknowledgement": wire["observedClearKeys"] = ["clear/\(UUID().uuidString)"]+ case "kind": wire["kind"] = "unknown"+ default: break+ }+ let broken: Data+ if fault == "json" { broken = Data("broken".utf8) }+ else { broken = try JSONSerialization.data(withJSONObject: wire) }+ let decoder = JSONDecoder()+ #expect(throws: Error.self) {+ try NoEpisodeHistory.Action.decode(broken, workID: workID, decoder: decoder)+ }+ #expect(try NoEpisodeHistory.Action.decode(data, workID: workID, decoder: decoder) == valid)+ let moved = try NoEpisodeHistory.Action.decode(data, workID: otherWorkID, decoder: decoder)+ #expect(moved.workID == otherWorkID)+ #expect(moved.key == valid.key && moved.day == valid.day && moved.kind == valid.kind)+ }++ @Test("one chunk reads all pending or saved physical source rows once", arguments: [false, true])+ func sourcePresenceReadsOnce(saved: Bool) throws {+ let (container, context) = try store(); defer { _ = container }+ let target = UUID(), absent = UUID()+ context.insert(source(target)); context.insert(source(target))+ if saved { try context.save() }+ var reads = 0+ var inventory = DuplicateReconciler.EntrySourceInventory()+ let fetch: (ModelContext) throws -> [EntrySource] = { context in+ reads += 1+ return try context.fetch(FetchDescriptor<EntrySource>())+ }+ #expect(try inventory.contains(any: [target], context: context, fetchRows: fetch))+ #expect(try !inventory.contains(any: [absent], context: context, fetchRows: fetch))+ #expect(reads == 1)+ #expect(try context.fetchCount(FetchDescriptor<EntrySource>()) == 2)+ }++ @Test("a combine invalidation observes pending source insertions and repoints")+ func invalidationReadsCurrentPendingRows() throws {+ let (container, context) = try store(); defer { _ = container }+ let old = UUID(), moved = UUID(), inserted = UUID()+ let row = source(old); context.insert(row); try context.save()+ var reads = 0+ let fetch: (ModelContext) throws -> [EntrySource] = { context in+ reads += 1+ return try context.fetch(FetchDescriptor<EntrySource>())+ }+ var inventory = DuplicateReconciler.EntrySourceInventory()+ #expect(try inventory.contains(any: [old], context: context, fetchRows: fetch))+ row.entryID = moved; context.insert(source(inserted))+ inventory.invalidate()+ #expect(try !inventory.contains(any: [old], context: context, fetchRows: fetch))+ #expect(try inventory.contains(any: [moved], context: context, fetchRows: fetch))+ #expect(try inventory.contains(any: [inserted], context: context, fetchRows: fetch))+ #expect(reads == 2)+ var replay = DuplicateReconciler.EntrySourceInventory()+ #expect(try replay.contains(any: [inserted], context: context, fetchRows: fetch))+ #expect(reads == 3)+ }++ @Test("failed source reads cannot populate a partial inventory")+ func throwingReadDoesNotPoisonInventory() throws {+ let (container, context) = try store(); defer { _ = container }+ let target = UUID(); context.insert(source(target))+ enum Failure: Error { case injected }+ var inventory = DuplicateReconciler.EntrySourceInventory()+ #expect(throws: Failure.self) {+ try inventory.contains(any: [target], context: context, fetchRows: { _ in throw Failure.injected })+ }+ #expect(try inventory.contains(any: [target], context: context))+ }+}++@Suite("Deletion source inventory integration", .serialized)+@MainActor+struct PerformanceReadReuseIntegrationTests {+ @Test("mixed multi-plan source redirects and deletion survive chunk replay", arguments: [false, true])+ func mixedSourcesAndReplay(failChunk: Bool) throws {+ let failure = FailFirstDeletingSaveStrategy()+ let store = try DuplicateStore(saveStrategy: failChunk ? failure : nil)+ let site = store.addSite()+ var retained: [(survivor: UUID, loser: UUID, url: String, sourceIDs: Set<UUID>, evidence: Data)] = []+ var deletedLoser: UUID?+ for index in 0..<3 {+ let survivor = store.addEntry(id: DuplicateStore.rankedID(index * 2), key: "source-chunk-\(index)",+ capturedAt: TimeInterval(index), site: site)+ let loser = store.addEntry(id: DuplicateStore.rankedID(index * 2 + 1), key: "source-chunk-\(index)",+ capturedAt: TimeInterval(index) + 50, site: site)+ if index == 1 { deletedLoser = loser.id; continue }+ let url = "https://\(DuplicateStore.hostname)/source-\(index)"+ let evidence = try EntrySourceEvidence(confirmed: [+ .init(origin: .v2, key: "source-evidence-\(index)", ruleID: UUID())+ ]).encoded()+ let ids = Set([UUID(), UUID()])+ for id in ids {+ store.seed.insert(EntrySource(id: id, entryID: loser.id, urlString: url,+ hostname: DuplicateStore.hostname, timestamp: DuplicateStore.epoch, evidenceData: evidence))+ }+ retained.append((survivor.id, loser.id, url, ids, evidence))+ }+ try store.commit()+ _ = try store.reconcile()+ let settled = try store.reconcile()+ #expect(settled.collapsedMembers == 3)+ #expect(settled.settlingSetKeys.isEmpty)+ #expect(failure.hasFired == failChunk)+ let ordinaryLoser = try #require(deletedLoser)+ try store.read { context in+ let entries = try context.fetch(FetchDescriptor<Entry>())+ #expect(entries.count == 5)+ #expect(!entries.contains { $0.id == ordinaryLoser })+ let sources = try context.fetch(FetchDescriptor<EntrySource>())+ let index = try EntrySourceIndex(context: context)+ for expected in retained {+ #expect(index.destination(of: expected.loser) == expected.survivor)+ #expect(!index.hasUnresolvedContent(for: expected.survivor))+ #expect(index.urls(for: expected.survivor).contains(expected.url))+ let original = sources.filter { expected.sourceIDs.contains($0.id) }+ #expect(original.count == 2)+ #expect(Set(original.map(\.id)) == expected.sourceIDs)+ #expect(original.allSatisfy { $0.entryID == expected.survivor && $0.urlString == expected.url+ && $0.evidenceData == expected.evidence })+ #expect(sources.filter { $0.urlString == expected.url }.count == 2)+ }+ }+ }++ @Test("pending deletion and a fresh post-rollback inventory use current physical rows")+ func pendingDeletionAndRollback() throws {+ let store = try DuplicateStore()+ let old = UUID(), removed = UUID(), moved = UUID(), inserted = UUID()+ let original = EntrySource(entryID: old, urlString: "https://fixture.invalid/a", hostname: "fixture.invalid",+ timestamp: DuplicateStore.epoch)+ let deletion = EntrySource(entryID: removed, urlString: "https://fixture.invalid/b", hostname: "fixture.invalid",+ timestamp: DuplicateStore.epoch)+ store.seed.insert(original); store.seed.insert(deletion); try store.commit()+ var inventory = DuplicateReconciler.EntrySourceInventory()+ #expect(try inventory.contains(any: [old], context: store.seed))+ original.entryID = moved+ store.seed.delete(deletion)+ store.seed.insert(EntrySource(entryID: inserted, urlString: "https://fixture.invalid/c", hostname: "fixture.invalid",+ timestamp: DuplicateStore.epoch))+ inventory.invalidate()+ #expect(try inventory.contains(any: [moved], context: store.seed))+ #expect(try inventory.contains(any: [inserted], context: store.seed))+ #expect(try !inventory.contains(any: [removed], context: store.seed))+ store.seed.rollback()+ try store.read { fresh in+ var replay = DuplicateReconciler.EntrySourceInventory()+ let hasOld = try replay.contains(any: [old], context: fresh)+ let hasRemoved = try replay.contains(any: [removed], context: fresh)+ let hasUncommitted = try replay.contains(any: [moved, inserted], context: fresh)+ let physicalCount = try fresh.fetchCount(FetchDescriptor<EntrySource>())+ #expect(hasOld)+ #expect(hasRemoved)+ #expect(!hasUncommitted)+ #expect(physicalCount == 2)+ }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RecognisedCharacterLinkTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RecognisedCharacterLinkTests.swiftnew file mode 100644index 00000000..3efe6510--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RecognisedCharacterLinkTests.swift@@ -0,0 +1,308 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Recognised character background authority", .serialized)+struct RecognisedCharacterLinkTests {+ private struct IDs: Sendable { let work = UUID(), entry = UUID(), character = UUID() }+ private final class SwitchSave: RepositorySaveStrategy, @unchecked Sendable {+ private let lock = NSLock()+ private var fail = false+ func arm() { lock.withLock { fail = true } }+ func save(_ context: ModelContext) throws {+ let failure = lock.withLock { let value = fail; fail = false; return value }+ if failure { throw CocoaError(.fileWriteUnknown) }+ try context.save()+ }+ }+ private func fixture(tier: Int = 0, chapter: Bool = true, save: any RepositorySaveStrategy = ModelContextSaveStrategy()) async throws -> (M5Fixture, IDs) {+ let fixture = try await M5Fixture(saveStrategy: save), ids = IDs()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding recognised character") { context in+ let work = Work(id: ids.work, displayTitle: "Synthetic recognised Work", timestamp: M5Fixture.epoch)+ let entry = Entry(id: ids.entry, captureTitle: "Synthetic chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Ada enters.")+ try entry.authorTarget(.init(kind: chapter ? .chapter : .note))+ context.insert(work); context.insert(entry); entry.work = work+ LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch)+ context.insert(CharacterRecord(id: ids.character, name: tier == 0 ? "Ada" : "Adaline",+ nameKey: tier == 1 ? "ada" : "adaline", aliases: tier == 0 ? [] : ["Ada"], work: work))+ try context.save()+ }+ return (fixture, ids)+ }+ private func candidate(_ fixture: M5Fixture, _ ids: IDs) async throws -> ExtractionCandidate {+ try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ }+ private func request(_ fixture: M5Fixture, _ ids: IDs, originalKind: RecordKind = .character) async throws -> DecisionRequest {+ let candidate = try await candidate(fixture, ids)+ let source = try #require(candidate.sources.first { $0.ref == .entry(ids.entry) })+ return .init(workID: ids.work, action: .accept, displayedKeys: ["ada"], displayedTargetID: ids.character,+ proposedName: "Ada", completedSources: [source.completedSource],+ mentions: source.isChapter ? [.init(entryID: ids.entry, noteFingerprint: source.fingerprint,+ spellingKeys: ["ada"], observedRejectionIDs: candidate.mentionIndex.rejectionIDs(entryID: ids.entry, kind: .character, recordID: ids.character, spellingKeys: ["ada"]),+ sourceGuard: candidate.mentionIndex.sourceGuards[ids.entry])] : [],+ reviewedKey: .init(kind: originalKind, nameKey: "ada"), requiresCurrentSources: true)+ }++ @Test("Current name, retained key and accepted alias save one link without enrichment", arguments: [0, 1, 2])+ func recognisedTiersAreIdempotent(tier: Int) async throws {+ let (fixture, ids) = try await fixture(tier: tier)+ let before = try await fixture.repository.backupV20Snapshot()+ let input = try await request(fixture, ids)+ #expect(try await fixture.repository.commitRecognisedCharacter(input) == .committed(recordID: ids.character))+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry).filter { !$0.activeAcceptanceIDs.isEmpty }.count == 1)+ let once = try await fixture.repository.backupV20Snapshot()+ #expect(once.library.characters == before.library.characters)+ #expect(once.pairNoteVersions == before.pairNoteVersions)+ #expect(try await fixture.repository.commitRecognisedCharacter(input) == .committed(recordID: ids.character))+ #expect(try await fixture.repository.backupV20Snapshot() == once)+ withExtendedLifetime(fixture) {}+ }++ @Test("Ties, source changes and changed targets never silently reroute", arguments: [0, 1, 2, 3])+ func racesRefuseWithoutMutation(mode: Int) async throws {+ let (fixture, ids) = try await fixture()+ let input = try await request(fixture, ids)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "simulating recognition race") { context in+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first)+ if mode == 0 { context.insert(CharacterRecord(name: "Ada", nameKey: "ada", work: work)) }+ if mode == 1 { try #require(try context.fetch(FetchDescriptor<Entry>()).first).note = "Ada leaves." }+ if mode == 2 { try #require(try context.fetch(FetchDescriptor<CharacterRecord>()).first).name = "Cora" }+ if mode == 3 {+ let other = Work(displayTitle: "Other Work", timestamp: M5Fixture.epoch); context.insert(other)+ context.insert(CharacterRecord(id: ids.character, name: "Ada", nameKey: "ada", work: other))+ }+ try context.save()+ }+ let before = try await fixture.repository.backupV20Snapshot()+ if case .refused = try await fixture.repository.commitRecognisedCharacter(input) {} else { Issue.record("Expected guarded refusal") }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }++ @Test func existingRejectionCannotBeReconsideredByBackgroundCommit() async throws {+ let (fixture, ids) = try await fixture()+ var skipped = try await request(fixture, ids); skipped.action = .skip+ #expect(try await fixture.repository.commitDecision(skipped) == .committed(recordID: nil))+ let before = try await fixture.repository.backupV20Snapshot()+ let fresh = try await request(fixture, ids)+ if case .refused = try await fixture.repository.commitRecognisedCharacter(fresh) {} else { Issue.record("Rejected spelling was resurrected") }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }++ @Test func enrichmentFieldsAreNeverInstalled() async throws {+ let (fixture, ids) = try await fixture()+ var input = try await request(fixture, ids); input.proposedAliases = ["Lady Ada"]+ let before = try await fixture.repository.backupV20Snapshot()+ await #expect(throws: (any Error).self) { try await fixture.repository.commitRecognisedCharacter(input) }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }++ @Test func ordinaryRecognitionCannotAcknowledgePlaceKey() async throws {+ let (fixture, ids) = try await fixture()+ let current = try await candidate(fixture, ids)+ let marker = AssociationPendingReviewRequest(marker: .init(workID: ids.work, entryID: ids.entry,+ sourceGuard: try #require(current.mentionIndex.sourceGuards[ids.entry]), items: [+ .init(key: .init(kind: .character, nameKey: "ada"), targetID: ids.character, spellingKeys: ["ada"]),+ .init(key: .init(kind: .place, nameKey: "ada"), targetID: nil, spellingKeys: ["ada"]),+ ]), originalEligibilityBase: current.mentionIndex.coverageBases[ids.entry], originalEligibilityDigest: current.mentionIndex.eligibilityByEntry[ids.entry])+ let saved = try #require(try await fixture.repository.recordPendingMentionReviews([marker]).first)+ var input = try await request(fixture, ids, originalKind: .place)+ input.reviewAcknowledgements = [.init(workID: ids.work, entryID: ids.entry, references: saved.references)]+ let before = try await fixture.repository.backupV20Snapshot()+ await #expect(throws: (any Error).self) { try await fixture.repository.commitRecognisedCharacter(input) }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ // Only an explicit kind-switch may settle the original place key.+ #expect(try await fixture.repository.commitReclassifiedRecognisedCharacter(input) == .committed(recordID: ids.character))+ #expect(try await candidate(fixture, ids).mentionIndex.pendingReviewReferences[ids.entry]?.map(\.key.kind) == [.character])+ withExtendedLifetime(fixture) {}+ }++ @Test func candidateSuppressionRemainsScopedToCreation() async throws {+ let (fixture, ids) = try await fixture()+ _ = try await fixture.repository.commitDecision(.init(workID: ids.work, action: .skip,+ displayedKeys: ["ada"], proposedName: "Ada"))+ let before = try await candidate(fixture, ids).suppressions(of: .character)+ #expect(before.candidateKeys.contains("ada"))+ _ = try await fixture.repository.commitRecognisedCharacter(try await request(fixture, ids))+ #expect(try await candidate(fixture, ids).suppressions(of: .character) == before)+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry).filter { !$0.activeAcceptanceIDs.isEmpty }.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test func nonChapterRecognitionSettlesWithoutInventingLink() async throws {+ let (fixture, ids) = try await fixture(chapter: false)+ let input = try await request(fixture, ids)+ #expect(input.mentions.isEmpty)+ #expect(try await fixture.repository.commitRecognisedCharacter(input) == .committed(recordID: ids.character))+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry).isEmpty)+ #expect(try await candidate(fixture, ids).sources.first { $0.ref == .entry(ids.entry) }?.isCovered == false)+ withExtendedLifetime(fixture) {}+ }++ @Test func genericRecognitionCannotCoverOtherUndecidedNames() async throws {+ let (fixture, ids) = try await fixture()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding mixed generic evidence") { context in+ try #require(try context.fetch(FetchDescriptor<Work>()).first).genericNotes = "Ada meets Cora by the Harbor."+ try context.save()+ }+ let source = try #require(try await candidate(fixture, ids).sources.first { $0.ref == .genericNotes })+ let input = DecisionRequest(workID: ids.work, action: .accept, displayedTargetID: ids.character,+ proposedName: "Ada", completedSources: [source.completedSource], reviewedKey: .init(kind: .character, nameKey: "ada"))+ #expect(try await fixture.repository.commitRecognisedCharacter(input) == .committed(recordID: ids.character))+ #expect(try await candidate(fixture, ids).sources.first { $0.ref == .genericNotes }?.isCovered == false)+ withExtendedLifetime(fixture) {}+ }++ @Test func restorationIsExplicitGuardedAndDoesNotEnrich() async throws {+ let (fixture, ids) = try await fixture()+ var skipped = try await request(fixture, ids); skipped.action = .skip+ _ = try await fixture.repository.commitDecision(skipped)+ let captured = try #require(try await fixture.repository.skippedCharacterLinks(entryID: ids.entry).first)+ let before = try await fixture.repository.backupV20Snapshot()+ #expect(try await fixture.repository.restoreCharacterLink(captured) == .committed(recordID: ids.character))+ let after = try await fixture.repository.backupV20Snapshot()+ #expect(after.library.characters == before.library.characters)+ #expect(after.pairNoteVersions == before.pairNoteVersions)+ #expect(try await fixture.repository.skippedCharacterLinks(entryID: ids.entry).isEmpty)+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry).filter { !$0.activeAcceptanceIDs.isEmpty }.count == 1)+ if case .refused = try await fixture.repository.restoreCharacterLink(captured) {} else { Issue.record("Stale rejection receipt replayed") }+ #expect(try await fixture.repository.backupV20Snapshot() == after)+ // Historical rejection IDs remain in the ledger after explicit restoration.+ // Ordinary recognition may observe them but must never reconsider them again.+ #expect(try await fixture.repository.commitRecognisedCharacter(try await request(fixture, ids)) == .committed(recordID: ids.character))+ let settled = try await fixture.repository.backupV20Snapshot()+ #expect(settled.library == after.library)+ #expect(settled.pairNoteVersions == after.pairNoteVersions)+ let previousIDs = Set(after.associationEvents.map(\.id))+ #expect(settled.associationEvents.filter { previousIDs.contains($0.id) } == after.associationEvents)+ let additions = settled.associationEvents.filter { !previousIDs.contains($0.id) }+ #expect(additions.count == 1)+ if case .coverage? = additions.first?.value?.payload {} else { Issue.record("Only one-time source completion may change") }+ #expect(try await fixture.repository.commitRecognisedCharacter(try await request(fixture, ids)) == .committed(recordID: ids.character))+ #expect(try await fixture.repository.backupV20Snapshot() == settled)+ withExtendedLifetime(fixture) {}+ }++ @Test func restorationRejectsChangedSourceWithoutClearingSuppression() async throws {+ let (fixture, ids) = try await fixture()+ var skipped = try await request(fixture, ids); skipped.action = .skip+ _ = try await fixture.repository.commitDecision(skipped)+ let captured = try #require(try await fixture.repository.skippedCharacterLinks(entryID: ids.entry).first)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "changing restored source") { context in+ try #require(try context.fetch(FetchDescriptor<Entry>()).first).note = "Ada returns."+ try context.save()+ }+ let before = try await fixture.repository.backupV20Snapshot()+ #expect(try await fixture.repository.restoreCharacterLink(captured) == .refused(.staleSource(.entry(ids.entry))))+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }++ @Test func strictNamesOnlyKeepRefusesDeletedSourceButLegacyCitationToleranceRemains() async throws {+ let (fixture, ids) = try await fixture(chapter: false)+ let source = try #require(try await candidate(fixture, ids).sources.first)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "removing synthetic note") { context in+ for row in try context.fetch(FetchDescriptor<Entry>()) { context.delete(row) }+ try context.save()+ }+ var input = DecisionRequest(workID: ids.work, action: .accept, proposedName: "Cora",+ completedSources: [source.completedSource], requiresCurrentSources: true)+ #expect(try await fixture.repository.commitDecision(input) == .refused(.staleSource(.entry(ids.entry))))+ input.requiresCurrentSources = false+ if case .committed = try await fixture.repository.commitDecision(input) {} else { Issue.record("Legacy dangling-citation tolerance changed") }+ withExtendedLifetime(fixture) {}+ }++ @Test func failedSaveRollsBackLinkMarkerAcknowledgementAndCoverage() async throws {+ let save = SwitchSave(), (fixture, ids) = try await fixture(save: save)+ let current = try await candidate(fixture, ids)+ let marker = AssociationPendingReviewRequest(marker: .init(workID: ids.work, entryID: ids.entry,+ sourceGuard: try #require(current.mentionIndex.sourceGuards[ids.entry]), items: [+ .init(key: .init(kind: .character, nameKey: "ada"), targetID: ids.character, spellingKeys: ["ada"]),+ ]), originalEligibilityBase: current.mentionIndex.coverageBases[ids.entry], originalEligibilityDigest: current.mentionIndex.eligibilityByEntry[ids.entry])+ let saved = try #require(try await fixture.repository.recordPendingMentionReviews([marker]).first)+ var input = try await request(fixture, ids)+ input.reviewAcknowledgements = [.init(workID: ids.work, entryID: ids.entry, references: saved.references)]+ let before = try await fixture.repository.backupV20Snapshot()+ save.arm()+ await #expect(throws: (any Error).self) { try await fixture.repository.commitRecognisedCharacter(input) }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ #expect(try await fixture.repository.commitRecognisedCharacter(input) == .committed(recordID: ids.character))+ withExtendedLifetime(fixture) {}+ }++ @Test func renewedSupportDoesNotAttachDetachedAuthoredText() async throws {+ let (fixture, ids) = try await fixture()+ _ = try await fixture.repository.commitRecognisedCharacter(try await request(fixture, ids))+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry, kind: .character, recordID: ids.character)+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ _ = try await fixture.repository.saveAssociationNote(basis: basis, text: "Reader's exact chapter annotation.")+ var entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "No names remain.", rating: nil)+ let detached = try await fixture.repository.backupV20Snapshot().pairNoteVersions+ entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Ada returns.", rating: nil)+ _ = try await fixture.repository.commitRecognisedCharacter(try await request(fixture, ids))+ #expect(try await fixture.repository.backupV20Snapshot().pairNoteVersions == detached)+ #expect(try await fixture.repository.chapterAssociations(entryID: ids.entry).first?.noteHeads.isEmpty == true)+ withExtendedLifetime(fixture) {}+ }++ @Test("Automatic settlement cannot swallow another target or unsupported spelling", arguments: [false, true])+ func markerBasisMustMatchTheAutomaticEvidence(wrongTarget: Bool) async throws {+ let (fixture, ids) = try await fixture()+ let current = try await candidate(fixture, ids)+ let marker = AssociationPendingReviewRequest(marker: .init(workID: ids.work, entryID: ids.entry,+ sourceGuard: try #require(current.mentionIndex.sourceGuards[ids.entry]), items: [+ .init(key: .init(kind: .character, nameKey: "ada"), targetID: wrongTarget ? UUID() : ids.character,+ spellingKeys: wrongTarget ? ["ada"] : ["ada", "bryn"]),+ ]), originalEligibilityBase: current.mentionIndex.coverageBases[ids.entry], originalEligibilityDigest: current.mentionIndex.eligibilityByEntry[ids.entry])+ let saved = try #require(try await fixture.repository.recordPendingMentionReviews([marker]).first)+ var input = try await request(fixture, ids)+ input.reviewAcknowledgements = [.init(workID: ids.work, entryID: ids.entry, references: saved.references)]+ let before = try await fixture.repository.backupV20Snapshot()+ if case .refused = try await fixture.repository.commitRecognisedCharacter(input) {} else { Issue.record("Unrelated marker basis acknowledged") }+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }++ @Test func settlementPreservesOtherOriginalKindsAndKeys() async throws {+ let (fixture, ids) = try await fixture()+ let current = try await candidate(fixture, ids)+ let marker = AssociationPendingReviewRequest(marker: .init(workID: ids.work, entryID: ids.entry,+ sourceGuard: try #require(current.mentionIndex.sourceGuards[ids.entry]), items: [+ .init(key: .init(kind: .character, nameKey: "ada"), targetID: ids.character, spellingKeys: ["ada"]),+ .init(key: .init(kind: .place, nameKey: "ada"), targetID: nil, spellingKeys: ["ada"]),+ ]), originalEligibilityBase: current.mentionIndex.coverageBases[ids.entry],+ originalEligibilityDigest: current.mentionIndex.eligibilityByEntry[ids.entry])+ let saved = try #require(try await fixture.repository.recordPendingMentionReviews([marker]).first)+ var input = try await request(fixture, ids)+ input.reviewAcknowledgements = [.init(workID: ids.work, entryID: ids.entry, references: saved.references)]+ #expect(try await fixture.repository.commitRecognisedCharacter(input) == .committed(recordID: ids.character))+ let after = try await candidate(fixture, ids)+ #expect(after.mentionIndex.pendingReviewReferences[ids.entry]?.map(\.key.kind) == [.place])+ #expect(after.sources.first { $0.ref == .entry(ids.entry) }?.isCovered == false)+ withExtendedLifetime(fixture) {}+ }+}++@Suite("Recognition confidence before deterministic tie-break")+struct RecordRecognitionTests {+ @Test func winningTierUniquenessIsRequired() {+ let a = UUID(), b = UUID()+ func target(_ id: UUID, name: String = "ada", retained: String = "old", aliases: [String] = [], torn: Bool = false) -> MatchTarget {+ .init(id: id, currentNameKey: name, retainedKey: retained, aliasKeys: aliases, isTorn: torn)+ }+ #expect(RecordMatching.recognition(nameKey: "ada", among: []) == .noMatch)+ #expect(RecordMatching.recognition(nameKey: "ada", among: [target(a), target(b, name: "other", retained: "ada")]) == .unique(a))+ #expect(RecordMatching.recognition(nameKey: "ada", among: [target(a), target(b)]) == .ambiguous)+ #expect(RecordMatching.recognition(nameKey: "ada", among: [target(a, torn: true)]) == .ambiguous)+ #expect(RecordMatching.recognition(nameKey: "ada", among: [target(a), target(a, name: "other")]) == .ambiguous)+ #expect(RecordMatching.recognition(nameKey: "ada", among: [target(a), target(a)]) == .unique(a))+ #expect(RecordMatching.match(nameKey: "ada", among: [target(a), target(b)]) != nil)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RecordHistoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RecordHistoryTests.swiftnew file mode 100644index 00000000..cf862cf2--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RecordHistoryTests.swift@@ -0,0 +1,174 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Selected record chapter history", .serialized)+struct RecordHistoryTests {+ private struct IDs: Sendable { let work = UUID(), record = UUID(); var entries: [UUID] = [] }+ private func fixture(count: Int = 2, kind: RecordKind = .character, annotate: Bool = false) async throws -> (M5Fixture, IDs) {+ let fixture = try await M5Fixture(), initial = IDs()+ let ids = try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding selected record history") { context in+ var ids = initial+ let work = Work(id: ids.work, displayTitle: "Synthetic history Work", timestamp: M5Fixture.epoch)+ let otherWork = Work(displayTitle: "Unrelated history Work", timestamp: M5Fixture.epoch)+ context.insert(work); context.insert(otherWork)+ let legacy = RecordFact(statement: "Existing saved fact", quote: "Preserved quote", nameKey: "ada", source: .entry(UUID()))+ let targetFingerprint: String+ if kind == .character {+ let record = CharacterRecord(id: ids.record, name: "Ada", nameKey: "ada", facts: [legacy], work: work)+ context.insert(record); targetFingerprint = AssociationEndpointInventory.targetFingerprint(record)+ for index in 0..<119 { context.insert(CharacterRecord(name: "Other\(index)", nameKey: "other\(index)", work: work)) }+ } else {+ let record = Place(id: ids.record, name: "Ada", nameKey: "ada", facts: [legacy], workID: ids.work)+ context.insert(record); targetFingerprint = AssociationEndpointInventory.targetFingerprint(record)+ }+ let empty = AssociationLedgerInventory(events: [])+ for index in 0..<count {+ let entry = Entry(captureTitle: "Chapter \(index + 1)", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch.addingTimeInterval(Double(index)),+ note: "Ada. " + String(repeating: "Exact saved source 🌟. ", count: annotate ? 15 : 1))+ try entry.authorTarget(.init(kind: .chapter)); context.insert(entry); entry.work = work+ LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch)+ ids.entries.append(entry.id)+ let pair = AssociationPair(workID: ids.work, entryID: entry.id, kind: kind, recordID: ids.record)+ let current = AssociationCurrentPair(pair: pair, sourceFingerprint: AssociationEndpointInventory.sourceFingerprint(entry),+ matchingFingerprint: targetFingerprint, evidence: RecordMentionGrounding.evidence(names: ["Ada"], in: entry.note))+ let event = AssociationLedgerEvent(payload: .accept(.init(pair: pair, spellingKeys: ["ada"])), validation: empty.receipt(for: current))+ context.insert(try AssociationEvent(event: event, recordedAt: M5Fixture.epoch))+ if annotate {+ context.insert(try PairNoteVersion(note: .init(pair: pair, attachmentAcceptanceIDs: [event.id],+ text: "Authored annotation \(index). " + String(repeating: "Unchanged prose. ", count: 8))))+ }+ let outside = AssociationPair(workID: otherWork.id, entryID: UUID(), kind: kind, recordID: UUID())+ context.insert(try AssociationEvent(event: .init(payload: .accept(.init(pair: outside, spellingKeys: ["outside"]))), recordedAt: M5Fixture.epoch))+ }+ try context.save(); return ids+ }+ return (fixture, ids)+ }+ private func history(_ fixture: M5Fixture, _ ids: IDs, kind: RecordKind = .character) async throws -> RecordHistorySnapshot {+ try await fixture.repository.recordHistory(workID: ids.work, kind: kind, recordID: ids.record)+ }++ @Test("600 selected chapters are one fold, one endpoint batch and 30 local windows", arguments: [RecordKind.character, .place])+ func selected600IsBatchedAndCaptured(kind: RecordKind) async throws {+ let (fixture, ids) = try await fixture(count: 600, kind: kind, annotate: true)+ let before = try await fixture.repository.backupV20Snapshot()+ let measurement = try await fixture.repository.withLockedContext(mode: .shared, operation: "measuring selected history") { context in+ let start = ContinuousClock.now+ let baseline = try AssociationStorageInventory.read(context: context, workIDs: [ids.work])+ let selected = baseline.ledger.pairs.filter { $0.recordID == ids.record && $0.kind == kind }+ _ = try AssociationEndpointInventory.read(context: context, pairs: selected)+ let baselineTime = start.duration(to: .now)+ let projectionStart = ContinuousClock.now+ let result = try LibraryRepository.recordHistory(selection: .init(workID: ids.work, kind: kind, recordID: ids.record), context: context)+ print("T2468 history600 \(kind.rawValue): baseline inventory+batch \(baselineTime), projection \(projectionStart.duration(to: .now)), UTF8 display payload \(result.snapshot.displayTextUTF8ByteCount) bytes (not allocator peak)")+ #expect(baseline.rawEvents.count == 600)+ return (result.snapshot, result.diagnostics)+ }+ let snapshot = measurement.0+ #expect(snapshot.availability == .available && snapshot.activeChapterCount == 600)+ #expect(snapshot.rows.map(\.id.entryID) == ids.entries)+ #expect(snapshot.rows.allSatisfy { $0.hasAnnotation && !$0.hasConflictingAnnotations && $0.sourcePreview.count <= 160 })+ #expect(measurement.1.ledgerFoldCount == 1 && measurement.1.eventFetchCount == 2 && measurement.1.noteFetchCount == 2)+ #expect(measurement.1.endpointFetchCount == 3)+ var reached: Set<AssociationPair> = []+ for window in 1...30 { reached.formUnion(snapshot.rows.prefix(window * 20).map(\.id)) }+ #expect(reached.count == 600)+ let first = try #require(snapshot.rows.first)+ #expect(snapshot.detail(for: first.id, expectedGeneration: "older generation") == nil)+ let detail = try #require(snapshot.detail(for: first.id, expectedGeneration: snapshot.generation))+ #expect(detail.sourceText.hasPrefix("Ada. ") && detail.annotationHeads.first?.text.hasPrefix("Authored annotation 0.") == true)+ #expect(try await history(fixture, ids, kind: kind).generation == snapshot.generation)+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ withExtendedLifetime(fixture) {}+ }++ @Test func annotationSaveChangesGenerationWithoutChangingSourceOrWorkClock() async throws {+ let (fixture, ids) = try await fixture()+ let first = try await history(fixture, ids), pair = try #require(first.rows.first?.id)+ let workBefore = try await fixture.repository.workDetail(id: ids.work).work.modifiedAt+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ _ = try await fixture.repository.saveAssociationNote(basis: basis, text: "Exact authored text.")+ let next = try await history(fixture, ids)+ #expect(first.generation != next.generation && next.activeChapterCount == 2)+ #expect(next.rows.first?.sourceFingerprint == first.rows.first?.sourceFingerprint)+ #expect(try await fixture.repository.workDetail(id: ids.work).work.modifiedAt == workBefore)+ #expect(first.detail(for: pair, expectedGeneration: first.generation)?.annotationHeads.isEmpty == true)+ #expect(next.detail(for: pair, expectedGeneration: next.generation)?.annotationHeads.first?.text == "Exact authored text.")+ #expect(next.detail(for: pair, expectedGeneration: first.generation) == nil)+ withExtendedLifetime(fixture) {}+ }++ @Test func finalSupportLossDetachesTextAndRenewedLinkDoesNotAttachIt() async throws {+ let (fixture, ids) = try await fixture(count: 1, annotate: true)+ let original = try await history(fixture, ids), pair = try #require(original.rows.first?.id)+ var entry = try await fixture.repository.entry(id: ids.entries[0])+ _ = try await fixture.repository.updateEntry(id: entry.id, basis: .init(entry: entry), note: "No character here.", rating: nil)+ let empty = try await history(fixture, ids)+ #expect(empty.activeChapterCount == 0 && empty.availability == .available)+ let raw = try await fixture.repository.backupV20Snapshot().pairNoteVersions+ entry = try await fixture.repository.entry(id: entry.id)+ _ = try await fixture.repository.updateEntry(id: entry.id, basis: .init(entry: entry), note: "Ada returned.", rating: nil)+ let candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ let source = try #require(candidate.sources.first)+ _ = try await fixture.repository.commitRecognisedCharacter(.init(workID: ids.work, action: .accept,+ displayedTargetID: ids.record, proposedName: "Ada", completedSources: [source.completedSource],+ mentions: [.init(entryID: entry.id, noteFingerprint: source.fingerprint, spellingKeys: ["ada"], sourceGuard: candidate.mentionIndex.sourceGuards[entry.id])],+ reviewedKey: .init(kind: .character, nameKey: "ada")))+ let renewed = try await history(fixture, ids)+ #expect(renewed.activeChapterCount == 1 && renewed.detail(for: pair, expectedGeneration: renewed.generation)?.annotationHeads.isEmpty == true)+ #expect(try await fixture.repository.backupV20Snapshot().pairNoteVersions == raw)+ withExtendedLifetime(fixture) {}+ }++ @Test("Incomplete source/target copies are not zero chapters", arguments: [false, true])+ func missingOrConflictingEndpointsStayReviewNeeded(targetConflict: Bool) async throws {+ let (fixture, ids) = try await fixture()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "simulating incomplete history endpoints") { context in+ if targetConflict {+ let other = Work(displayTitle: "Conflicting Work", timestamp: M5Fixture.epoch); context.insert(other)+ context.insert(CharacterRecord(id: ids.record, name: "Other", nameKey: "other", work: other))+ } else {+ let removed = ids.entries[0]+ for entry in try context.fetch(FetchDescriptor<Entry>(predicate: #Predicate { $0.id == removed })) { context.delete(entry) }+ }+ try context.save()+ }+ let snapshot = try await history(fixture, ids)+ #expect(snapshot.availability == .reviewRequired && snapshot.activeChapterCount == nil)+ #expect(snapshot.rows.count == (targetConflict ? 0 : 1))+ #expect(!snapshot.unavailableEntryIDs.isEmpty)+ withExtendedLifetime(fixture) {}+ }++ @Test func duplicateAcceptancesAndConcurrentHeadsStayOneChapterWithExactTexts() async throws {+ let (fixture, ids) = try await fixture(count: 1, annotate: true)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding concurrent history evidence") { context in+ let row = try #require(try context.fetch(FetchDescriptor<AssociationEvent>()).first { $0.workID == ids.work })+ let existing = try #require(row.ledgerValue)+ context.insert(try AssociationEvent(event: .init(payload: existing.payload, validation: existing.validation), recordedAt: M5Fixture.epoch))+ let pair = try #require(existing.payload.pair)+ context.insert(try PairNoteVersion(note: .init(pair: pair, attachmentAcceptanceIDs: [existing.id], text: "Independent concurrent annotation.")))+ try context.save()+ }+ let snapshot = try await history(fixture, ids), row = try #require(snapshot.rows.first)+ #expect(snapshot.activeChapterCount == 1 && row.hasConflictingAnnotations)+ #expect(snapshot.detail(for: row.id, expectedGeneration: snapshot.generation)?.annotationHeads.count == 2)+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: row.id))+ _ = try await fixture.repository.clearAssociationNote(basis: basis)+ let cleared = try await history(fixture, ids)+ #expect(cleared.activeChapterCount == 1 && cleared.rows.first?.hasAnnotation == false)+ #expect(cleared.generation != snapshot.generation)+ withExtendedLifetime(fixture) {}+ }++ @Test func nonexistentSelectionAndKnownEmptySelectionAreDifferent() async throws {+ let (fixture, ids) = try await fixture(count: 0)+ #expect(try await history(fixture, ids).activeChapterCount == 0)+ let absent = try await fixture.repository.recordHistory(workID: ids.work, kind: .character, recordID: UUID())+ #expect(absent.activeChapterCount == nil && absent.availability == .unavailable)+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swiftindex 1ce47dc7..a0e291fe 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RepositoryCaptureTests.swift@@ -85,7 +85,8 @@ struct RepositoryCaptureTests { try await fixture.repository.deleteEntry(id: entry.id) #expect(try await fixture.repository.debugCounts() == LibraryRecordCounts(- entries: 0, works: 1, sites: 1, titlePatterns: 0).withSeededWorkTypes)+ entries: 0, works: 1, sites: 1, titlePatterns: 0,+ workTypes: WorkTypeSeeding.seeds.count, associationEvents: 1)) let modifiedAt = try await fetchWorkModifiedAt(configuration: fixture.configuration, workID: workID) #expect(modifiedAt == clock.now()) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swiftindex 835d3de3..d7c82c26 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/RuleSelectionTests.swift@@ -98,7 +98,7 @@ struct RuleSelectionTests { /// hands back the same registered objects in the same order every time, /// which is a property of that context, not of the accessor. private func container() throws -> ModelContainer {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) return try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SaveTimeKnownLinkMatchingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SaveTimeKnownLinkMatchingTests.swiftnew file mode 100644index 00000000..1a0e37e1--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/SaveTimeKnownLinkMatchingTests.swift@@ -0,0 +1,40 @@+import Foundation+import Testing+@testable import AsterismCore++@Suite("Save-time complete known names")+struct SaveTimeKnownLinkMatchingTests {+ @Test(arguments: [+ ("Alice", "Alice", true), ("Alice", "(Alice)", true), ("Alice", "ALICE", true),+ ("Alice", "Alice’s coat", true), ("Alice", "Alice's coat", true), ("Alice", "Alice'", true),+ ("Alice", "alice", false), ("Ann", "Anna", false), ("Ann", "Ann2", false),+ ("Ann", "Ann_2", false), ("Ann", "Ann-Marie", false), ("Ann", "Ann‐Marie", false),+ ("Ann", "Ann’Neil", false), ("Ann", "Jo-Ann", false), ("Ann", "Jo’Ann", false),+ ("Ann", "中Ann", false), ("Ann", "Ann中", false), ("Ann", "Ann²", false),+ ("Ann", "Ann\u{203F}Other", false), ("Ann", "Ann\u{0301}", false),+ ("O’Neil", "O’Neil arrived", true), ("O", "O’Neil arrived", false),+ ("Neil", "O’Neil arrived", false), ("New York", "New York.", true),+ ("New York", "New Yorker", false), ("René", "Rene\u{0301}", true),+ ("Rene\u{0301}", "René", true), ("Rene", "René", false),+ ("中", "中", true), ("中", "中文", false),+ ("정교", "정교가", false), ("서울", "서울에서", false), ("太郎", "太郎를", false), ("Alice", "🌟Alice🌟", true),+ ("She", "She", false), (String(repeating: "A", count: 101), String(repeating: "A", count: 101), false)+ ])+ func completeNameAdmission(name: String, source: String, expected: Bool) {+ #expect(!RecordMentionGrounding.completeNameEvidence(names: [name], in: source).isEmpty == expected)+ }++ @Test func currentThenRetainedThenAliasMustHaveOneCoherentIdentity() {+ let current = UUID(), retained = UUID(), alias = UUID()+ let a = MatchTarget(id: current, currentNameKey: "ada", retainedKey: "old", aliasKeys: [], isTorn: false)+ let b = MatchTarget(id: retained, currentNameKey: "briar", retainedKey: "ada", aliasKeys: [], isTorn: false)+ let c = MatchTarget(id: alias, currentNameKey: "cora", retainedKey: "cora", aliasKeys: ["ada"], isTorn: false)+ #expect(RecordMatching.recognition(nameKey: "ada", among: [c, b, a]) == .unique(current))+ #expect(RecordMatching.recognition(nameKey: "ada", among: [c, b]) == .unique(retained))+ #expect(RecordMatching.recognition(nameKey: "ada", among: [c]) == .unique(alias))+ let collision = MatchTarget(id: UUID(), currentNameKey: "ada", retainedKey: "ada", aliasKeys: [], isTorn: false)+ #expect(RecordMatching.recognition(nameKey: "ada", among: [a, collision]) == .ambiguous)+ let torn = MatchTarget(id: current, currentNameKey: "ada", retainedKey: "old", aliasKeys: [], isTorn: true)+ #expect(RecordMatching.recognition(nameKey: "ada", among: [torn, b, c]) == .ambiguous)+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SaveTimeKnownLinkRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SaveTimeKnownLinkRepositoryTests.swiftnew file mode 100644index 00000000..ecb1554b--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/SaveTimeKnownLinkRepositoryTests.swift@@ -0,0 +1,500 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Save-time known chapter links", .serialized)+struct SaveTimeKnownLinkRepositoryTests {+ private struct IDs: Sendable { let work = UUID(), character = UUID(), place = UUID(), entry = UUID() }+ private func fixture(seedEntry: Bool = false, target: AuthoredEntryTarget.Kind = .chapter,+ save: any RepositorySaveStrategy = ModelContextSaveStrategy()) async throws -> (M5Fixture, IDs) {+ let fixture = try await M5Fixture(saveStrategy: save), ids = IDs()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding save-time known links") { context in+ let work = Work(id: ids.work, displayTitle: "Saved book", timestamp: M5Fixture.epoch)+ context.insert(work)+ context.insert(CharacterRecord(id: ids.character, name: "Ada", nameKey: "ada", aliases: ["Addie"], work: work))+ context.insert(Place(id: ids.place, name: "Harbor", nameKey: "harbor", workID: ids.work))+ if seedEntry {+ let entry = Entry(id: ids.entry, captureTitle: "Chapter", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch,+ note: "Ada visits Harbor and Newtown.")+ try entry.authorTarget(.init(kind: target)); context.insert(entry); entry.work = work+ LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch)+ }+ try context.save()+ }+ return (fixture, ids)+ }+ private func active(_ fixture: M5Fixture, entry: UUID) async throws -> [ChapterAssociationSnapshot] {+ try await fixture.repository.chapterAssociations(entryID: entry).filter { !$0.activeAcceptanceIDs.isEmpty }+ }+ @Test(arguments: [AuthoredEntryTarget.Kind.chapter, .note])+ func manualSaveLinksBothKindsOnlyForChapter(kind: AuthoredEntryTarget.Kind) async throws {+ let (fixture, ids) = try await fixture()+ let projection = try await fixture.repository.projectManualEntry(workID: ids.work)+ guard case .committed(let entry) = try await fixture.repository.commitManualEntry(projection: projection,+ draft: .init(target: .init(kind: kind), note: "Ada visits Harbor.")) else { Issue.record("Expected saved note"); return }+ let links = try await active(fixture, entry: entry.id)+ #expect(Set(links.map { $0.pair.kind }) == (kind == .chapter ? Set([RecordKind.character, .place]) : []))+ #expect(links.allSatisfy { $0.pair.workID == ids.work && $0.activeAcceptanceIDs.count == 1 })+ let saved = try await fixture.repository.workDetail(id: ids.work)+ #expect(saved.characters.allSatisfy { $0.facts.isEmpty } && saved.places.allSatisfy { $0.facts.isEmpty })+ withExtendedLifetime(fixture) {}+ }+ @Test func unchangedSaveFillsMissingLinksAndSettlesOnlyKnownPlacePendingKey() async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ let before = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ let guardValue = try #require(before.mentionIndex.sourceGuards[ids.entry])+ let request = AssociationPendingReviewRequest(marker: .init(workID: ids.work, entryID: ids.entry,+ sourceGuard: guardValue, items: [+ .init(key: .init(kind: .place, nameKey: "harbor"), targetID: ids.place, spellingKeys: ["harbor"]),+ .init(key: .init(kind: .place, nameKey: "newtown"), targetID: nil, spellingKeys: ["newtown"])]),+ originalEligibilityBase: before.mentionIndex.coverageBases[ids.entry], originalEligibilityDigest: before.mentionIndex.eligibilityByEntry[ids.entry])+ _ = try await fixture.repository.recordPendingMentionReviews([request])+ let entry = try await fixture.repository.entry(id: ids.entry)+ #expect(try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: entry.note, rating: entry.rating) == .committed)+ #expect(Set(try await active(fixture, entry: ids.entry).map { $0.pair.kind }) == Set([RecordKind.character, .place]))+ let after = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ #expect(after.mentionIndex.pendingReviewReferences[ids.entry]?.map(\.key.nameKey) == ["newtown"])+ #expect(after.sources.first { $0.ref == .entry(ids.entry) }?.isCovered == false)+ let snapshot = try await fixture.repository.backupV20Snapshot()+ let fresh = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: fresh), note: fresh.note, rating: fresh.rating)+ #expect(try await fixture.repository.backupV20Snapshot().associationEvents == snapshot.associationEvents)+ withExtendedLifetime(fixture) {}+ }++ @Test func saveAcknowledgesOnlyExactPendingKeysInItsCurrentChapter() async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ let candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ let sourceGuard = try #require(candidate.mentionIndex.sourceGuards[ids.entry])+ let harbor = AssociationReviewKey(kind: .place, nameKey: "harbor")+ let newtown = AssociationReviewKey(kind: .place, nameKey: "newtown")+ let valid = UUID(), invalid = UUID(), settled = UUID(), unsupported = UUID()+ let otherChapter = UUID(), otherWork = UUID(), otherChapterMarker = UUID(), otherWorkMarker = UUID()+ let priorAcknowledgement = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding source-scoped pending variants") { context in+ func marker(_ id: UUID, work: UUID, entry: UUID, items: [AssociationPendingReviewItem]) throws {+ context.insert(try AssociationEvent(event: .init(id: id, payload: .pendingReview(.init(+ workID: work, entryID: entry, sourceGuard: sourceGuard, items: items))), recordedAt: M5Fixture.epoch))+ }+ let known = AssociationPendingReviewItem(key: harbor, targetID: ids.place, spellingKeys: ["harbor"])+ try marker(valid, work: ids.work, entry: ids.entry, items: [known,+ .init(key: newtown, targetID: nil, spellingKeys: ["newtown"])])+ try marker(otherChapterMarker, work: ids.work, entry: otherChapter, items: [known])+ try marker(otherWorkMarker, work: otherWork, entry: ids.entry, items: [known])+ // Both variants enter the source index, but neither may authorize settlement.+ try marker(invalid, work: ids.work, entry: ids.entry, items: [known])+ try marker(invalid, work: otherWork, entry: otherChapter, items: [known])+ try marker(unsupported, work: ids.work, entry: ids.entry, items: [+ .init(key: harbor, targetID: ids.place, spellingKeys: ["harbor", "newtown"])])+ try marker(settled, work: ids.work, entry: ids.entry, items: [known])+ context.insert(try AssociationEvent(event: .init(id: priorAcknowledgement, payload: .reviewAcknowledgement(.init(+ workID: ids.work, entryID: ids.entry, references: [.init(markerID: settled, key: harbor)], outcome: .skipped))),+ recordedAt: M5Fixture.epoch))+ try context.save()+ }+ let entry = try await fixture.repository.entry(id: ids.entry)+ #expect(try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: entry.note, rating: entry.rating) == .committed)+ let acknowledgements = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking exact saved references") { context in+ try context.fetch(FetchDescriptor<AssociationEvent>()).compactMap { row -> AssociationReviewAcknowledgement? in+ guard row.id != priorAcknowledgement, let event = row.ledgerValue,+ case .reviewAcknowledgement(let value) = event.payload else { return nil }+ return value+ }+ }+ #expect(acknowledgements.count == 1)+ #expect(acknowledgements.first?.workID == ids.work && acknowledgements.first?.entryID == ids.entry)+ #expect(acknowledgements.flatMap(\.references) == [.init(markerID: valid, key: harbor)])+ let after = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ #expect(after.mentionIndex.pendingReviewReferences[ids.entry, default: []].contains(.init(markerID: valid, key: newtown)))+ #expect(after.sources.first { $0.ref == .entry(ids.entry) }?.isCovered == false)+ let links = try await active(fixture, entry: ids.entry)+ #expect(Set(links.map { $0.pair.kind }) == Set([RecordKind.character, .place]))+ #expect(links.allSatisfy { $0.activeAcceptanceIDs.count == 1 })+ let snapshot = try await fixture.repository.backupV20Snapshot()+ let fresh = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: fresh), note: fresh.note, rating: fresh.rating)+ let repeated = try await fixture.repository.backupV20Snapshot()+ #expect(repeated.associationEvents == snapshot.associationEvents && repeated.pairNoteVersions == snapshot.pairNoteVersions)+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["update", "liveReShare", "drainedReplay", "manualExisting", "noteToChapter"])+ func existingSaveTerminalsUseFinalStoredNoteAndDeduplicate(terminal: String) async throws {+ let (fixture, ids) = try await fixture(seedEntry: true, target: terminal == "noteToChapter" ? .note : .chapter)+ let entry = try await fixture.repository.entry(id: ids.entry)+ switch terminal {+ case "liveReShare":+ let basis = try await fixture.repository.withLockedContext(mode: .shared, operation: "reading test re-share basis") { context in+ try LibraryRepository.fetchNormalisedEntryGroup(id: ids.entry, context: context).reShareBasis(hostname: "", site: nil)+ }+ #expect(try await fixture.repository.commitReShareUpdate(basis: basis, note: entry.note, rating: nil) == .committed)+ case "drainedReplay":+ let target = DrainedReShareTarget(entryID: ids.entry, hostname: "", identityKey: "entry/\(ids.entry.uuidString.lowercased())")+ #expect(try await fixture.repository.recordDrainedReShare(target: target, sharedAt: entry.lastSharedAt) == .committed)+ let first = try await fixture.repository.backupV20Snapshot()+ #expect(try await fixture.repository.recordDrainedReShare(target: target, sharedAt: entry.lastSharedAt) == .committed)+ #expect(try await fixture.repository.backupV20Snapshot() == first)+ case "manualExisting":+ let projection = try await fixture.repository.projectManualEntry(workID: ids.work)+ guard case .committed = try await fixture.repository.commitManualEntry(projection: projection,+ draft: .init(target: .init(kind: .chapter), note: entry.note, existingEntryID: ids.entry)) else { Issue.record("Expected existing save"); return }+ case "noteToChapter":+ let correction = try await fixture.repository.projectEntryCorrection(entryID: ids.entry)+ #expect(try await fixture.repository.commitEntryCorrection(correction, target: .init(kind: .chapter)) == .committed(entryID: ids.entry))+ default:+ #expect(try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: entry.note, rating: nil) == .committed)+ }+ let links = try await active(fixture, entry: ids.entry)+ #expect(Set(links.map { $0.pair.kind }) == Set([RecordKind.character, .place]))+ #expect(links.allSatisfy { $0.activeAcceptanceIDs.count == 1 })+ withExtendedLifetime(fixture) {}+ }++ private func teach(_ fixture: M5Fixture, _ ids: IDs) async throws {+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding known-link capture rule") { context in+ let site = Site(hostname: "example.com"); site.mode = .taught; context.insert(site)+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ context.insert(WorkSiteMembership(hostname: site.hostname, createdAt: M5Fixture.epoch, workID: work.id, work: work, site: site))+ context.insert(try TitlePattern(version: 1, isActive: true, createdAt: M5Fixture.epoch,+ definition: .phrase(prefix: "", separator: " - ", suffix: "", order: .workThenChapter), site: site))+ try context.save()+ }+ }+ @Test(arguments: ["ordinary", "chapterNew", "chapterExisting"])+ func captureTerminalsLinkFinalSavedContent(terminal: String) async throws {+ let (fixture, ids) = try await fixture()+ try await teach(fixture, ids)+ let url = "https://example.com/12", title = "Saved book - 12"+ let saved: EntrySnapshot+ if terminal == "ordinary" {+ let contract = try await fixture.repository.projectCapture(hostname: "example.com", captureTitle: title,+ captureTitleSource: .manual, rawURLString: url, canonicalURLString: nil, note: "Addie visits Harbor.", rating: nil)+ guard case .committed(let entry) = try await fixture.repository.commitCapture(contract) else { Issue.record("Expected ordinary capture"); return }+ saved = entry+ } else {+ var projection = try await fixture.repository.projectChapterCapture(rawURL: url, captureTitle: title, workID: ids.work)+ let draft = CaptureDraft(captureTitle: title, captureTitleSource: .manual, rawURLString: url, note: "Addie visits Harbor.")+ guard case .committed(let entry) = try await fixture.repository.commitChapterCapture(.init(projection: projection,+ capture: draft, intent: .newChapter(.init(kind: .chapter, designation: "12"), confirmedNew: true))) else { Issue.record("Expected chapter capture"); return }+ saved = entry+ if terminal == "chapterExisting" {+ projection = try await fixture.repository.projectChapterCapture(rawURL: url, captureTitle: title, workID: ids.work)+ guard case .committed(let same) = try await fixture.repository.commitChapterCapture(.init(projection: projection,+ capture: .init(captureTitle: title, captureTitleSource: .manual, rawURLString: url, note: "No known names."),+ intent: .existing(entry.id, contentChoice: .source))) else { Issue.record("Expected chosen destination content"); return }+ #expect(same.note == "No known names.")+ #expect(try await active(fixture, entry: same.id).isEmpty)+ withExtendedLifetime(fixture) {}; return+ }+ }+ #expect(saved.workID == ids.work && saved.note == "Addie visits Harbor.")+ #expect(Set(try await active(fixture, entry: saved.id).map { $0.pair.kind }) == Set([RecordKind.character, .place]))+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: [EntryCorrectionContentChoice.source, .destination])+ func ownershipCorrectionLinksOnlyChosenFinalContent(choice: EntryCorrectionContentChoice) async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ let destination = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding correction destination") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ let entry = Entry(id: destination, captureTitle: "Other", captureTitleSource: .manual, rawURLString: "", hostname: "",+ entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "No known names.")+ try entry.authorTarget(.init(kind: .chapter)); context.insert(entry); entry.work = work+ LibraryRepository.applyManualAssignment(to: entry, at: M5Fixture.epoch); try context.save()+ }+ let correction = try await fixture.repository.projectEntryCorrection(entryID: ids.entry, destinationID: destination)+ #expect(try await fixture.repository.commitEntryCorrection(correction, target: .init(kind: .chapter), contentChoice: choice) == .committed(entryID: destination))+ #expect(try await active(fixture, entry: destination).count == (choice == .source ? 2 : 0))+ #expect(try await active(fixture, entry: ids.entry).isEmpty)+ withExtendedLifetime(fixture) {}+ }++ @Test func removedWholeNameRetiresSupportAndKeepsExactDetachedAnnotation() async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ var entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Ada visits Harbor.", rating: nil)+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry, kind: .character, recordID: ids.character)+ let basis = try #require(try await fixture.repository.associationNoteBasis(pair: pair))+ _ = try await fixture.repository.saveAssociationNote(basis: basis, text: " Exact detached\nannotation 🌟 ")+ entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Adam visits Harbor.", rating: nil)+ #expect(try await active(fixture, entry: ids.entry).map { $0.pair.kind } == [.place])+ #expect(try await fixture.repository.detachedAssociationNotes().contains { $0.raw.text == " Exact detached\nannotation 🌟 " })+ entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Ada visits Harbor.", rating: nil)+ let returned = try #require(try await active(fixture, entry: ids.entry).first { $0.pair == pair })+ #expect(returned.noteHeads.isEmpty && returned.activeAcceptanceIDs.count == 1)+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["wrongTarget", "newTarget", "ambiguousTarget", "suppressedSpelling", "staleGuard"])+ func saveNeverSettlesUnsupportedPendingObligations(mode: String) async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ let candidate = try #require(try await fixture.repository.extractionCandidates(limit: 1, workIDs: [ids.work]).first)+ let sourceGuard = try #require(candidate.mentionIndex.sourceGuards[ids.entry])+ let marker = UUID(), key = AssociationReviewKey(kind: .place, nameKey: "harbor")+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding pending guard control") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ if mode == "ambiguousTarget" { context.insert(Place(name: "Harbor", nameKey: "harbor", workID: ids.work)) }+ let item = AssociationPendingReviewItem(key: key, targetID: mode == "newTarget" ? nil : mode == "wrongTarget" ? UUID() : ids.place, spellingKeys: ["harbor"])+ context.insert(try AssociationEvent(event: .init(id: marker, payload: .pendingReview(.init(workID: ids.work, entryID: ids.entry,+ sourceGuard: mode == "staleGuard" ? "old guard" : sourceGuard, items: [item]))), recordedAt: M5Fixture.epoch))+ if mode == "suppressedSpelling" {+ context.insert(try AssociationEvent(event: .init(payload: .reject(.init(pair: .init(workID: ids.work, entryID: ids.entry,+ kind: .place, recordID: ids.place), spellingKeys: ["harbor"]))), recordedAt: M5Fixture.epoch))+ }+ _ = work // Preserve the Work-existence assertion without an unused binding.+ try context.save()+ }+ let entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: entry.note, rating: entry.rating)+ let acknowledged = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking unsupported obligation") { context in+ try AssociationStorageInventory.read(context: context, workIDs: [ids.work], includeNotes: false).ledger.pendingReviews+ .isAcknowledged(.init(markerID: marker, key: key))+ }+ #expect(!acknowledged)+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["coherent", "tornSource", "tornTarget", "ambiguous", "retained", "higherTier"])+ func directoryAndPhysicalCopiesMustAuthorizeOneIdentity(mode: String) async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ let higher = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding known-link identity control") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ let original = try #require(CharacterRecord.rows(ids: [ids.character], context: context).first)+ switch mode {+ case "coherent": context.insert(CharacterRecord(id: ids.character, name: "Ada", nameKey: "ada", aliases: ["Addie"], work: work))+ case "tornTarget": context.insert(CharacterRecord(id: ids.character, name: "Ada", nameKey: "ada", note: "Conflicting authored notes", work: work))+ case "ambiguous": context.insert(CharacterRecord(name: "Ada", nameKey: "ada", work: work))+ case "retained": original.name = "Adelaide"; original.aliases = []+ case "higherTier": context.insert(CharacterRecord(id: higher, name: "Addie", nameKey: "addie", work: work))+ default:+ let conflict = Entry(id: ids.entry, captureTitle: "Conflict", captureTitleSource: .manual,+ rawURLString: "", hostname: "", entryIdentityKey: "", timestamp: M5Fixture.epoch, note: "Other saved text")+ try conflict.authorTarget(.init(kind: .chapter)); context.insert(conflict); conflict.work = work+ LibraryRepository.applyManualAssignment(to: conflict, at: M5Fixture.epoch)+ }+ try context.save()+ }+ let entry = try await fixture.repository.entry(id: ids.entry)+ let result = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry),+ note: mode == "higherTier" ? "Addie visits Harbor." : entry.note, rating: entry.rating)+ if mode == "tornSource" { if case .conflict = result {} else { Issue.record("Torn source must refuse") } }+ let links = try await active(fixture, entry: ids.entry)+ if mode == "tornSource" { #expect(links.isEmpty) }+ else {+ #expect(links.contains { $0.pair.kind == .place })+ let characters = links.filter { $0.pair.kind == .character }+ #expect(characters.count == (["tornTarget", "ambiguous"].contains(mode) ? 0 : 1))+ if mode == "higherTier" { #expect(characters.first?.pair.recordID == higher) }+ }+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["manual", "update", "reShare", "correction"])+ func failedSaveRollsBackLinksAndContentAcrossDiskReopen(terminal: String) async throws {+ let save = FailingSaveStrategy()+ let (fixture, ids) = try await fixture(seedEntry: true, target: terminal == "correction" ? .note : .chapter, save: save)+ let before = try await fixture.repository.backupV20Snapshot()+ let entry = try await fixture.repository.entry(id: ids.entry)+ let manual = try await fixture.repository.projectManualEntry(workID: ids.work)+ let correction = try await fixture.repository.projectEntryCorrection(entryID: ids.entry)+ let reShare = try await fixture.repository.withLockedContext(mode: .shared, operation: "reading failure fixture") { context in+ try LibraryRepository.fetchNormalisedEntryGroup(id: ids.entry, context: context).reShareBasis(hostname: "", site: nil)+ }+ save.fail = true+ await #expect(throws: LibraryRepositoryError.self) {+ switch terminal {+ case "manual": _ = try await fixture.repository.commitManualEntry(projection: manual,+ draft: .init(target: .init(kind: .chapter), note: "Ada visits Harbor.", existingEntryID: ids.entry))+ case "reShare": _ = try await fixture.repository.commitReShareUpdate(basis: reShare, note: "Ada visits Harbor.", rating: nil)+ case "correction": _ = try await fixture.repository.commitEntryCorrection(correction, target: .init(kind: .chapter))+ default: _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Ada visits Harbor.", rating: nil)+ }+ }+ save.fail = false+ await fixture.repository.shutdown()+ let reopened = try await LibraryRepository.openForApp(.init(rootDirectory: fixture.directory)).repository+ #expect(try await reopened.backupV20Snapshot() == before)+ await reopened.shutdown()+ withExtendedLifetime(fixture) {}+ }++ @Test func cancelledProjectionAndStaleEntrySaveNeverCreateLinks() async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ let before = try await fixture.repository.backupV20Snapshot()+ _ = try await fixture.repository.projectManualEntry(workID: ids.work)+ #expect(try await fixture.repository.backupV20Snapshot() == before)+ let stale = try await fixture.repository.withLockedContext(mode: .shared, operation: "capturing stale re-share basis") { context in+ try LibraryRepository.fetchNormalisedEntryGroup(id: ids.entry, context: context).reShareBasis(hostname: "", site: nil)+ }+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "arriving later note") { context in+ let entry = try #require(context.fetch(FetchDescriptor<Entry>()).first { $0.id == ids.entry })+ entry.note = "New text"; entry.modifiedAt = M5Fixture.epoch.addingTimeInterval(20); try context.save()+ }+ let current = try await fixture.repository.backupV20Snapshot()+ if case .stale = try await fixture.repository.commitReShareUpdate(basis: stale, note: "Ada visits Harbor.", rating: nil) {} else { Issue.record("Stale re-share must refuse") }+ #expect(try await fixture.repository.backupV20Snapshot() == current)+ withExtendedLifetime(fixture) {}+ }++ @Test func movingChapterLinksOnlyDestinationWorkRecords() async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ var entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: entry.note, rating: nil)+ let destination = UUID(), character = UUID(), place = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding destination known directory") { context in+ let work = Work(id: destination, displayTitle: "Destination", timestamp: M5Fixture.epoch); context.insert(work)+ context.insert(CharacterRecord(id: character, name: "Ada", nameKey: "ada", work: work))+ context.insert(Place(id: place, name: "Harbor", nameKey: "harbor", workID: destination)); try context.save()+ }+ entry = try await fixture.repository.entry(id: ids.entry)+ #expect(try await fixture.repository.moveEntry(ids.entry, basis: .init(entry: entry), to: .existing(destination)) == .committed)+ let links = try await active(fixture, entry: ids.entry)+ #expect(links.count == 2 && links.allSatisfy { $0.pair.workID == destination })+ #expect(Set(links.map { $0.pair.recordID }) == [character, place])+ withExtendedLifetime(fixture) {}+ }++ @Test func reparseAssignmentUsesItsFinalSavedWorkAndNote() async throws {+ let (fixture, ids) = try await fixture()+ try await teach(fixture, ids)+ let entry = try await fixture.repository.capture(.init(captureTitle: "Saved book - 13", captureTitleSource: .manual,+ rawURLString: "https://example.com/13", note: "Ada visits Harbor."))+ #expect(entry.workID == nil)+ #expect(try await active(fixture, entry: entry.id).isEmpty)+ let contract = try await fixture.repository.projectReparse(entryID: entry.id)+ #expect(try await fixture.repository.commitReparse(contract) == .committed)+ #expect(try await fixture.repository.entry(id: entry.id).workID == ids.work)+ #expect(Set(try await active(fixture, entry: entry.id).map { $0.pair.kind }) == Set([RecordKind.character, .place]))+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["ordinary", "chapterNew"])+ func failedCaptureRollsBackNewEntryLinksAndScopeAcrossDiskReopen(terminal: String) async throws {+ let save = FailingSaveStrategy()+ let (fixture, ids) = try await fixture(save: save)+ try await teach(fixture, ids)+ let url = "https://example.com/failure", title = "Saved book - 14"+ let capture = try await fixture.repository.projectCapture(hostname: "example.com", captureTitle: title,+ captureTitleSource: .manual, rawURLString: url, canonicalURLString: nil, note: "Ada visits Harbor.", rating: nil)+ let chapter = try await fixture.repository.projectChapterCapture(rawURL: url, captureTitle: title, workID: ids.work)+ let before = try await fixture.repository.backupV20Snapshot()+ save.fail = true+ await #expect(throws: LibraryRepositoryError.self) {+ if terminal == "ordinary" { _ = try await fixture.repository.commitCapture(capture) }+ else {+ _ = try await fixture.repository.commitChapterCapture(.init(projection: chapter,+ capture: .init(captureTitle: title, captureTitleSource: .manual, rawURLString: url, note: "Ada visits Harbor."),+ intent: .newChapter(.init(kind: .chapter, designation: "14"), confirmedNew: true)))+ }+ }+ save.fail = false+ await fixture.repository.shutdown()+ let reopened = try await LibraryRepository.openForApp(.init(rootDirectory: fixture.directory)).repository+ #expect(try await reopened.backupV20Snapshot() == before)+ await reopened.shutdown()+ withExtendedLifetime(fixture) {}+ }++ @Test func sameUUIDAcrossKindsIsAmbiguousAndOtherWorkNamesNeverLeak() async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding independent namespaces") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ context.insert(CharacterRecord(id: ids.place, name: "Harbor", nameKey: "harbor", work: work))+ let other = Work(displayTitle: "Unrelated Work", timestamp: M5Fixture.epoch); context.insert(other)+ context.insert(CharacterRecord(name: "Newtown", nameKey: "newtown", work: other))+ context.insert(Place(name: "Newtown", nameKey: "newtown", workID: other.id)); try context.save()+ }+ let entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Harbor and Newtown.", rating: nil)+ let links = try await active(fixture, entry: ids.entry)+ #expect(links.isEmpty)+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["differentUUID", "suppressedOpposite", "tornVariant", "alias", "retained", "existingAccepted"])+ func crossKindClaimsCannotSupplyLiteralKindAuthority(mode: String) async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry, kind: .place, recordID: ids.place)+ if mode == "existingAccepted" {+ _ = try await fixture.repository.commitDecision(.init(workID: ids.work, kind: .place, action: .accept,+ displayedKeys: ["harbor"], displayedTargetID: ids.place, proposedName: "Harbor",+ mentions: [.init(entryID: ids.entry, noteFingerprint: CharacterCoverageFingerprint.of("Ada visits Harbor and Newtown."), spellingKeys: ["harbor"])]))+ }+ let before = try await active(fixture, entry: ids.entry).first { $0.pair == pair }+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding cross-kind literal ambiguity") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ let name = mode == "tornVariant" ? "Briar" : "Harbor"+ context.insert(CharacterRecord(name: mode == "alias" || mode == "retained" ? "Mariner" : name,+ nameKey: mode == "retained" ? "harbor" : RecordNameKey.normalize(mode == "alias" ? "Mariner" : name),+ aliases: mode == "alias" ? ["Harbor"] : [], work: work))+ if mode == "tornVariant" {+ context.insert(Place(id: ids.place, name: "Briar", nameKey: "briar", workID: ids.work))+ }+ if mode == "suppressedOpposite" {+ context.insert(try AssociationEvent(event: .init(payload: .reject(.init(pair: pair, spellingKeys: ["harbor"]))), recordedAt: M5Fixture.epoch))+ }+ try context.save()+ }+ let entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry),+ note: mode == "tornVariant" ? "Briar." : "Harbor.", rating: nil)+ let links = try await active(fixture, entry: ids.entry)+ if mode == "existingAccepted" {+ #expect(links.count == 1 && links.first?.pair == pair)+ #expect(links.first?.activeAcceptanceIDs == before?.activeAcceptanceIDs)+ } else { #expect(links.isEmpty) }+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: ["current", "retained", "alias", "higherTier", "unrelated"])+ func unsafePhysicalVariantClaimsRespectWinningTier(mode: String) async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ let coherent = UUID(), unsafe = UUID()+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding same-kind physical claim tiers") { context in+ let work = try #require(context.fetch(FetchDescriptor<Work>()).first { $0.id == ids.work })+ context.insert(CharacterRecord(id: unsafe, name: "Harbor", nameKey: "harbor", work: work))+ context.insert(CharacterRecord(id: unsafe, name: mode == "current" ? "Briar" : "Other",+ nameKey: mode == "retained" ? "briar" : "other",+ aliases: ["alias", "higherTier"].contains(mode) ? ["Briar"] : [], work: work))+ context.insert(CharacterRecord(id: coherent, name: ["retained", "alias"].contains(mode) ? "Mariner" : "Briar",+ nameKey: mode == "retained" ? "briar" : "mariner",+ aliases: mode == "alias" ? ["Briar"] : [], work: work))+ try context.save()+ }+ let entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry), note: "Briar.", rating: nil)+ let links = try await active(fixture, entry: ids.entry)+ if ["higherTier", "unrelated"].contains(mode) {+ #expect(links.count == 1 && links.first?.pair.recordID == coherent)+ } else { #expect(links.isEmpty) }+ withExtendedLifetime(fixture) {}+ }++ @Test(arguments: [false, true])+ func spellingRejectionStandsWhileIndependentAcceptedAliasMayLink(alternateAlias: Bool) async throws {+ let (fixture, ids) = try await fixture(seedEntry: true)+ let pair = AssociationPair(workID: ids.work, entryID: ids.entry, kind: .character, recordID: ids.character)+ let rejection = AssociationLedgerEvent(payload: .reject(.init(pair: pair, spellingKeys: ["ada"])))+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding standing spelling rejection") { context in+ context.insert(try AssociationEvent(event: rejection, recordedAt: M5Fixture.epoch)); try context.save()+ }+ let entry = try await fixture.repository.entry(id: ids.entry)+ _ = try await fixture.repository.updateEntry(id: ids.entry, basis: .init(entry: entry),+ note: alternateAlias ? "Addie visits Harbor." : entry.note, rating: nil)+ #expect(try await active(fixture, entry: ids.entry).contains { $0.pair == pair } == alternateAlias)+ let stored = try await fixture.repository.withLockedContext(mode: .shared, operation: "checking rejection preservation") { context in+ let storage = try AssociationStorageInventory.read(context: context, workIDs: [ids.work], includeNotes: false)+ return (storage.ledger.isSuppressed(pair: pair, spellingKey: "ada"), storage.rawEvents.compactMap(\.value).compactMap { event -> AssociationAcceptance? in+ if case .accept(let value) = event.payload, value.pair == pair { return value }; return nil+ })+ }+ #expect(stored.0 && stored.1.allSatisfy { $0.reconsideredRejectionIDs.isEmpty && !$0.spellingKeys.contains("ada") })+ withExtendedLifetime(fixture) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SelectedWorkNoEpisodeReaderTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SelectedWorkNoEpisodeReaderTests.swiftnew file mode 100644index 00000000..862d4e2a--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/SelectedWorkNoEpisodeReaderTests.swift@@ -0,0 +1,129 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("Selected Work no-episode histories", .serialized)+@MainActor+struct SelectedWorkNoEpisodeReaderTests {+ private func store() throws -> (ModelContainer, ModelContext) {+ let schema = Schema([NoEpisodeAction.self])+ let container = try ModelContainer(for: schema, configurations: [+ ModelConfiguration(schema: schema, isStoredInMemoryOnly: true, cloudKitDatabase: .none)+ ])+ let context = ModelContext(container); context.autosaveEnabled = false+ return (container, context)+ }+ private func mark(_ work: UUID) throws -> NoEpisodeHistory.Action {+ try .init(workID: work, key: "mark/\(UUID().uuidString)", day: "2026-09-29", kind: .mark, observedClearKeys: [])+ }+ private func row(_ action: NoEpisodeHistory.Action) throws -> NoEpisodeAction {+ NoEpisodeAction(workID: action.workID, key: action.key, payloadData: try action.canonicalData())+ }++ @Test(arguments: ["json", "version", "day", "payloadKey", "ack", "columnKey", "conflict"], [false, true])+ func damageRetainsLazyScopeAndGlobalRefusal(fault: String, selected: Bool) throws {+ let (container, context) = try store(); defer { _ = container }+ let healthy = UUID(), damaged = UUID()+ let good = try mark(healthy), bad = try mark(damaged)+ context.insert(try row(good))+ var object = try #require(JSONSerialization.jsonObject(with: bad.canonicalData()) as? [String: Any])+ switch fault {+ case "version": object["version"] = 2+ case "day": object["day"] = "2026-02-30"+ case "payloadKey": object["key"] = "mark/invalid"+ case "ack": object["observedClearKeys"] = ["clear/invalid"]+ default: break+ }+ let bytes = fault == "json" ? Data("broken".utf8) : try JSONSerialization.data(withJSONObject: object)+ context.insert(NoEpisodeAction(workID: damaged,+ key: fault == "columnKey" ? "mark/\(UUID().uuidString)" : bad.key, payloadData: bytes))+ if fault == "conflict" {+ let conflict = try NoEpisodeHistory.Action(workID: damaged, key: bad.key, day: "2026-09-30", kind: .mark, observedClearKeys: [])+ context.insert(try row(conflict))+ }+ let global = try NoEpisodeIndex(context: context)+ let scoped = try SelectedWorkNoEpisodeReader(context: context, workIDs: selected ? [healthy, damaged] : [healthy])+ #expect(try scoped.history(for: healthy) == global.history(for: healthy))+ if selected {+ #expect(throws: Error.self) { try scoped.history(for: damaged) }+ } else {+ #expect(try scoped.history(for: damaged) == .empty)+ }+ #expect(throws: Error.self) { try global.history(for: damaged) }+ #expect(throws: Error.self) { try global.allActions }+ #expect(throws: Error.self) { try NoEpisodeWriter.insertMissing([good], context: context) }+ }++ @Test func currentColumnOwnsMovedStableKeyAndIdenticalCopies() throws {+ let (container, context) = try store(); defer { _ = container }+ let origin = UUID(), destination = UUID(), entry = UUID()+ let action = try NoEpisodeHistory.Action(workID: destination,+ key: "note/\(entry.uuidString)/\(origin.uuidString)/0/2026-09-29", day: "2026-09-29", kind: .clear, observedClearKeys: [])+ context.insert(try row(action)); context.insert(try row(action))+ let selected = try SelectedWorkNoEpisodeReader(context: context, workIDs: [destination])+ #expect(try selected.history(for: destination).actions == [action])+ #expect(try selected.history(for: destination) == NoEpisodeIndex(context: context).history(for: destination))+ let oldOwner = try SelectedWorkNoEpisodeReader(context: context, workIDs: [origin])+ #expect(try oldOwner.history(for: origin) == .empty)+ #expect(try oldOwner.history(for: destination) == .empty)+ #expect(try context.fetchCount(FetchDescriptor<NoEpisodeAction>()) == 2)+ }++ @Test func freshSelectedReadIncludesPendingInsertRepointAndDeletion() throws {+ let (container, context) = try store(); defer { _ = container }+ let origin = UUID(), destination = UUID()+ let original = try mark(origin), removed = try mark(destination), inserted = try mark(destination)+ let movingRow = try row(original), removedRow = try row(removed)+ context.insert(movingRow); context.insert(removedRow); try context.save()+ movingRow.workID = destination; context.delete(removedRow); context.insert(try row(inserted))+ let selected = try SelectedWorkNoEpisodeReader(context: context, workIDs: [destination])+ let global = try NoEpisodeIndex(context: context)+ #expect(try selected.history(for: destination) == global.history(for: destination))+ #expect(try selected.history(for: destination).actions.count == 2)+ #expect(try selected.history(for: origin) == .empty)+ try context.save()+ #expect(try SelectedWorkNoEpisodeReader(context: context, workIDs: [destination]).history(for: destination)+ == NoEpisodeIndex(context: context).history(for: destination))+ #expect(try SelectedWorkNoEpisodeReader(context: context, workIDs: []).history(for: destination) == .empty)+ let fresh = ModelContext(container); fresh.autosaveEnabled = false+ let freshSelected = try SelectedWorkNoEpisodeReader(context: fresh, workIDs: [origin, destination])+ let freshGlobal = try NoEpisodeIndex(context: fresh)+ let moved = try NoEpisodeHistory.Action(workID: destination, key: original.key,+ day: original.day, kind: original.kind, observedClearKeys: original.observedClearKeys)+ let expected = try NoEpisodeHistory([moved, inserted])+ #expect(try freshSelected.history(for: destination) == expected)+ #expect(try freshSelected.history(for: destination) == freshGlobal.history(for: destination))+ #expect(try freshSelected.history(for: origin) == .empty)+ #expect(try freshGlobal.history(for: origin) == .empty)+ }++ @Test func creatorDetailPreservesCompleteValuesAndSelectedDamageRefuses() async throws {+ let fixture = try await M5Fixture(); defer { withExtendedLifetime(fixture) {} }+ let creator = UUID(), work = UUID(), outside = UUID()+ try await fixture.repository.seedCreators([SeedCreator(id: creator, name: "Writer",+ nameModifiedAt: M5Fixture.epoch, createdAt: M5Fixture.epoch)])+ try await fixture.repository.seedM5Rows(sites: [M5SeedSite(hostname: "selected-history.example")],+ works: [M5SeedWork(id: work, displayTitle: "Selected", hostname: "selected-history.example")])+ try await fixture.repository.seedCredits([SeedCredit(workID: work, creatorID: creator, roleIDs: [])])+ let action = try mark(work)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding selected history") { @Sendable [work, action] context in+ context.insert(NoEpisodeAction(workID: work, key: action.key, payloadData: try action.canonicalData()))+ try context.save()+ }+ let before = try #require(try await fixture.repository.creatorDetail(id: creator))+ #expect(before.works.count == 1)+ #expect(before.works.first?.work.noEpisodeHistory.actions == [action])+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding unrelated damaged history") { @Sendable [outside] context in+ context.insert(NoEpisodeAction(workID: outside, key: "bad", payloadData: Data("broken".utf8)))+ try context.save()+ }+ let after = try await fixture.repository.creatorDetail(id: creator)+ #expect(after == before)+ try await fixture.repository.withLockedContext(mode: .exclusive, operation: "seeding selected damaged history") { @Sendable [work] context in+ context.insert(NoEpisodeAction(workID: work, key: "bad", payloadData: Data("broken".utf8)))+ try context.save()+ }+ await #expect(throws: Error.self) { try await fixture.repository.creatorDetail(id: creator) }+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swiftindex 3cfbf4a2..47998510 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteReconcilerTests.swift@@ -453,12 +453,12 @@ private final class ReconcilerStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismSiteReconciler-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) self.saveStrategy = saveStrategy ?? saveRecorder
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swiftindex 737ba411..7cd1e965 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/SiteUnionProjectionTests.swift@@ -429,12 +429,12 @@ private final class ProjectionStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismSiteUnion-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swiftindex e47f0168..b3f194c8 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/StoreMetadataTests.swift@@ -209,7 +209,7 @@ struct StoreMetadataTests { try #require(FileManager.default.fileExists(atPath: dir.storeURL.path + "-wal"), "the conversion has to be in the log for this to be the hazard") - #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["20.0.0"],+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: dir.storeURL) == ["21.0.0"], "the conversion is committed in the log, so a reader of the log sees it") #expect(StoreMetadata.recordedVersion(at: dir.storeURL) == .atOrAboveV5, "a reader that ignored the log would still have to answer, not refuse")
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swiftindex 2dfdbec5..2ce52aed 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailBytesReachTests.swift@@ -80,6 +80,8 @@ struct ThumbnailBytesReachTests { "AsterismSchemaV16.swift", "AsterismSchemaV17Models.swift", "AsterismSchemaV18Models.swift", "AsterismSchemaV19Models.swift",+ // Frozen V20 declares the same stored relationship/blob, with no live accessor.+ "AsterismSchemaV20Models.swift", "GroupOrdering.swift", "Thumbnails/ThumbnailStoreProbe.swift", "LibraryRepository+Thumbnails.swift",
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swiftindex e2b69969..33be4c6b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ThumbnailStoreProbeTests.swift@@ -55,7 +55,7 @@ struct ThumbnailStoreProbeTests { let probeNames = Set(ThumbnailStoreProbe.schema.entities.map(\.name)) #expect(probeNames == ["ProbeExternalWork", "ProbeInlineWork"]) - let live = Set(Schema(versionedSchema: AsterismSchemaV20.self).entities.map(\.name))+ let live = Set(Schema(versionedSchema: AsterismSchemaV21.self).entities.map(\.name)) let frozen = Set(Schema(versionedSchema: AsterismSchemaV16.self).entities.map(\.name)) #expect(live.isDisjoint(with: probeNames)) #expect(frozen.isDisjoint(with: probeNames))
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swiftindex 4ebbd8b3..58a1749d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/ToReadMatcherTests.swift@@ -801,7 +801,7 @@ private final class MatchStore { let context: ModelContext init() throws {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) container = try ModelContainer( for: schema, configurations: [ModelConfiguration(
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swiftindex 8b5007c3..cd772d16 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/URLOptionalSequenceTests.swift@@ -945,7 +945,7 @@ struct URLOptionalSequenceArchiveTests { #expect(decoded.payload == payload) #expect(try Self.combinedRule(of: decoded.payload)?.sequencePresence == .optional) - let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let container = try ModelContainer( for: schema, configurations: [
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swiftindex 0b7dbf84..2d843aa8 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V16RecordedStoreTests.swift@@ -63,8 +63,8 @@ struct V16RecordedStoreTests { return } // The stage completed and the marker moved, in that order.- #expect(try root.recordedVersions() == ["20.0.0"])- #expect(try root.markerText() == "20")+ #expect(try root.recordedVersions() == ["21.0.0"])+ #expect(try root.markerText() == "21") #expect(counts.works == 1) #expect(counts.entries == 3) #expect(counts.sites == 1)@@ -393,8 +393,8 @@ struct V16RecordedStoreTests { #expect(try LibraryRepository.classify(root.configuration, fileManager: .default) == .ready) let (_, second) = try await LibraryRepository.openForApp(root.configuration) await second.shutdown()- #expect(try root.markerText() == "20")- #expect(try root.recordedVersions() == ["20.0.0"])+ #expect(try root.markerText() == "21")+ #expect(try root.recordedVersions() == ["21.0.0"]) withExtendedLifetime(root) {} } }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swiftindex 28c1dee7..e0eb7b6b 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V17RecordedStoreTests.swift@@ -40,9 +40,9 @@ struct V17RecordedStoreTests { #expect(facts.2 == 0) #expect(facts.3) #expect(try String(contentsOf: configuration.readinessMarkerURL,- encoding: .utf8) == "20\n")+ encoding: .utf8) == "21\n") #expect(try V4RecordedStoreFixture.recordedModelVersions(- at: configuration.storeURL) == ["20.0.0"])+ at: configuration.storeURL) == ["21.0.0"]) await repository.shutdown() }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swiftindex 0b3f1c29..d7a5793d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V18RecordedStoreTests.swift@@ -44,14 +44,14 @@ struct V18RecordedStoreTests { #expect(facts.4 == confirmation) #expect(facts.5 == thumbnail) #expect(facts.6 == [payload])- #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "20\n")- #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["20.0.0"])+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "21\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["21.0.0"]) let (_, extensionRepository) = try await LibraryRepository.openForExtension(configuration) await extensionRepository.shutdown() } @Test("App accepts 16–19 while the extension refuses every lagging marker",- arguments: ["16", "17", "18", "19", "20"])+ arguments: ["16", "17", "18", "19", "20", "21"]) func markerContracts(marker: String) async throws { let root = FileManager.default.temporaryDirectory.appending(path: "Marker19-\(UUID())") defer { try? FileManager.default.removeItem(at: root) }@@ -60,14 +60,14 @@ struct V18RecordedStoreTests { await initial.shutdown() try Data("\(marker)\n".utf8).write(to: configuration.readinessMarkerURL) #expect(try LibraryRepository.classify(configuration, fileManager: .default)- == (marker == "20" ? .ready : .markerLagging(generation: marker)))- if marker != "20" {+ == (marker == "21" ? .ready : .markerLagging(generation: marker)))+ if marker != "21" { await #expect(throws: Error.self) { try await LibraryRepository.openForExtension(configuration) } #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "\(marker)\n") } let (_, app) = try await LibraryRepository.openForApp(configuration) await app.shutdown()- #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "20\n")+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "21\n") } private func seed(at url: URL, workID: UUID, confirmation: Data, thumbnail: Data,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/V20RecordedStoreTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/V20RecordedStoreTests.swiftnew file mode 100644index 00000000..9c9f172f--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/V20RecordedStoreTests.swift@@ -0,0 +1,79 @@+import Foundation+import SwiftData+import Testing+@testable import AsterismCore++@Suite("V20 association-ledger migration", .serialized)+struct V20RecordedStoreTests {+ @Test func populatedRecordedV20PreservesAuthoredDataWithoutBackfill() async throws {+ let root = FileManager.default.temporaryDirectory.appending(path: "AssociationV20-\(UUID())")+ defer { try? FileManager.default.removeItem(at: root) }+ let configuration = LibraryConfiguration(rootDirectory: root)+ try FileManager.default.createDirectory(at: configuration.storeURL.deletingLastPathComponent(),+ withIntermediateDirectories: true)+ let workID = UUID(), entryID = UUID(), characterID = UUID(), placeID = UUID()+ try seed(at: configuration.storeURL, workID: workID, entryID: entryID,+ characterID: characterID, placeID: placeID)+ try Data("20\n".utf8).write(to: configuration.readinessMarkerURL)+ await #expect(throws: Error.self) { try await LibraryRepository.openForExtension(configuration) }+ let (_, repository) = try await LibraryRepository.openForApp(configuration)+ let actual = try await repository.withLockedContext(mode: .shared, operation: "checking V20 ledger migration") { context in+ let work = try #require(try context.fetch(FetchDescriptor<Work>()).first)+ let entry = try #require(try context.fetch(FetchDescriptor<Entry>()).first)+ let character = try #require(try context.fetch(FetchDescriptor<CharacterRecord>()).first)+ let place = try #require(try context.fetch(FetchDescriptor<Place>()).first)+ #expect(character.facts == [RecordFact(statement: "Arrived", quote: "Alice", nameKey: "alice", source: .entry(entryID))])+ #expect(place.facts == [RecordFact(statement: "Visited", quote: "Harbor", nameKey: "harbor", source: .entry(entryID))])+ return (work.id, work.chapterCaptureDefaultRaw, entry.id, entry.note, entry.rawURLString,+ character.id, character.aliases, place.id, place.note,+ try context.fetchCount(FetchDescriptor<AssociationEvent>()),+ try context.fetchCount(FetchDescriptor<PairNoteVersion>()))+ }+ await repository.shutdown()+ #expect(actual.0 == workID && actual.1 == "ordinary")+ #expect(actual.2 == entryID && actual.3 == "Alice visited Harbor." && actual.4.isEmpty)+ #expect(actual.5 == characterID && actual.6 == ["Ally"])+ #expect(actual.7 == placeID && actual.8 == "Preserve record note")+ #expect(actual.9 == 0 && actual.10 == 0)+ #expect(try String(contentsOf: configuration.readinessMarkerURL, encoding: .utf8) == "21\n")+ #expect(try V4RecordedStoreFixture.recordedModelVersions(at: configuration.storeURL) == ["21.0.0"])+ }++ @Test func schemaAddsOnlyTwoRelationshipFreeTables() throws {+ #expect(BackupV20Document.schemaVersion == AsterismSchemaV21.versionIdentifier.major)+ #expect(BackupV20Document.formatVersion == 20)+ let old = Schema(versionedSchema: AsterismSchemaV20.self)+ let live = Schema(versionedSchema: AsterismSchemaV21.self)+ #expect(Set(live.entities.map(\.name)).subtracting(old.entities.map(\.name)) == ["AssociationEvent", "PairNoteVersion"])+ for entity in old.entities {+ let counterpart = try #require(live.entities.first { $0.name == entity.name })+ #expect(entity.properties.map(\.name).sorted() == counterpart.properties.map(\.name).sorted())+ }+ for name in ["AssociationEvent", "PairNoteVersion"] {+ let entity = try #require(live.entities.first { $0.name == name })+ #expect(entity.relationships.isEmpty)+ #expect(entity.attributes.allSatisfy { !$0.isUnique })+ }+ }++ /// Release the frozen container before opening the live schema. SwiftData's+ /// model registry is global; serial Core execution preserves this ordering.+ private func seed(at url: URL, workID: UUID, entryID: UUID,+ characterID: UUID, placeID: UUID) throws {+ let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let container = try ModelContainer(for: schema, configurations: [+ ModelConfiguration("AsterismV3", schema: schema, url: url, cloudKitDatabase: .none)])+ let context = ModelContext(container)+ let work = AsterismSchemaV20.Work(); work.id = workID; work.displayTitle = "Synthetic ledger migration"+ let entry = AsterismSchemaV20.Entry(); entry.id = entryID; entry.note = "Alice visited Harbor."; entry.work = work+ let character = AsterismSchemaV20.Character(); character.id = characterID; character.name = "Alice"+ character.aliases = ["Ally"]; character.work = work+ character.factsData = RecordFactCodec.encode([RecordFact(statement: "Arrived", quote: "Alice", nameKey: "alice", source: .entry(entryID))])+ let place = AsterismSchemaV20.Place(); place.id = placeID; place.name = "Harbor"+ place.workID = workID; place.note = "Preserve record note"+ place.factsData = RecordFactCodec.encode([RecordFact(statement: "Visited", quote: "Harbor", nameKey: "harbor", source: .entry(entryID))])+ context.insert(work); context.insert(entry); context.insert(character); context.insert(place)+ try context.save()+ withExtendedLifetime(container) {}+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swiftindex 02c1648c..33598f7e 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkRecordCopyRepositoryTests.swift@@ -209,19 +209,19 @@ struct WorkRecordCopyRepositoryTests { let fixture = try await fixture() let preview = try await preview(fixture.repository, includeNotes: true) _ = try await fixture.repository.commitRecordCopy(preview)- let payload = try await fixture.repository.backupV19Snapshot()- let archive = try BackupV19Codec.encode(+ let payload = try await fixture.repository.backupV20Snapshot()+ let archive = try BackupV20Codec.encode( payload: payload, metadata: .init(appBuild: "tests", exportedAt: M5Fixture.epoch)) let plan = try BackupImporter.plan(from: archive) let restored = try await M5Fixture() _ = try await restored.repository.confirmImport(plan: plan) _ = try await restored.repository.confirmImport(plan: plan)- let after = try await restored.repository.backupV19Snapshot()- #expect(after.characters.count == 2 && after.places.count == 2)- #expect(Set(after.characters.map(\.id)) == Set(payload.characters.map(\.id)))- let copied = try #require(after.characters.first { $0.workID == destination })+ let after = try await restored.repository.backupV20Snapshot()+ #expect(after.library.characters.count == 2 && after.library.places.count == 2)+ #expect(Set(after.library.characters.map(\.id)) == Set(payload.library.characters.map(\.id)))+ let copied = try #require(after.library.characters.first { $0.workID == destination }) #expect(- copied.note == "secret" && after.places.first { $0.workID == destination }?.note == "setting")+ copied.note == "secret" && after.library.places.first { $0.workID == destination }?.note == "setting") let basis = RecordEditBasis( kind: .character, recordID: copied.id, name: copied.name, note: copied.note, aliases: copied.aliases, facts: copied.facts)@@ -231,14 +231,14 @@ struct WorkRecordCopyRepositoryTests { .update(basis: basis, draft: .init(kind: .character, name: "Corrected", note: "local")) ]) #expect(- try await restored.repository.backupV19Snapshot().characters.first { $0.id == character }?+ try await restored.repository.backupV20Snapshot().library.characters.first { $0.id == character }? .name == "Robert") let corrected = RecordEditBasis( kind: .character, recordID: copied.id, name: "Corrected", note: "local", aliases: [], facts: []) _ = try await restored.repository.commitRecordEdits( workID: destination, operations: [.delete(basis: corrected)])- #expect(try await restored.repository.backupV19Snapshot().characters.count == 1)+ #expect(try await restored.repository.backupV20Snapshot().library.characters.count == 1) } @Test(arguments: ["orphan", "offOwner", "key"])
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swiftindex 0f87ef65..fd259216 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeConvergenceTests.swift@@ -31,9 +31,9 @@ struct WorkTypeConvergenceTests { directory = FileManager.default.temporaryDirectory .appending(path: "WorkTypeConvergence-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swiftindex 08b0dc30..d485b2a8 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypeOrderingTests.swift@@ -30,9 +30,9 @@ struct WorkTypeOrderingTests { directory = FileManager.default.temporaryDirectory .appending(path: "WorkTypeOrdering-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [ ModelConfiguration( "AsterismV3", schema: schema,
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swiftindex c1da30e8..58801395 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WorkTypePlumbingTests.swift@@ -30,12 +30,12 @@ struct WorkTypePlumbingTests { directory = FileManager.default.temporaryDirectory .appending(path: "WorkTypePlumbing-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swiftindex e417b38f..d8bf6f8d 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WriteSiteRelationshipTests.swift@@ -410,7 +410,7 @@ struct WriteSiteRelationshipTests { /// format change, no marker republication, no second pass. @Test("materializeArchive wires both relationships from its sitesByHostname map") func materializeWiresBothRelationships() throws {- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let container = try ModelContainer( for: schema, configurations: [ModelConfiguration(@@ -439,7 +439,7 @@ struct WriteSiteRelationshipTests { let dir = try TempDir("WriteSiteImportFill") let cfg = configuration(dir) let (_, repository) = try await LibraryRepository.openForApp(cfg)- #expect(try markerContent(cfg) == "20",+ #expect(try markerContent(cfg) == "21", "mark-at-birth certifies an empty store at the current generation") let plan = try importPlan()@@ -448,7 +448,7 @@ struct WriteSiteRelationshipTests { Issue.record("expected committed, got \(result)") return }- #expect(try markerContent(cfg) == "20", "the import republishes nothing")+ #expect(try markerContent(cfg) == "21", "the import republishes nothing") try expectEveryRelationshipPopulated(cfg) withExtendedLifetime(dir) {} }@@ -466,7 +466,7 @@ struct WriteSiteRelationshipTests { Issue.record("expected committed, got \(result)") return }- #expect(try markerContent(cfg) == "20")+ #expect(try markerContent(cfg) == "21") try expectEveryRelationshipPopulated(cfg) withExtendedLifetime(dir) {} }
diff --git a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swiftindex e04e334a..b97f7431 100644--- a/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift+++ b/Packages/AsterismCore/Tests/AsterismCoreTests/WrongHostWorkURLValidatorTests.swift@@ -407,12 +407,12 @@ final class WrongHostStore { directory = FileManager.default.temporaryDirectory .appending(path: "AsterismWrongHostWorkURL-\(UUID())", directoryHint: .isDirectory) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)- let schema = Schema(versionedSchema: AsterismSchemaV20.self)+ let schema = Schema(versionedSchema: AsterismSchemaV21.self) let configuration = ModelConfiguration( "AsterismV3", schema: schema, url: directory.appending(path: "library.store"), cloudKitDatabase: .none) container = try ModelContainer(- for: schema, migrationPlan: AsterismV20MigrationPlan.self,+ for: schema, migrationPlan: AsterismV21MigrationPlan.self, configurations: [configuration]) context = ModelContext(container) }
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/AssociationProposalTests.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/AssociationProposalTests.swiftnew file mode 100644index 00000000..b364ddd9--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/AssociationProposalTests.swift@@ -0,0 +1,114 @@+import AsterismCore+import Foundation+import Testing+@testable import AsterismIntelligence++@Suite("Association proposal eligibility")+struct AssociationProposalTests {+ @Test func existingNameOnlySurvivesUntilItsChapterLinkIsActive() throws {+ let work = UUID(), entry = UUID(), record = UUID()+ let pair = AssociationPair(workID: work, entryID: entry, kind: .character, recordID: record)+ var context = CharacterExtractionContext(records: [.character: [.init(id: record, name: "Nova", retainedKey: "nova")]],+ acceptedFacts: [:], suppressedNameKeys: [:], suppressedFacts: [:],+ mentionIndex: .init(workID: work, eligibleEntries: [entry], eligibilityByEntry: [entry: "basis"], activePairs: [], decisions: [:]))+ let candidate = GroundedCandidate(name: "Nova", nameKey: "nova", kind: .character,+ proposedAliases: [], source: .entry(entry), facts: [])+ func assemble(_ context: CharacterExtractionContext) -> [ExtractionProposal] {+ CharacterExtractionAssembler.assemble([candidate], revisions: [.entry(entry): "note"], context: context, pass: .automatic)+ }+ let proposal = try #require(assemble(context).first)+ #expect(proposal.mentions == [.init(entryID: entry, noteFingerprint: "note", spellingKeys: ["nova"])])+ #expect(proposal.completedSources.first?.mentionEligibilityDigest == "basis")+ #expect(proposal.decisionRequest(workID: work, action: .accept).mentions == proposal.mentions)+ context.mentionIndex.activePairs = [pair]+ #expect(assemble(context).isEmpty)+ }+ @Test func automaticRejectIsNarrowAndManualCarriesObservedAcknowledgement() throws {+ let work = UUID(), entry = UUID(), record = UUID(), rejection = UUID()+ let pair = AssociationPair(workID: work, entryID: entry, kind: .place, recordID: record)+ let index = AssociationMentionIndex(workID: work, eligibleEntries: [entry], eligibilityByEntry: [entry: "basis"], activePairs: [],+ decisions: [pair: ["nova": .init(rejectionIDs: [rejection], suppressed: true)]])+ let context = CharacterExtractionContext(records: [.place: [.init(id: record, name: "Nova", retainedKey: "nova")]],+ acceptedFacts: [:], suppressedNameKeys: [:], suppressedFacts: [:], mentionIndex: index)+ let candidate = GroundedCandidate(name: "Nova", nameKey: "nova", kind: .place, proposedAliases: [], source: .entry(entry), facts: [])+ #expect(CharacterExtractionAssembler.assemble([candidate], revisions: [.entry(entry): "note"], context: context, pass: .automatic).isEmpty)+ let manual = try #require(CharacterExtractionAssembler.assemble([candidate], revisions: [.entry(entry): "note"], context: context, pass: .manual).first)+ #expect(manual.mentions.first?.observedRejectionIDs == [rejection])+ }+ @Test func genericNotesNeverCreateMentionDecision() throws {+ let candidate = GroundedCandidate(name: "Nova", nameKey: "nova", kind: .character, proposedAliases: [], source: .genericNotes, facts: [])+ let context = CharacterExtractionContext(records: [:], acceptedFacts: [:], suppressedNameKeys: [:], suppressedFacts: [:])+ let proposal = try #require(CharacterExtractionAssembler.assemble([candidate], revisions: [.genericNotes: "note"], context: context, pass: .automatic).first)+ #expect(proposal.mentions.isEmpty)+ }+}++extension AssociationProposalTests {+ @Test func lateRejectionDropsOnlyAutomaticMentionAndKeepsUnrelatedOtherKind() {+ let work = UUID(), entry = UUID(), character = UUID(), place = UUID(), rejection = UUID()+ let source = SourceRef.entry(entry)+ let characterPair = AssociationPair(workID: work, entryID: entry, kind: .character, recordID: character)+ let a = ExtractionProposal(name: "Nova", nameKey: "nova", kind: .character, proposedAliases: [],+ target: .existing(character), facts: [], citedRevisions: [source: "note"],+ mentions: [.init(entryID: entry, noteFingerprint: "note", spellingKeys: ["nova"], sourceGuard: "guard")],+ citedMentionEligibility: [source: "old-coverage"])+ let b = ExtractionProposal(name: "Harbor", nameKey: "harbor", kind: .place, proposedAliases: [],+ target: .existing(place), facts: [], citedRevisions: [source: "note"],+ mentions: [.init(entryID: entry, noteFingerprint: "note", spellingKeys: ["harbor"], sourceGuard: "guard")],+ citedMentionEligibility: [source: "old-coverage"])+ let key = ExtractionSourceKey(work: work, source: source)+ var ledger = CharacterExtractionLedger()+ ledger.beginSweep()+ let started = ledger.start(key, fingerprint: "old-coverage", pass: .automatic, environment: .init())+ #expect(started == .start)+ ledger.settle(key, .proposals([a, b]), modelPhase: .zero)+ let invalidated = ledger.reconcile(against: [work: .init(revisions: [source: "note"],+ recordIDs: [.character: [character], .place: [place]], eligibility: [source: "new-coverage"], sourceGuards: [entry: "guard"])])+ #expect(invalidated.isEmpty)+ #expect(ledger.held(for: work).count == 2)+ #expect(!ledger.isAttempted(key))+ ledger.refreshMentionDecisions(for: work, index: .init(workID: work, eligibleEntries: [entry],+ eligibilityByEntry: [entry: "new-coverage"], activePairs: [],+ decisions: [characterPair: ["nova": .init(rejectionIDs: [rejection], suppressed: true)]], sourceGuards: [entry: "guard"]))+ #expect(ledger.held(for: work) == [b])+ }++ @Test func manualRerouteRefreshesOnlyNewlyDisplayedTargetsRejectionBasis() throws {+ let work = UUID(), entry = UUID(), oldTarget = UUID(), newTarget = UUID(), oldRejection = UUID(), newRejection = UUID()+ let source = SourceRef.entry(entry)+ let proposal = ExtractionProposal(name: "Nova", nameKey: "nova", kind: .character, proposedAliases: [],+ target: .existing(oldTarget), facts: [], citedRevisions: [source: "note"], pass: .manual,+ mentions: [.init(entryID: entry, noteFingerprint: "note", spellingKeys: ["nova"], observedRejectionIDs: [oldRejection])])+ let key = ExtractionSourceKey(work: work, source: source)+ var ledger = CharacterExtractionLedger()+ let started = ledger.start(key, fingerprint: "note", pass: .manual, environment: .init())+ #expect(started == .start)+ ledger.settle(key, .proposals([proposal]), modelPhase: .zero)+ let retargeted = ledger.retarget(proposal.key, for: work, to: newTarget)+ #expect(retargeted)+ let newPair = AssociationPair(workID: work, entryID: entry, kind: .character, recordID: newTarget)+ ledger.refreshMentionDecisions(for: work, index: .init(workID: work, eligibleEntries: [entry],+ eligibilityByEntry: [:], activePairs: [], decisions: [newPair: ["nova": .init(rejectionIDs: [newRejection], suppressed: true)]]))+ let request = try #require(ledger.held(for: work).first).decisionRequest(workID: work, action: .accept)+ #expect(request.displayedTargetID == newTarget)+ #expect(request.mentions.first?.observedRejectionIDs == [newRejection])+ #expect(request.mentions.first?.observedRejectionIDs.contains(oldRejection) == false)+ }++ @Test func sourceBarrierChangeInvalidatesHeldEvenWhenRawTextReturned() {+ let work = UUID(), entry = UUID(), record = UUID(), source = SourceRef.entry(entry)+ let proposal = ExtractionProposal(name: "Nova", nameKey: "nova", kind: .character, proposedAliases: [],+ target: .existing(record), facts: [], citedRevisions: [source: "note"],+ mentions: [.init(entryID: entry, noteFingerprint: "note", spellingKeys: ["nova"], sourceGuard: "old-guard")])+ var ledger = CharacterExtractionLedger()+ let key = ExtractionSourceKey(work: work, source: source)+ let started = ledger.start(key, fingerprint: "old-composite", pass: .manual, environment: .init())+ #expect(started == .start)+ ledger.settle(key, .proposals([proposal]), modelPhase: .zero)+ let invalidated = ledger.reconcile(against: [work: .init(revisions: [source: "note"],+ recordIDs: [.character: [record]], eligibility: [source: "new-composite"], sourceGuards: [entry: "new-guard"])])+ #expect(invalidated == [work])+ #expect(ledger.held(for: work).isEmpty)+ #expect(!ledger.isAttempted(key))+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swiftindex 323f2333..2be04d43 100644--- a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swift+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/FoundationCharacterExtractionModelClientTests.swift@@ -52,14 +52,14 @@ struct FoundationCharacterExtractionModelClientTests { #expect(instructions.contains("reported with no facts")) } - @Test("The instructions fold pronouns into the named character and exclude places and activities")+ @Test("The names-only instructions forbid pronoun inference and exclude places and activities") func instructionsNamePronounsPlacesAndActivities() { let instructions = FoundationCharacterExtractionModelClient.instructions - // Q113: the model does the folding; grounding only drops what slips- // through, so the attribution rule has to be stated here.+ // The approved names-only request must not infer a name or fact from pronouns. #expect(instructions.contains("A pronoun is never a character"))- #expect(instructions.contains("report the fact under that character's name"))+ #expect(instructions.contains("Do not infer a name from a pronoun"))+ #expect(!instructions.contains("report the fact under")) // Q114: the shapes the first real runs produced are named as examples. #expect(instructions.contains("the hotel")) #expect(instructions.contains("activities and events"))@@ -93,8 +93,8 @@ struct FoundationCharacterExtractionModelClientTests { "A title or epithet the note uses as a name, written with a capital letter")) #expect(instructions.contains("The Crowned One")) // The closing rule covers both kinds now.- #expect(instructions.contains(- "A character or place the note only mentions by name is reported with no facts"))+ #expect(instructions.contains("Return names only"))+ #expect(instructions.contains("reported with no facts")) } @Test("The prompt closes by asking for both kinds")
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/NoteFirstExtractionTests.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/NoteFirstExtractionTests.swiftnew file mode 100644index 00000000..e8491b70--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/NoteFirstExtractionTests.swift@@ -0,0 +1,115 @@+import AsterismCore+import Foundation+import FoundationModels+import Testing+@testable import AsterismIntelligence++@Suite("NoteFirstExtraction")+struct NoteFirstExtractionTests {+ let work = UUID(), entry = UUID(), record = UUID()+ func context(_ characters: [ExistingCharacter] = [], places: [ExistingCharacter] = [],+ suppressed: Bool = false, active: Bool = false) -> CharacterExtractionContext {+ let pair = AssociationPair(workID: work, entryID: entry, kind: .character, recordID: record)+ return .init(records: [.character: characters, .place: places], acceptedFacts: [:],+ suppressedNameKeys: [:], suppressedFacts: [:],+ mentionIndex: .init(workID: work, eligibleEntries: [entry], eligibilityByEntry: [entry: "digest"],+ activePairs: active ? [pair] : [],+ decisions: suppressed ? [pair: ["ada": .init(rejectionIDs: [UUID()], suppressed: true)]] : [:],+ sourceGuards: [entry: "guard"], coherentRecordIDs: [.character: Set(characters.map(\.id)), .place: Set(places.map(\.id))]))+ }+ func candidates(_ kinds: Set<RecordKind> = [.character], source: SourceRef? = nil) -> [GroundedCandidate] {+ let source = ExtractionSource(workID: work, workTitle: "Story", source: source ?? .entry(entry),+ text: "Ada meets Ada.", fingerprint: "fp", displayTitle: "Chapter 12", isChapter: true)+ let result = ExtractionResult(characters: kinds.contains(.character) ? [.init(name: "Ada", facts: [.init(statement: "obsolete", quote: "Ada")])] : [],+ places: kinds.contains(.place) ? [.init(name: "Ada")] : [])+ return CharacterGrounding.ground(result, from: source).candidates+ }+ @Test("The live generated schema has names and no facts or prose fields")+ func liveSchema() {+ let value = NamedExtractionResult(characters: [.init(name: "Ada")], places: [.init(name: "Harbour")])+ #expect(value.legacyValue.characters.first?.facts.isEmpty == true)+ #expect(value.legacyValue.places.first?.facts.isEmpty == true)+ let schema = String(describing: NamedExtractionResult.generationSchema)+ #expect(!schema.contains("statement")); #expect(!schema.contains("quote"))+ #expect(FoundationCharacterExtractionModelClient.instructions.contains("Return names only"))+ #expect(!FoundationCharacterExtractionModelClient.prompt(for: .init(workID: work, workTitle: "Story", source: .genericNotes, text: "Ada", fingerprint: "f")).contains("with any facts"))+ }+ @Test("All established matching tiers retain the known character without generated facts", arguments: [0, 1, 2])+ func knownTiers(_ tier: Int) throws {+ let known = ExistingCharacter(id: record, name: tier == 0 ? "Ada" : "Renamed", retainedKey: tier == 1 ? "ada" : "original", aliases: tier == 2 ? ["Ada"] : [])+ let rows = CharacterExtractionAssembler.assembleNoteFirst(candidates(), revisions: [.entry(entry): "fp"], context: context([known]), pass: .automatic)+ let row = try #require(rows.first)+ #expect(row.target == .existing(record)); #expect(row.facts.isEmpty)+ #expect(row.mentions.count == 1)+ #expect(row.sourceEvidence.first?.text == "Ada meets Ada.")+ #expect(row.sourceEvidence.first?.displayTitle == "Chapter 12")+ #expect(row.decisionRequest(workID: work, action: .accept).facts.isEmpty)+ #expect(row.decisionRequest(workID: work, action: .accept).requiresCurrentSources)+ }+ @Test("Same-tier ambiguity stays unresolved and cannot fold away a place decision")+ func ambiguity() throws {+ let known = [ExistingCharacter(id: record, name: "Ada", retainedKey: "ada"), .init(id: UUID(), name: "Ada", retainedKey: "other")]+ let rows = CharacterExtractionAssembler.assembleNoteFirst(candidates([.character, .place]), revisions: [.entry(entry): "fp"], context: context(known), pass: .manual)+ #expect(rows.count == 2)+ #expect(rows.first { $0.kind == .character }?.target == .unresolved)+ #expect(rows.first { $0.kind == .character }?.mentions.count == 1)+ #expect(rows.first { $0.kind == .place }?.returnedKinds == [.place])+ }+ @Test("Unique high-tier identity wins over lower-tier matches")+ func precedence() {+ let known = [ExistingCharacter(id: record, name: "Ada", retainedKey: "x"), .init(id: UUID(), name: "Else", retainedKey: "ada")]+ let rows = CharacterExtractionAssembler.assembleNoteFirst(candidates(), revisions: [.entry(entry): "fp"], context: context(known), pass: .automatic)+ #expect(rows.first?.target == .existing(record))+ }+ @Test("Manual known-character processing never reconsiders rejected spellings")+ func manualSuppression() {+ let known = ExistingCharacter(id: record, name: "Ada", retainedKey: "ada")+ let rows = CharacterExtractionAssembler.assembleNoteFirst(candidates(), revisions: [.entry(entry): "fp"], context: context([known], suppressed: true), pass: .manual)+ #expect(rows.first?.mentions.isEmpty == true)+ #expect(rows.first?.sourceEvidence.count == 1)+ }+ @Test("Already active known links still produce a validated no-op outcome")+ func activeKnown() {+ let known = ExistingCharacter(id: record, name: "Ada", retainedKey: "ada")+ let rows = CharacterExtractionAssembler.assembleNoteFirst(candidates(), revisions: [.entry(entry): "fp"], context: context([known], active: true), pass: .automatic)+ #expect(rows.first?.mentions.count == 1)+ }+ @Test("Known characters and places retain independent original keys")+ func knownDualKind() {+ let known = ExistingCharacter(id: record, name: "Ada", retainedKey: "ada")+ let rows = CharacterExtractionAssembler.assembleNoteFirst(candidates([.character, .place]), revisions: [.entry(entry): "fp"], context: context([known]), pass: .automatic)+ #expect(rows.count == 2)+ #expect(Set(rows.map(\.key)) == [.init(kind: .character, nameKey: "ada"), .init(kind: .place, nameKey: "ada")])+ #expect(rows.allSatisfy { $0.returnedKinds.count == 1 })+ }+ @Test("Evidence deduplicates repeated spellings within one revision but not distinct entries")+ func evidenceIdentity() throws {+ var copies = candidates()+ copies += copies+ copies += candidates(source: .entry(UUID()))+ let rows = CharacterExtractionAssembler.assembleNoteFirst(copies, revisions: Dictionary(uniqueKeysWithValues: Set(copies.map(\.source)).map { ($0, "fp") }), context: context(), pass: .automatic)+ let evidence = try #require(rows.first?.sourceEvidence)+ #expect(evidence.count == 2)+ #expect(evidence.allSatisfy { $0.spellings == ["Ada"] && $0.text == "Ada meets Ada." })+ }+ @Test("An obsolete fact-bearing proposal cannot reintroduce generated facts at the note-first bridge")+ func bridgeBoundary() {+ var row = ExtractionProposal(name: "Ada", nameKey: "ada", kind: .character, proposedAliases: [], target: .newRecord,+ facts: [.init(nameKey: "ada", statement: "old", quote: "Ada", source: .entry(entry))], citedRevisions: [.entry(entry): "fp"])+ row.isNoteFirst = true+ let request = row.decisionRequest(workID: work, action: .accept)+ #expect(request.facts.isEmpty); #expect(request.untickedFacts.isEmpty)+ }+ @Test("A uniquely named but physically incoherent target retains an unresolved chapter marker")+ func incoherentTarget() throws {+ let known = ExistingCharacter(id: record, name: "Ada", retainedKey: "ada")+ var input = context([known])+ input.mentionIndex.coherentRecordIDs = [.character: []]+ let rows = CharacterExtractionAssembler.assembleNoteFirst(candidates(), revisions: [.entry(entry): "fp"], context: input, pass: .automatic)+ let row = try #require(rows.first)+ #expect(row.target == .unresolved)+ #expect(row.mentions.count == 1)+ #expect(row.mentions.first?.sourceGuard == "guard")+ }++}
diff --git a/Packages/AsterismCore/Tests/AsterismIntelligenceTests/SaveTimeKnownLinkLedgerTests.swift b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/SaveTimeKnownLinkLedgerTests.swiftnew file mode 100644index 00000000..f0155286--- /dev/null+++ b/Packages/AsterismCore/Tests/AsterismIntelligenceTests/SaveTimeKnownLinkLedgerTests.swift@@ -0,0 +1,40 @@+import Foundation+import Testing+import AsterismCore+@testable import AsterismIntelligence++@Suite("Save-time known link held review reconciliation")+struct SaveTimeKnownLinkLedgerTests {+ @Test(arguments: [RecordKind.character, .place], ["fulfilled", "pendingSpelling", "guardChanged", "manual", "enrichment", "ambiguous"])+ func reconcileOnlyCompletedOriginalObligations(kind: RecordKind, mode: String) {+ let work = UUID(), entry = UUID(), record = UUID(), marker = UUID()+ let knownKey = AssociationReviewKey(kind: kind, nameKey: "harbor")+ let newKey = AssociationReviewKey(kind: kind, nameKey: "newtown")+ let knownRef = AssociationReviewReference(markerID: marker, key: knownKey)+ let newRef = AssociationReviewReference(markerID: marker, key: newKey)+ let mention = AssociationMentionDecision(entryID: entry, noteFingerprint: "fp", spellingKeys: ["harbor"], sourceGuard: "guard")+ var known = ExtractionProposal(name: "Harbor", nameKey: "harbor", kind: kind,+ proposedAliases: [], target: .existing(record), facts: [], citedRevisions: [.entry(entry): "fp"],+ mentions: [mention], reviewAcknowledgements: [.init(workID: work, entryID: entry, references: [knownRef])], isNoteFirst: true)+ if mode == "manual" { known.pass = .manual }+ if mode == "enrichment" { known.facts = [.init(nameKey: "harbor", statement: "Authored proposal", quote: "Harbor", source: .entry(entry))] }+ if mode == "ambiguous" { known.target = .unresolved }+ let fresh = ExtractionProposal(name: "Newtown", nameKey: "newtown", kind: kind,+ proposedAliases: [], target: .newRecord, facts: [], citedRevisions: [.entry(entry): "fp"],+ mentions: [.init(entryID: entry, noteFingerprint: "fp", spellingKeys: ["newtown"], sourceGuard: "guard")],+ reviewAcknowledgements: [.init(workID: work, entryID: entry, references: [newRef])], isNoteFirst: true)+ var ledger = CharacterExtractionLedger()+ ledger.settle(.init(work: work, source: .entry(entry)), .proposals([known, fresh]), modelPhase: .zero)+ let attempted = ledger.attempted+ var pending = [newRef]+ if mode == "pendingSpelling" { pending.append(.init(markerID: UUID(), key: knownKey)) }+ let index = AssociationMentionIndex(workID: work, eligibleEntries: [entry], eligibilityByEntry: [entry: "eligibility"],+ activePairs: [.init(workID: work, entryID: entry, kind: kind, recordID: record)], decisions: [:],+ sourceGuards: [entry: mode == "guardChanged" ? "new guard" : "guard"],+ coherentRecordIDs: [kind: [record]], pendingReviewReferences: [entry: pending])+ ledger.refreshMentionDecisions(for: work, index: index)+ #expect(ledger.held(for: work).map(\.nameKey) == (mode == "fulfilled" ? ["newtown"] : ["harbor", "newtown"]))+ #expect(ledger.held(for: work).last == fresh)+ #expect(ledger.attempted == attempted, "Reconciliation cannot certify source completion")+ }+}
diff --git a/Packages/AsterismCore/Tests/AsterismPresentationTests/WorksListOptionsTests.swift b/Packages/AsterismCore/Tests/AsterismPresentationTests/WorksListOptionsTests.swiftindex 25befefe..1287bf02 100644--- a/Packages/AsterismCore/Tests/AsterismPresentationTests/WorksListOptionsTests.swift+++ b/Packages/AsterismCore/Tests/AsterismPresentationTests/WorksListOptionsTests.swift@@ -873,6 +873,13 @@ struct WorksSeriesFilterTests { func destinationPreferencesReset() { #expect(WorksListStorageKey.seededLaunchResets.contains(WorksListStorageKey.sort)) #expect(WorksListStorageKey.seededLaunchResets.contains(RestoreStorageKey.worksDestination))+ // Fixed fixture UUIDs must not make a previous Mac leaf selection+ // valid in an otherwise fresh synthetic library.+ for key in [RestoreStorageKey.selectedTab, RestoreStorageKey.selectedTodayEntryID,+ RestoreStorageKey.selectedWorkID, RestoreStorageKey.selectedSidebarItem,+ RestoreStorageKey.todayPath, RestoreStorageKey.libraryPath] {+ #expect(WorksListStorageKey.seededLaunchResets.contains(key))+ } for group in WorksGroup.allCases { #expect(WorksListStorageKey.seededLaunchResets.contains("worksGroup.sort." + group.rawValue)) }
diff --git a/specs/retire-migration-chain/library-graph-baseline.txt b/specs/retire-migration-chain/library-graph-baseline.txtindex db55358c..2d600f07 100644--- a/specs/retire-migration-chain/library-graph-baseline.txt+++ b/specs/retire-migration-chain/library-graph-baseline.txt@@ -87,8 +87,9 @@ # catchUpConfirmationData and lastChapterOverrideData after releaseDaysRaw. # Both optional blobs are nil on a converted V16 row; no entity or # relationship changes. Hand-edited into the recorded work line.-format 14-counts entries=4 works=1 sites=2 titlePatterns=1 urlRulePatterns=1 workTypes=2 memberships=1 distinctPairs=0 series=0 links=0 creators=0 creatorRoles=3 credits=0 places=0 placeSuppressions=0+# format 15 adds the two V21 feature tables; existing graph data is unchanged.+format 15+counts entries=4 works=1 sites=2 titlePatterns=1 urlRulePatterns=1 workTypes=2 memberships=1 distinctPairs=0 series=0 links=0 creators=0 creatorRoles=3 credits=0 places=0 placeSuppressions=0 associationEvents=0 pairNoteVersions=0 site hostname="alpha.test" displayName="Alpha Reader" modeRaw="untaught" site hostname="beta.test" displayName="Beta Serials" modeRaw="taught" titlePattern id=A1000000-0000-4000-8000-000000000001 site="beta.test" version=1 isActive=true createdAt=1800000000.000 definitionData="{\"definition\":{\"segment\":{\"ignored\":[{\"offset\":0,\"origin\":\"end\"}],\"work\":{\"length\":1,\"offset\":0,\"origin\":\"start\"}}},\"trimPrefix\":\"The \"}"
diff --git a/AGENTS.md b/AGENTS.mdindex 0c382896..5497508d 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -154,11 +154,11 @@ When adding tests, follow **Writing efficient tests** in `docs/agent-notes/testing.md`: put value rules on the native host, state runtime dependencies explicitly, and review fast-manifest placement with each new suite. -**The live store schema is V20** (`specs/url-optional-chapter-notes/`), the readiness-marker generation is `"20"`, and the retained migration chain is V16 → V17 →-V18 → V19 → V20. V16–V19 are frozen snapshots; app markers 16–20 remain-accepted, while the extension opens only 20. The current archive generation is-**19/20**, with bounded conversion of predecessor 18/19 archives. The archive envelope test pins its+**The live store schema is V21** (`specs/character-chapter-associations/`), the readiness+marker generation is `"21"`, and the retained migration chain is V16 → V17 →+V18 → V19 → V20 → V21. V16–V20 are frozen snapshots; app markers 16–21 remain+accepted, while the extension opens only 21. The current archive generation is+**20/21**, with bounded conversion of predecessor 19/20 and 18/19 archives. The archive envelope test pins its schema version to the live store. `docs/agent-notes/schema-migration.md` is the procedure for moving all four.
diff --git a/Asterism/Asterism/Announcements/Documents/getting-started-mac.md b/Asterism/Asterism/Announcements/Documents/getting-started-mac.mdindex 6cf14123..9e651eb4 100644--- a/Asterism/Asterism/Announcements/Documents/getting-started-mac.md+++ b/Asterism/Asterism/Announcements/Documents/getting-started-mac.md@@ -129,6 +129,22 @@ anything from it. **Unattached Notes** is at the bottom of **All works** and holds captures that belong to no work yet. It is hidden while a query or token is active. +### Characters, places and chapter notes++When you save a chapter note, Asterism can link recognised, unambiguous names+to characters and places already saved for the same work. These links record+what your note mentions, not everyone who appears in the chapter.++Open a work, click a character or place, choose **Show chapters**, then expand+its **Chapters** section. Open a chapter row to read **Saved chapter note**+separately from **Your link note**. Choose **Edit link note** to write your+own text about that character or place in that chapter.++When the final supporting mention is removed, the link disappears. A link+note you wrote remains in **Settings → Detached link notes**. Choose+**Copy text**, or **Recover to this chapter link** when that action is+available. A returning mention does not attach your old link note automatically.+ ## Stats Stats counts notes, not pages: a note is counted on the day it was first
diff --git a/Asterism/Asterism/Announcements/Documents/getting-started.md b/Asterism/Asterism/Announcements/Documents/getting-started.mdindex be627358..7d2e9aec 100644--- a/Asterism/Asterism/Announcements/Documents/getting-started.md+++ b/Asterism/Asterism/Announcements/Documents/getting-started.md@@ -126,6 +126,22 @@ anything from it. **Unattached Notes** is at the bottom of **All works** and holds captures that belong to no work yet. It is hidden while a query or token is active. +### Characters, places and chapter notes++When you save a chapter note, Asterism can link recognised, unambiguous names+to characters and places already saved for the same work. These links record+what your note mentions, not everyone who appears in the chapter.++Open a work, tap a character or place, choose **Show chapters**, then expand+its **Chapters** section. Open a chapter row to read **Saved chapter note**+separately from **Your link note**. Choose **Edit link note** to write your+own text about that character or place in that chapter.++When the final supporting mention is removed, the link disappears. A link+note you wrote remains in **Settings → Detached link notes**. Choose+**Copy text**, or **Recover to this chapter link** when that action is+available. A returning mention does not attach your old link note automatically.+ ## Stats Stats counts notes, not pages: a note is counted on the day it was first
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e009c194..368d5ed4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,8 +6,41 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Fixed++- **UI acceptance discovery (T-2468):** reveal lazy Work, recovery and saved-source review rows before verifying note counts, exact annotation text and control sizes. Keep review controls fully below their own sheet toolbar before native activation and wait for the decision before closing. Open Capture details with its native action and require the expanded content as the witness.++- **Chapter-history navigation (T-2468):** keep the Mac Today inspector on its dashboard stack, guard retired dismissals, and preserve a scrolled wide Today across inspector and Work returns. Expose real chapter headings beside native Mac previews and reset seeded navigation preferences consistently.+ ### Changed +- **Selected library history (T-2468):** scope creator-detail history reads to the selected works and avoid unused singleton capture variants while retaining complete validation for writes. Clarify how saved chapter notes link known characters and places and how authored link notes are recovered.++- **Work-list publication (T-2468):** read the displayed day and calendar from the mounted list and pass them explicitly to shared helpers, keeping chapter release and catch-up labels consistent across time zones.++- **Reconcile reads (T-2468):** reuse one decoder during each history load and one source-presence inventory during each deletion chunk. Refresh the inventory after combining sources and on replay, while validating every physical history payload.++- **Chapter link reads (T-2468):** reuse chapter-scoped pending lookups and avoid character-support history reads for empty casts, preserving conflicting-copy quarantine, rejection and exact pending decisions.++- **Save-time known chapter links (T-2468):** link saved chapter notes immediately to unambiguous known characters and places across app saves, sharing and queued replay. Removing the final supported mention removes its link while preserving detached authored notes, rejection decisions and established uncased-name support.++- **Duplicate resolution association continuity (T-2468):** preserve supported chapter links and exact annotation history when choosing duplicate content, transfer character/place ownership and suppressions with combined works, and prevent stale links returning after record-name choices. Match known names against the final chosen or appended chapter note within the same save.++- **Expanded history and character ranking (T-2468):** share repeated history reads, retain visible chapters across cancellation and refresh, and validate newer changes before editing. Rank characters using active saved chapter links alongside existing historical fact evidence, preserving decay and deterministic ties.++- **Suggestion and history chapter rows (T-2468):** use the actual chapter title without a separate chapter heading or saved-source ordinal, and align the compact date at the right of the same row in both character and place suggestions and history. Preserve exact source notes and the native collapsed Chapters list.++- **Reading presentation (T-2468):** hide legacy facts while preserving their saved data, remove saved-note ordinals, place dates beside chapter titles, and use a native collapsed Chapters disclosure with retained pagination and note editing.++- **Selected chapter history (T-2468):** add a read-only selected character/place snapshot with exact or explicitly incomplete counts, shared chapter ordering, captured source and annotation values, and local 20-row windows. History retains native collapsed disclosure, local pagination and exact link-note editing.++- **Note-first extraction (T-2468):** automatically save supported chapter links for uniquely recognised existing characters, keep new-character and place review, and preserve ambiguous or rejected links. Generate names only; retain existing facts. Final composed qualification remains in progress.++- **Backup fidelity (T-2468):** preserve raw legacy chapter titles with their+ matching provenance while keeping authored chapter and note targets separate.+ Reuse NoEpisode history within existing import save chunks without changing+ validation or persistence boundaries.+ - **Performance instrumentation (T-2115):** rename the presentation and launch signpost category from `M2Performance` to `PresentationPerformance`, and composed teaching from `M3Performance` to `TeachingPerformance`. Update saved@@ -75,6 +108,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). folding and complete typed note values; name historical dates in the result while keeping the invocation's date context fixed across midnight/settings changes. +- **Chapter mention links (T-2468):** save reviewed character and place mentions+ against chapter identity, including URL-free chapters and repeated names or+ aliases without new facts. Preserve current grounded evidence, explicit+ rejection and durable pending review across restart and backup. Add optional+ authored link notes with Save/Cancel, concurrent text preservation and explicit+ detached-note recovery while retaining existing facts.+ - **Copy characters and places (T-2439):** review independent copies into directly related works or series peers, with explicit record selection, optional notes and Skip/Keep separate choices for name clashes. Extracted evidence stays in
diff --git a/specs/OVERVIEW.md b/specs/OVERVIEW.mdindex 299bb8a5..dd54a6f2 100644--- a/specs/OVERVIEW.md+++ b/specs/OVERVIEW.md@@ -2,6 +2,7 @@ | Name | Creation Date | Status | Summary | |------|---------------|--------|---------|+| [Character–Chapter Associations](#characterchapter-associations) | 2026-10-18 | In Progress — removal-policy decision and publication qualifications open | T-2468. Persist grounded chapter-note links and exact pair annotations; shared known-character/place Save matching and duplicate-resolution continuity have focused verification. | | [Performance Signpost Names](#performance-signpost-names) | 2026-10-15 | In Progress — source implemented; acceptance blocked by host memory/scheduler pressure | T-2115. Replace milestone helper/category names with presentation and teaching names, preserve interval behavior, and guard emitter/metric agreement on the host. Physical sample verification remains owner-run. | | [Chosen-Day Notes](#chosen-day-notes) | 2026-10-15 | Complete — owner validated; phone UI gate qualified | T-2428. Optional day in the existing notes Shortcuts action, preserving default-today/latest-share results and typed values. | | [Bootstrap Initialization](#bootstrap-initialization) | 2026-10-14 | Owner accepted — pr-pilot final review; broad UI gates qualified | T-2056. Consolidate five AppLibraryModel constructors through one private Bootstrap initializer while preserving caller APIs and runtime behavior. |@@ -1073,3 +1074,26 @@ Approved internal constructor refactor for T-2056. Preserve declared, explicit, - [Decision log](bootstrap-initialization/decision_log.md) - [Implementation](bootstrap-initialization/implementation.md) - [Verification and remaining acceptance](bootstrap-initialization/verification.md)++## Character–Chapter Associations++**Status: In Progress — T-2468.** The approved V21 ledger saves grounded chapter-note mentions and exact pair annotations, preserving facts and linkless chapter identity. Earlier correctness and owner-tested Development checkpoints remain source-qualified in the linked reports. The current save-time known-character/place addition has a focused scanner/grounding pass (34 declarations / 187 executions); the original duplicate-resolution maintenance repair passed 94 declarations / 102 executions and independent code review. The owner clarified final-mention removal (S4); the reviewed bounded correction passed 27 declarations / 71 executions, preserving established uncased-script AI grounding and unchanged legacy receipt bytes. Original Release N10 observation/settling remain 3.932553s/6.648267s against unchanged 2s limits; full33 and current eight-method Mac UI qualification are incomplete. Current unfiltered Core passed all 4,093 expected declarations (4,038 pass / 55 explicit opt-in performance skips); native publication7 and corrected phone/iPad journeys pass; signed Mac app/extension compile is verified. Broader app/publication gates remain owed. No performance/Mac exception, implementation commit, push, merge or regular Release deployment is claimed.++- [Requirements](character-chapter-associations/requirements.md)+- [Design](character-chapter-associations/design.md)+- [Tasks](character-chapter-associations/tasks.md)+- [Decisions](character-chapter-associations/decision_log.md)+- [Preserved checkpoint](character-chapter-associations/checkpoint.md)+- [Implementation evidence](character-chapter-associations/implementation.md)+- [Approved note-first implementation](character-chapter-associations/note-first-redesign/implementation.md)+- [Owner-tested reading refinements](character-chapter-associations/note-first-redesign/ui-refinements.md)+- [Refinement verification and Development installation](character-chapter-associations/note-first-redesign/ui-refinements-implementation.md)+- [Suggestion-source row correction](character-chapter-associations/note-first-redesign/source-row-refinements.md)+- [Suggestion-source verification and Development deployment](character-chapter-associations/note-first-redesign/source-row-implementation.md)+- [Expanded-history refresh investigation and fix](bugfixes/expanded-history-refresh/report.md)+- [Chapter-based character ranking correction](bugfixes/character-chapter-ranking/report.md)+- [Save-time known character/place links](character-chapter-associations/save-time-known-links/smolspec.md)+- [Save-time known-link tasks](character-chapter-associations/save-time-known-links/tasks.md)+- [Save-time matching and resolver verification](character-chapter-associations/save-time-known-links/implementation.md)+- [Save-time policy decisions](character-chapter-associations/save-time-known-links/decision_log.md)+- [Reading refinement tasks](character-chapter-associations/note-first-redesign/ui-refinements-tasks.md)
diff --git a/specs/bugfixes/character-chapter-ranking/report.md b/specs/bugfixes/character-chapter-ranking/report.mdnew file mode 100644index 00000000..f7c03572--- /dev/null+++ b/specs/bugfixes/character-chapter-ranking/report.md@@ -0,0 +1,41 @@+# Bugfix Report: Chapter-based character ranking++Date: 2026-10-19. Status: Investigating and preparing regression coverage.++## Issue and confirmed source cause++The owner reports that new stories no longer order characters by recency and relevance. Source inspection confirms RecordRanking reads facts only. Names-only extraction now saves chapter associations without facts, so these new characters have zero ranking evidence and fall through to alphabetical ordering. Work detail, sharing and record-copy contexts all use this fact-only ranker.++## Chosen semantics++Preserve the existing chapter-position axis, half-life decay, concave log2(n+1) breadth weighting, firstCapturedAt behavior for unplaced evidence and normalized-name/UUID deterministic ties. Add one support unit per distinct active, validated character-to-chapter Entry association. Multiple spellings or acceptance events do not multiply support. If the same Entry already contributes saved legacy facts, use max(existing fact count, 1), avoiding double counting.++Preserve saved legacy-fact relevance as historical evidence; it is not a claim of current chapter presence. Removed, suppressed, rejected or invalid associations lose their link contribution. Do not reconstruct associations from facts or mine new appearances outside saved notes. No-mention characters retain zero-evidence deterministic fallback. Work scope, linkless/unnumbered chapter handling and reshare invariance remain explicit regression cases. Place ranking remains unchanged.++Use one per-Work batched association inventory and validated endpoints, excluding annotation bodies; never a history read per character. This narrowly supersedes the old ranking specification's no-added-fetch promise because fact-free association evidence now supplies the ranking. No schema or display redesign is required.++## Verification plan++Add focused pure rank-rule and repository regressions for fact-free recency/breadth, latest evidence changes, duplicate support, work isolation, no acceptance, removed/rejected links, unnumbered/linkless chapters, torn/moved endpoints and legacy-fact overlap. Verify the same ordering reaches Work detail, sharing and record copying. Keep the expanded-history fix moving; source mutations and heavy runs are coordinated so every runtime manifest remains truthful. Integrate both fixes before one authorized Development phone update. No merge is requested.++## Red reproduction++The existing fact-only implementation ran the new seven-declaration integration suite, expanding to 13 executions. Six declarations failed with 18 expected assertion issues, one declaration passed, and all four parameterized endpoint-safety arms passed. No test error or skip was reported. The raw log and JUnit are retained under the parent task's `evidence/t2468-character-ranking/red/`. All 960 frozen product inputs matched before and after.++The wrapper hit an exclusive-create filename error during its post-run bookkeeping after the test had finished. Its exact child exit was not persisted before that wrapper error; the raw test failures and fresh matching post-run manifest establish the red result. Do not describe the outer wrapper failure as a new product failure or rerun merely to replace the receipt. A subsequent one-line fixture warning correction preserved the same `#require` assertion using an inferred nonoptional local binding.++Independent draft review found no arithmetic or scope defect and requested the additional event-quarantine control now included in these seven declarations. Contradictory/malformed acceptance copies must remove only affected support, preserving an independent valid character and readable ordering across Work, share and record-copy consumers. The production correction followed the coordinated native red checkpoint.++## Green ranking outcome++The combined implementation passed exactly 95 source declarations in seven suites and 113 expanded executions: 95 declarations minus seven parameterized declarations plus 25 observed argument invocations. There were no failures, errors, skips or unexpected/missing selected tests. Runtime was 3.005 seconds; the full compile-and-test process exited 0 after 166.236 seconds. All 962 inputs matched reviewed source `cc712ab3932abb46d6b8306884b9d18cdc7c7ddb371e13cf83da32127a3b6497` before and after. Raw logs, JUnit, actual child result, source manifests and exact inventory are retained in `evidence/t2468-character-ranking/green/` in the parent task directory.++No new ranking or fixture compiler warnings were found. Inherited warnings in unchanged NoEpisode, FoundationModels and RepositoryReShare files are retained and are not represented as warning-free compilation. A separate prelaunch manifest-argument guard stopped before Make or compiler launch and is preserved; the corrected fresh run used the approved source manifest.++A later 17-line addition changes only the app UI test's post-navigation history assertions; ranking production, tests and dependencies are unchanged. Do not rerun unchanged Core cohorts solely for that driver assertion. Final combined validation passed: 21 native history executions, three phone history UI methods, the sustained both-kind iPad method and the fixed 456-identifier fast gate. Signed Mac and phone app/extension builds passed strict identity checks. The only post-test input delta is Xcode’s refresh accessibility catalog extraction; retained catalog entries are unchanged. The single phone install/launch request timed out after 600 seconds at a passcode-locked phone. Container replacement is observed and the library group/released metadata are unchanged, but normal launch is unconfirmed. No retry occurred; the exact partial receipt is kept in the parent task evidence folder. Unlock and inspect the original action/process before resuming launch.++## Read-only verification after owner unlock++The owner reported unlocking the phone and began verification. A read-only follow-up confirms Devsterism 0.7.0 (1) installed in the same replacement bundle container observed during the original timed-out request, now with its executable running (PID 71113). The original RunProject build log finalized successfully; the lost MCP action response itself was not recovered, and the initiator of the observed launch is not established. No follow-up install, launch, termination, reset or runtime mutation was performed.++All 962 source inputs still match `933fa3196fdf8bd0057f4fd1ae86eb55cf119e0093582f1d6f95514c9cc29cff`, and signed host app/extension binary hashes and entitlements match the pre-install package. Device metadata confirms its Development identity and replacement path; device binary bytes were not read. Development library group and released Asterism metadata remain unchanged. The receipt now records installation completed and running observed, preserving the prior timeout receipt separately. Feature acceptance remains pending the owner's testing report.
diff --git a/specs/bugfixes/expanded-history-refresh/report.md b/specs/bugfixes/expanded-history-refresh/report.mdnew file mode 100644index 00000000..bba9fae2--- /dev/null+++ b/specs/bugfixes/expanded-history-refresh/report.md@@ -0,0 +1,108 @@+# Bugfix Report: Expanded history refresh instability++Date: 2026-10-19. Status: Investigating.++## Description of the issue++On installed Devsterism source d3972564, the owner reports frequent glitching while a character is expanded: a spinner appears and disappears roughly every one or two seconds. The suspected periodic refresh is an observation, not an established cause. Expected behavior is a stable expanded history that still adopts real library updates and handles cancellation and navigation correctly.++Reproduction: open a work, expand a character and its chapter history, leave the history open for a sustained interval, and observe loading state and row stability. Repeat the equivalent place surface if the shared path is implicated. Use isolated fixtures; do not inspect or mutate physical library contents.++## Investigation summary++The investigation covered selected-history invalidation, view/task identity, Work reloads, publication generations and cancellation/deduplication. WorkDetailView’s generation task and WorkDetailModel’s completed load both reach the shared read. The confirmed defects and correction below preserve real updates while bounding duplicate work.++## Discovered root cause++Source inspection and the retained native/rendered regressions identify three related defects:++1. `WorkDetailModel.refreshRecordHistory` deduplicates only a completed ready generation. The same generation while a read is suspended starts another repository read. Unversioned load/selection refreshes also reset the publication stamp, so the next same-generation call cannot deduplicate.+2. Current-owner cancellation clears a previously ready immutable capture; a returned result changes it to idle and a thrown CancellationError changes it to error. The previous cancellation test covers only an old cancelled response released after its replacement completed, leaving cancellation-before-replacement uncovered.+3. `RecordHistoryView` inserts and removes a ProgressView child on every refresh, altering the expanded list layout even while the captured rows are retained.++The read itself uses a shared locked context and performs no save, refreshAll or publication callback. No timer or source-level self-publication loop was found in the history path. The global generation task and completed Work reload are the actual refresh entry points. Sync arrivals use a documented two-second quiet period, which is a possible cadence source, but there is no device trace proving that it caused the owner's timing. Treat that cadence as unconfirmed.++The causal chain is refresh entry → missing in-flight ownership/dedup → repeated loading transitions → conditional layout child; cancellation additionally discards still-valid displayed data. The previous test validated stale completion ordering but not current cancellation before a successor. A real new global generation remains a legitimate invalidation: ledger and annotation changes may be invisible to a Work display fingerprint, so skipping by Work equality would lose updates.++## Resolution++The reviewed implementation gives each physical read an immutable operation containing its worker handle, typed selection, request token and composite publication/force target. Same-generation waiters join active work. Newer publications stay owed, and explicit Save/load requests add a force revision without erasing publication authority. Model-owned completion drains advanced targets even if the original view waiter leaves. Creator cancellation affects its captured worker only; joined waiter cancellation does not cancel shared work. Exact token/selection guards make late old completions inert.++A cancelled ready capture retains its rows, local window and expansion. A separate needs-validation state blocks editor authority until a successful fresh read. Completed authority advances only on a successful snapshot matching the latest desired target. Same-target selection reuses validated state; real errors remain retryable, and cancellation alone creates no autonomous retry loop.++After that ownership correction, the dynamic updating-spinner List child is removed. Updating/interrupted status is exposed on the existing Chapters header's accessibility value, preserving layout and source readability. This is not a spinner-only change: the native regressions and read-count checks enforce bounded physical work and real updates.++The explicit DEBUG fixture seam requires a validated isolated record-history root and launch flag. It exercises real owner refreshAll publications, duplicates same-generation requests and labels a 250 ms post-read capture hold; ordinary Development launches have none of those controls or delays.++## Verification plan++- Deterministic native regression for repeated invalidation/cancellation, stable expanded state, real updates and away/back behavior.+- Sustained rendered character and equivalent place history observation, with temporal evidence beyond a single screenshot.+- Focused Makefile targets, exact expected identifiers, private caches and serial owned simulator runtime with bounded deadlines.+- Fixed fast gate and signed Mac app/extension compile for final source, then authorized Development phone install and launch through Xcode MCP with identity/source/metadata receipt.++Keep broad publication and performance gates separate; no merge is requested. Preserve the prior installed snapshot and all failed evidence. No staging, commits, external ticket disclosure or destructive data changes are part of this investigation checkpoint.++## Red selection qualification++The first two-method native command exited 0 after 63.782 seconds but executed zero tests. It is neither a red reproduction nor a passing gate. Swift Testing's parameterized signature did not match the abbreviated selector. The actual zero-test receipt and unchanged test-only source manifest are retained. A corrected run of the small complete history-model suite is authorized, with nine declarations and 13 parameter-expanded executions expected. No production fix preceded the red regression.++## Confirmed native red reproduction++The corrected complete history-model selection exited 2 after 38.512 seconds. Exactly nine declarations and 13 parameter-expanded executions ran, with no missing, unexpected or skipped cases. The seven existing declarations passed; both new declarations failed across all six character/place arguments, recording 18 issues. The defects reproduce for returned and thrown cancellation: ready capture/window are discarded. Overlapping same-generation refreshes also issue duplicate reads, and selecting the same record loses the completed generation stamp. Real next-generation snapshots still arrive, which is behavior the fix must preserve.++Only WorkDetailModelTests.swift changed for this red checkpoint; all production inputs remained installed source d3972564. The source manifest and raw failing receipts are retained. A separate rejected zero-test selection is retained as well. This red checkpoint preceded the sustained rendered reproduction and the ownership/presentation correction.++## Rendered reproduction qualifications++The first UI attempt exited 2 after 129.343 seconds before observations: its DEBUG fixture guard consulted a one-shot seed field that had already been consumed. The guard was corrected to require the validated record-history test request, its exact isolated root directory and the explicit fixture flag. Ordinary Development paths remain excluded.++The corrected UI attempt exited 2 after 156.911 seconds. It reached three actual character publications. Retained accessibility metrics show initial read 1 followed by starts/completions 5, 9 and 13: four reads per real publication, proving redundant in-flight work through the actual view/owner/repository path. The capture identity stayed unchanged. The attempt then failed a driver control lookup when the place disclosure was behind the fixed fixture footer. The main agent inspected the failure and character publication screenshots and confirmed that the relevant body/disclosure was occluded; these are not accepted full visual stability proofs. The full trace was attached too late and was not retained after the driver failure; the per-pulse screenshots and accessibility trees are retained.++Do not repeat another pre-fix UI run solely to repair harness evidence. Native red already proves the defects and the partial runtime metrics confirm redundant reads. Correct the driver to position controls and expanded source in the navigation/footer-excluded viewport and retain incremental/deferred temporal attachments. Use that corrected driver for final sustained verification, including both kinds, real updates and away/back behavior.++The owner also requested chapter-based character ranking. That independent change uses separate package files; mutations and runs are coordinated so runtime source manifests are never rewritten or retroactively attributed to later edits.++## Expanded ownership regression checkpoint++The final pre-fix native selection exited 2 after 53.540 seconds. Exactly 12 declarations and 21 parameter-expanded executions ran, with no missing, unexpected or skipped cases. The seven old declarations passed; all five new declarations, expanding to 14 character/place cases, failed with 40 expected issues. The unchanged 960-input source hash is `311f8ef56731ea31e53bd041e6d5781bfb3e02ef3f6aee13b9db896ee508e2e4`.++The expanded controls cover retained display after returned/thrown cancellation, same-generation read sharing, a newer owed publication surviving creator cancellation and older re-entry, cancellation of a joined waiter, and a forced post-mutation read while an older publication read is active. A gate verifies that the next physical read starts before the old held read is released or re-entry triggers it; capture adoption assertions wait for valid completion rather than depending on scheduler order.++Independent design review cleared a per-read immutable operation with a composite publication/force target and exact-token completion. Cancellation must target the creator invocation's captured handle; a later target must drain independently of that creator's continued execution. Completed authority advances only on successful publication matching the latest target and typed selection. A cancelled capture stays visible but cannot authorize editing until fresh validation. This is a narrow ownership correction, not a new persistence authority or display fingerprint cache. Real new publications and post-save forced reads remain required.++## Combined source review and runtime selection++Independent frozen-code review cleared all 962 inputs at `cc712ab3932abb46d6b8306884b9d18cdc7c7ddb371e13cf83da32127a3b6497` before green testing. The main agent also inspected the actual ownership code, header accessibility status, batched ranking helper, per-Entry floor and live-evidence sort partition. A 17-line UI-only follow-up then strengthened re-entry verification; the other 961 inputs, including all production and package tests, stayed identical. The resulting phone source is `6da1c53bab9a590f101da19c2feada061e256e70f53849d94ca5c0e5b861a405`.++Phone selection: the complete 12-declaration history-model suite (21 expanded cases) plus the three affected history UI methods, totaling 15 declarations and 24 executions. iPad selection: the one new sustained both-kind publication/save/re-entry journey. Each runtime has a 600-second bound, private cache, two compiler jobs and its dedicated task-owned simulator, with actual pressure checked at admission. No unchanged broad publication or performance gate is repeated for this testing deployment.++## Phone green checkpoint++The actual phone process exited 0 after 484.015 seconds: exactly 15 declarations / 24 executions (12 native declarations / 21 parameter-expanded cases and three affected UI journeys), with no failures, errors, skips, missing or unexpected cases. All 962 inputs remained at `6da1c53bab9a590f101da19c2feada061e256e70f53849d94ca5c0e5b861a405`. The new sustained journey passed in 187.734 seconds; existing place and character history journeys also passed.++The main agent independently inspected all three publication frames per kind and the Save/re-entry frame. Across nine timestamped publication samples, character source Y stayed 579 over 21.505 seconds and place source Y stayed 521.333 over 18.346 seconds, with one capture per kind, exact source/count retained and one physical read per real publication. Separate idle loops configured for at least five seconds produced 26/27 samples spanning 4.902/4.914 seconds between first and last observations; read counts remained constant. These sampled spans are reported directly rather than inflated to the configured loop duration. Actual note Save and chapter → Work → reopened-history verification retained the saved annotation and freshly enabled Edit action.++Raw receipts, traces, rendered frames and source manifests are retained under `../evidence/t2468-history-refresh-flicker/green-phone/` outside the repository; root reconciliation is `../evidence/t2468-expanded-history-refresh/phone-root-verification.json`. The iPad sustained journey is verified below; final build/install checks follow.++## iPad and fixed fast verification++The iPad process exited 0 after 201.806 seconds with the single expected sustained both-kind journey passing, no failures or skips and unchanged 962-input source. Root inspected all six pulse screenshots and Save/re-entry. Ten character samples span 20.791 seconds at source Y 723.5; twelve place samples span 20.599 seconds at Y 874.5. Captures and source/count/layout remain stable, with one read per real publication. The 41/42 idle samples span 4.872/4.911 seconds between first and last samples with no new reads, within the separately configured five-second loops. Both owned simulators were shut down after actual test exit.++The fixed Makefile fast gate exited 0 in 8.575 seconds: exactly the 456 identifiers in `scripts/test-fast-identifiers.txt`, no failures, errors, skips, missing or unexpected identifiers. Product inputs remained unchanged. Root reconciliations and raw receipts are retained in the local evidence folders.++The signed Development Mac app and embedded extension compiled successfully in 37.242 seconds and passed strict signature checks with the expected Development bundle IDs and original team. No Mac app launch or UI test was performed. Xcode extraction changed only `Localizable.xcstrings`: added the two current accessibility labels and removed the old updating-spinner label; all retained entries are byte-equivalent JSON values. The final source fingerprint is `933fa3196fdf8bd0057f4fd1ae86eb55cf119e0093582f1d6f95514c9cc29cff`. This catalog-only delta qualifies the tested source rather than retroactively changing test manifests.++## Development deployment outcome — partial, launch blocked++The signed phone preflight succeeded in 36.976 seconds. App and embedded extension strict signatures, original team, Development bundle IDs, App Group and CloudKit entitlements were verified before the single authorized RunProject request. All 962 product inputs and signed binary hashes stayed unchanged across the request at source `933fa3196fdf8bd0057f4fd1ae86eb55cf119e0093582f1d6f95514c9cc29cff`; a verified source ZIP is preserved locally.++The request returned no action response within its 600-second deadline. This is an uncertain overall outcome, not a denial or successful launch. Read-only metadata shows changed Development bundle/private-container paths, consistent with an in-place replacement. The Development library App Group path and all released Asterism app metadata remain unchanged. No container contents were inspected. A lock-state query reports passcode required; the post-timeout process query found no Development app process. Xcode reports no build running and a successful build. No install or launch retry was attempted.++Next action requires unlocking the paired phone. Inspect the original Xcode action state and Development process first; resume the already-authorized normal launch only after resolving whether the original request remains pending or completed. The local `evidence/t2468-expanded-history-refresh/phone-deployment/installation-receipt.json` records the exact partial outcome. No commit, push, merge, uninstall, reset or migration command occurred. Original Mac UI/performance and future full publication gates remain open.++## Read-only verification after owner unlock++The owner reported unlocking the phone and began verification. A read-only follow-up confirms Devsterism 0.7.0 (1) installed in the same replacement bundle container observed during the original timed-out request, now with its executable running (PID 71113). The original RunProject build log finalized successfully; the lost MCP action response itself was not recovered, and the initiator of the observed launch is not established. No follow-up install, launch, termination, reset or runtime mutation was performed.++All 962 source inputs still match `933fa3196fdf8bd0057f4fd1ae86eb55cf119e0093582f1d6f95514c9cc29cff`, and signed host app/extension binary hashes and entitlements match the pre-install package. Device metadata confirms its Development identity and replacement path; device binary bytes were not read. Development library group and released Asterism metadata remain unchanged. The receipt now records installation completed and running observed, preserving the prior timeout receipt separately. Feature acceptance remains pending the owner's testing report.
diff --git a/specs/bugfixes/mac-chapter-history-qualification/investigation-history.md b/specs/bugfixes/mac-chapter-history-qualification/investigation-history.mdnew file mode 100644index 00000000..3aeefde0--- /dev/null+++ b/specs/bugfixes/mac-chapter-history-qualification/investigation-history.md@@ -0,0 +1,419 @@+> Platform correction (20October2026): the earlier24pt-versus-2pt `WideLayoutUITests` scroll failure was on T2468 iPad E4BAD8EB, notMac. The actual iOS-result device metadata and `test-ui-ipad` plan prove this; the suite is excluded from Mac builds. Original historical wording below is retained as chronology.++# Bugfix Report: Mac chapter-history qualification++**Date:** 2026-10-20+**Status:** Five original journeys verified; Save-time re-entry remains blocked++## Issue and scope++The retained current-source Mac baseline executed eleven association-note methods: five passed and six failed. This repair phase diagnoses those six failures, preserves their semantic assertions and verifies affected behavior through bounded native regressions. The feature branch/worktree and earlier work remain preserved. No storage/reconciliation change, broader NoEpisode redesign, phone reinstall, push or merge is included.++The original red baseline remains immutable at `task-2/evidence/t2468-mac-current-source-qualification-20261019`. Completed repair attempts and native results are retained separately; failed attempts are not waived.++## Findings and repairs++### Actual accessibility exposure defect++Mac history rows were native leaf Buttons exposing only their source previews. The rendered title/date Text identifiers were absent from the native accessibility hierarchy. Containment-only and Button-trait candidates were tested and rejected; their results showed lost Button queries or nested Buttons without title/date children.++`RecordHistoryView` now exposes real title/date Text siblings above one genuine preview Button on Mac. Both the header gesture and Button invoke the same generation-checked expansion action. Visual spacing, pagination, captured text, conflict announcement and existing editor/open-chapter actions remain intact. Phone layout is unchanged. Native title-click fold/reopen, exact strings, trailing-date geometry, 20→24 rows and Cancel/Save behavior passed. Keyboard activation was not separately qualified.++### Native test-driver assumptions++`AssociationNotesUITests` now uses:++- The real main-window/scroll intersection instead of the frameless application root, finite bounded native scrolling, and the screenshot-grounded disclosure chevron with an asserted actual state transition.+- Exact typed record-card ownership on Mac instead of an impossible iOS Form Cell/Button query. `WorkDetailView` supplies a real contained card identified by kind and record UUID.+- Actual native StaticText string values. Source text and fixture metrics exist in AXValue; empty label reads previously made byte comparisons vacuous and the counter parser fail. The Mac reader requires the real text type and non-nil string; exact UTF-8, NFD, whitespace, counter deltas and temporal/layout tolerances are unchanged. iOS retains its original label reads.+- Normal native keyboard input for editable TextViews that report AX disabled, followed by exact draft checks and real Save/Update actions. Annotation and Entry editor controls are distinguished; no accessibility values are forced or unsupported dirty-label contract invented.+- The exact selected Entry pane as the Mac viewport. The old helper selected the note TextView's internal ScrollView; chapter-link buttons are siblings outside and wider than that rectangle. Full-control containment, absence scans, footer visibility and exact draft assertions remain. Phone Form scrolling is unchanged.+- An exact identified detached-text wrapper with an explicit one-match assertion, avoiding its same-text native child.++Native Back returns Work-origin chapter journeys to their retained parent Work. This verifies those journeys without qualifying the separately observed failed Open Work action.++## Native regression results++| Original failing method | Latest relevant outcome | Source manifest |+| --- | --- | --- |+| Expanded history through publications/re-entry | Passed, 214.140 s | `061ebc…` |+| Long saved source and reachable actions | Passed, 201.371 s | `061ebc…` |+| Place title/date/source | Passed, 36.592 s | `061ebc…` |+| Windowed history, title click, Cancel/Save/editor | Passed, 136.996 s | `061ebc…` |+| Explicit Restore vs unsaved parent fields | Passed, 53.973 s | `ccd9a9…` |+| Save-time known character/place links | **Failed**, 111.542 s | `b87ed8…` |++The final Save-time run executed exactly its one requested method; source remained identical across all 971 inputs, with zero skips/structured runtime warnings, natural Make/wrapper exit 2, no timeout or cleanup signals, and certain empty owned-process drain. Total duration was 221.465 seconds.++Its rebuild emitted three warning lines: one primary warning in unchanged `RuleSuggestionCoordinator.swift`, its diagnostic echo, and one AppIntents metadata-tool warning. No edited-file compiler warning was emitted. This is not a warning-free build claim.++Earlier selections also retained exact inventories, source maps and natural drain where reported. Some earlier exploratory single-case wrappers cleaned only their birth-owned idle `ibtoold`; those qualifiers remain in raw receipts and are not relabelled as natural clean exits.++Source-scope proofs bind the four passes to `061ebc…`, Restore to `ccd9a9…`, and final source to `b87ed8…`. The five passing method bodies/shared helpers remain unchanged. The only later production change is a Mac identifier on the already existing focused-row Edit Button; its action/layout is unchanged. The prior `061ebc…` test source was reconstructed and checked against its recorded full-file hash; later comparisons use an actual before-edit source snapshot. These are scoped results, not a fresh all-six/all-eleven green run.++## Remaining blocker and concrete next step++Save-time passes the first actual Save and both typed membership-removal counts. After returning to Work, reopening Return does not display the Entry editor. A centre click, a bounded leading coordinate and the exact focused-row Edit action have each failed in retained native runs. The final test verifies the exact focused entry marker, exposes and activates its real enabled UUID-identified Edit Button, then fails the unchanged 20-second editor-existence assertion. Later `Nobody visits.` readback, draft non-publication, second Save, re-addition and source/reopen oracles remain **unreached and unqualified on Mac**.++The real Edit callback is now verified: it fires, passes the Work-parent guard and appends the same chapter to the Today path. After Back and that append, the Work destination closure runs again with the same library/navigation objects, but the chapter destination closure and Entry route factory are not invoked. Missing input, a refused parent and a missing Entry factory do not explain that retained reproduction. The separate Open Work action remains unqualified.++Current investigation preserves the original navigation binding and all registrations. A three-arm mounted native fixture passed without reproducing the app failure; a manual-property binding and a child stack host each failed in the actual app and were removed. Omitting only the Today path's observed preference assignment also reproduced the later failure and was reverted. A separate actual-app control now tests native Back/reopen without any edit or Save; the original Save-time method remains unchanged. No navigation fix or new commit is qualified.++Broader NoEpisode/performance work remains paused. The prior iPad scroll-position failure, full publication gates and commit prerequisites remain separate outstanding work. No full-feature, publication or merge readiness is claimed.+++## Continued navigation diagnosis (2026-10-20)++A bounded single-journey diagnostic using the original path/item bindings and+synthetic, UUID-only system logging reproduced the remaining failure. It ran+exactly one method (97.765 seconds), Make/wrapper exit 2, total 213.788 seconds,+without timeout, cleanup signals, skips or structured runtime warnings. All+971 source inputs matched before/after (`b617ce26…`). Diagnostic sources and+native attachments are retained separately; instrumentation is removed from+the proposed repair.++The first chapter callback changed `[Work]` to `[Work, Chapter]` and its+rendered destination appeared. Native Back changed the path to `[Work]` and+the chapter disappeared. The later UUID-identified Edit callback fired,+passed the Work-parent guard and changed `[Work]` to `[Work, Chapter]` again.+The chapter destination never appeared. `selectedTodayEntryID` remained nil+during both typed chapter transitions. This establishes a model/render+mismatch; missed input, parent refusal and unchanged-final-path coalescing do+not explain this reproduction. It does not prove an internal SwiftUI cause.++The reviewed corrective candidate presents standalone Today entries and+existing Work routes through one typed wide-layout stack, preserving the+original model state, compact layout and dashboard-only controller reset.+Diagnostics keeps its existing presentation. Callback ownership and original+transactions are preserved; old entry dismissals cannot clear a replacement+entry or a newer Work, and old typed callbacks cannot pop a newer controller+revision. Focused adapter regressions and the unchanged Save-time journey+are the next validation. No passing verdict or commit qualification is+claimed for this candidate yet.+++### Candidate result and fixture-input control++The single typed-presentation candidate passed all fifteen selected native+regressions, but its unchanged Save-time UI method failed at the earlier+first Open chapter assertion (50.078 seconds). A separate observer-only+lifecycle diagnostic also failed there (50.335 seconds). Both results were+source-exact, without timeout, skips or structured runtime warnings; the+candidate is set aside and preserved. Its later re-entry effect remains+unqualified.++Source inspection found a separate controlled-input defect: seeded launches+reset the newer sidebar/path preferences but leave the three legacy Mac+restore keys (`selectedTab`, `selectedTodayEntryID`, `selectedWorkID`). Those+keys are still read intentionally by normal restoration. The original trace+shows entry `…0002` restored before this journey's inspector→Work actions;+fixed fixture UUIDs make such prior navigation remain valid in a fresh UUID+library. Data-store isolation alone did not isolate navigation defaults.++The next counterfactual restores the original navigation bindings and changes+only the seeded reset policy for those three keys. Explicit+`ASTERISM_UI_TEST_RESTORE_NAVIGATION=1` launches preserve them, retaining the+intentional restore-test path. The existing reset-contract test now pins the+legacy keys too. Normal reader restoration is unchanged. The same original+Save-time assertions and UUID-only trace will determine whether clean initial+navigation removes this reproduction; no success is claimed in advance.+++### Clean-start result and narrower presentation candidate++The original-binding control confirmed initial `item=nil`, `path=[]`, then+reproduced the later failure (98.279 seconds, total 214.841 seconds,+source `53442e45…`, natural Make/wrapper exit 2, no timeout/cleanup,+source-exact and no skips/structured runtime warnings). The first chapter+appeared, Back removed it, and the second Edit appended the same chapter+without a rendered destination. Clearing the legacy inputs is therefore+necessary fixture hygiene but is not sufficient to explain or fix re-entry.++The next corrective candidate keeps the existing standalone-entry destination+and retained Work controller. Only a chapter that has been popped receives+a fresh native presentation identity on its next visit. The app's stored+`WorksRoute` values, Work identity, active chapter edits and Save behavior+remain unchanged. Stale visit/controller callbacks and retired incoming tokens+are refused; valid Back writes preserve their original transactions. This is+a targeted hypothesis about destination reuse, not a claim about an internal+SwiftUI defect. Native ownership checks and the same full Save-time journey+must qualify it before instrumentation is removed or a code commit is made.+++### Presentation counterfactuals retained++The chapter-visit identity candidate passed eleven native tests but failed+at the earlier first Open chapter assertion (50.124 seconds, total 169.356,+source `3e4f3799…`). Its later visit identity effect was not reached. The+candidate and five added tests were preserved and removed, returning to the+original direct model binding.++A one-variable control then temporarily removed only the dormant diagnostics+Boolean destination registration. Diagnostics remained false in every event.+The first chapter appeared, Back popped it, and Edit appended the same valid+chapter path without appearance. The unchanged later editor assertion failed+(105.399 seconds, total 257.786, source `1d889835…`), with natural Make/wrapper+exit 2, exact source, no timeout/cleanup, skips or structured runtime warnings.+Removing that registration is insufficient. It has been restored.++The remaining distinction is destination construction versus appearance.+`EntryDetailRoute` can return empty when the app cannot supply an Entry model;+a retained Work holds its earlier model and does not establish current+repository availability. Diagnostic-only logging now distinguishes the+existing destination closure, route body, single existing factory outcome,+Entry loading/content/unavailable branch and appearance. It logs supplied+synthetic identities/outcomes without new model state, factory calls or+observable writes. No shipping navigation repair is qualified yet.+++### Mounted binding and actual-host comparisons++All results below retain the original Save-time assertions and their downstream persistence oracles. A failed earlier boundary does not qualify any later step.++| Comparison | Actual outcome | Source |+| --- | --- | --- |+| Original direct binding, destination/factory construction logging | Later re-entry failed; second append never invokes chapter destination closure | `c7da6c19…` |+| Both dormant nil-item and false diagnostics registrations removed | Same later failure, 102.906 s; registration family set aside | `b091bd83…` |+| Three mounted native arms: direct observable binding, identity wrapper, direct State | Exact 3/3 passed; real destination dismiss then same chapter reappeared; retained Work state token. App failure not reproduced, therefore inconclusive for its cause | `0f49bbb5…` |+| Actual app manual-property getter/setter with original transaction | Earlier first chapter opening failed, 50.868 s; callback/path append verified but no chapter constructor. Removed | `03b2b927…` |+| Child stack View, original projected binding and same navigation object | Later re-entry failed, 126.218 s; first Save/removal/Back passed, later valid append again invoked only the Work constructor. Removed | `71c69dc6…` |++The manual and child comparisons had natural Make/wrapper exit 2, exact 971-input before/after source maps, no skips or structured runtime warnings, no timeout and certain empty owned-process drain. The mounted 3/3 run had Make exit 0; its wrapper returned 124 solely after interrupting its birth-owned idle `ibtoold` 46398 after the principal exited. It was not a hard timeout or a natural wrapper exit. Existing warning diagnostics remain retained; no warning-free build is claimed.++All rejected sources, raw results, source maps and synthetic UUID-only event captures remain under `/tmp/t2468-ledger-build`. The immutable earlier archive is unchanged. The child candidate was restored to the exact `c7da6c19…` 971-input baseline before preparing the next isolated intervention.+++### Preference assignment result and no-Save control++The assignment-only counter (`f7867fd9…`) reproduced the later re-entry failure at the original field assertion (170.207 s, total 322.525 s). It executed exactly one original method, source-exact across 971 inputs, natural Make/wrapper exit 2, no timeout, skips or structured runtime warnings, and certain empty owned-process drain. Its 53 actual-SUT events again show first construction/Save/Back/disappearance, followed by a valid second append with only the Work constructor invoked. The preference assignment was restored and the full `c7da6c19…` baseline verified before further edits. No persistence repair is justified by this negative result.++The next separate Mac diagnostic retains the entire actual app, inspector, Work/history buttons, native Back and same focused UUID Edit action but performs no draft edit or Save. It captures initial/reopened exact UTF-8 and unchanged character/place history counts. Adding this temporary method leaves all eleven original methods and shared helpers byte-for-byte intact. Its pass would not qualify Save-time correctness; it tests whether the failure occurs without any edit or Save. A pass would implicate the omitted input/focus/Save/event sequence collectively, rather than establish Save alone as necessary.+++### Actual app re-entry fails without editing or Save++The separate no-edit/no-Save control (`186424a7…`) failed on its second real target pane/editor assertion after 72.179 seconds (total 151.113 s). The first chapter rendered, native Back removed it and the editor disappeared. The same UUID focused Edit action then fired and appended `[Work, Chapter]`, without invoking the chapter constructor. Its 28 actual-SUT events are retained. Exactly one new method ran; all eleven original methods/helpers and all production inputs remained baseline-exact. Make/wrapper exited 2 naturally, with no timeout, skips or structured runtime warnings and certain empty owned-process drain.++This establishes that draft editing, Save and its saved-data publication are unnecessary for the actual-app reproduction. A static mounted stack still passes. The next diagnostic compares the original inspector→Work trajectory with the genuine Today release-row→Work trajectory on identical disposable fixture data. Both use the same history Open-chapter controls for first opening and re-entry; release navigation intentionally has no focused Edit action, so no focus state is manufactured. Enabling all seven release weekdays on the fresh synthetic Work is test setup only; all chapter data, UUIDs, notes and associations remain unchanged. No NoEpisode action or implementation is included.+++### Focus-scroll effect discriminator before changing fixture setup++The scheduled inspector/release pair remains drafted but unrun and unapplied. Source review found a smaller omitted behavior: `WorkDetailView`'s `task(id: focusedEntryID)` requests an imperative scroll whenever it starts with a nonnil focused entry, including return appearances. The inspector supplies that focus; the static mounted fixture has no such task. The original Save-time test is now selected with only that scroll call omitted; the task/guard, inspector trajectory, focus styling, real Edit callback and every original assertion remain intact. All temporary new UI methods were removed and the complete `c7da6c19…` baseline verified before this one-line intervention.++This is a diagnostic effect suppression, not a shipping removal. Both real chapter callbacks must be delivered to interpret it; an offscreen-control failure would be inconclusive. If positive, the next candidate should restore initial and repeated scrolling using a typed chapter-row anchor while retaining existing route, ForEach and entry identities. Matching UUID values alone do not establish a global identity collision. If negative, the focused-scroll hypothesis is set aside.+++### Focus-scroll negative; outer route-identity fidelity check++Suppressing only the focused scroll reproduced the original later failure (99.622 s, total 172.694 s, `def453c4…`). Both intended chapter callbacks were delivered; the second append again constructed only the Work destination. Exactly one original method ran, source-exact, with natural Make/wrapper exit 2, no timeout, skips or structured runtime warnings and certain empty owned-process drain. The original scroll was restored and the full `c7da6c19…` baseline verified. The focused-scroll family is rejected; no scroll-anchor namespace variant is being tried.++Review identified a separate concrete fidelity gap: the passing mounted fixture applies `.id(route)` to its outer destination, while the app applies Work and Entry identities deeper beneath conditional route bodies. One actual-app counter now adds only that outer identity to Today's typed destination. It retains the original binding, registrations, inner identities, controller reset, fixture and all eleven original UI methods. A positive result still requires complete Save-time semantics and retained Work/history state; a negative result ends this exact hypothesis before the drafted trajectory pair. No framework-internal cause is inferred from matching or differing identity values.+++### Outer identity negative; matched real entry trajectories++Adding only the outer Today route identity also reproduced the original later failure (100.510 s, total 211.432 s, `1aa037f9…`). Exactly one original method ran, source-exact, natural Make/wrapper exit 2, no timeout/skips/structured runtime warnings and certain empty owned-process drain. The exact run-interval export recovered 53 actual-SUT events: both chapter callbacks fired; the second valid append did not construct the chapter destination. The candidate was preserved and removed, then the full baseline verified. This exact identity hypothesis is rejected.++The matched inspector/release pair is now prepared on identical disposable fixture data. Only release weekdays were added to the fresh synthetic Work, and only two separate diagnostic methods were added to the original UI file. Removing their shared fragment reproduces the entire original eleven-method file. Both arms open and reopen through the same character/place history controls, check real pane/field identity, exact unchanged UTF-8 and committed counts, and use native Back. The pair distinguishes entry trajectories (including their legitimate focus difference), rather than establish an inspector-internal cause by itself.+++### Scheduled inspector/release no-Save comparison (2026-10-20)++Both exact diagnostic cases failed at the second history reopen (line 1278). Inspector case: 78.834 s; release case: 83.299 s. Entire bounded run: 235.258 s, natural Make exit 2, no timeout, certain empty drain. Source 971 unchanged, SHA256 `5dce83d3b7e63022392235b9550dc28602fa9cebd3500aa70c7206a27b6d352e`; no skips/runtime warnings.++Exact-interval trace contains 56 events across separate actual SUT UUIDs: both first chapters rendered; native Back changed the path to Work-only and removed the editor; both second real history callbacks appended the same chapter to the same navigation instance without invoking a second chapter destination closure. Inspector entry, draft edits and Save are unnecessary for this reproduction. No product fix is qualified. Next control changes only the first Back action to the existing app Back command, keeping all original acceptance tests unchanged.++Evidence: `/tmp/t2468-ledger-build/mac-scheduled-inspector-release-no-save-pair-proposed/`.+++### App Back-command diagnostic build failure++The first command-control attempt failed before test execution: a missing separating newline in the temporary helper insertion joined two conditional directives at UI line 1296. No inference about command Back is possible. The source, native result, raw compiler diagnostic and root review remain in `mac-scheduled-release-app-back-command-control-proposed`. Make exit 2; wrapper 124 after cleaning only a birth-owned post-principal helper; 5.426 s; no timeout; certain empty drain. The separating newline is corrected and a fresh result/source binding is required.+++### Existing app Back command outcome++Corrected source executed exactly one method: failed 48.920 s; total 61.903 s, natural Make/wrapper 2, exact971source, zero skips/runtime warnings, certain empty drain. After the real command key input, the trace records Work+Chapter → Work-only, followed by both Work and chapter destination closures; the chapter screen remained visible and the unchanged 20-second Work-title assertion failed. No second Open occurred. This is a model/render pop mismatch, distinct from the native-Back comparison; it does not qualify any fix or prove native Back is necessary for the overall mismatch. Exact22events/SUT94C0E313… retained in `mac-scheduled-release-app-back-command-control-retry-prepared`. Next actual UI comparator keeps native Back and changes only the second chapter to existing Arrival002.+++### Different existing chapter control++Return003→native Back→Arrival002 also failed at the second editor assertion: 109.243 s; bounded total 139.905 s; natural Make/wrapper2; source971exact; zero skips/runtime warnings; certain empty drain. Exact28events actualSUTF43A1A41… show first003 render and disappearance, then real002callback/pathappend without002destination construction. The reproduction affects a different subsequent chapter, not only same-ID revisits. Measured coexistence with private Meddy simulator work was recorded; this is a functional check, not a performance measurement. Evidence retained in `mac-scheduled-release-different-chapter-control-proposed`.++The next temporary discriminator removes EntryDetailView and its argument evaluation/loading/lifecycle, leaving actual factory/availability/route/identity and real Work controls. A new diagnostic uses a genuine Text marker; all original acceptance tests stay unchanged, and no editor/feature qualification can follow from the marker alone. Critic reviewed this fidelity before application.+++### Minimal chapter content: second-action delivery unestablished++The exact one-case minimal-marker diagnostic failed 76.190 s (total150.400 s), with source971exact, naturalMake/wrapper2, no skips/runtimewarnings and certain empty drain. The first real Text marker and nativeBack disappearance passed. Only17trace events were retained; no second callback/append event is established despite the second ordinary click in the test log. Missing diagnostics alone cannot prove absence, so this is inconclusive for attributing the original rendering failure to a component.++The screenshot shows the actual blue Open chapter control within the viewport. Its83×16 AXframe is634,901. Ancestor Disabled flags also occur in earlier runs with delivered callbacks and are not evidence of an actual disabled control. Critic reviewed a single explicit10%/50% coordinate action on that same second button, requiring exactID/enabled/viewport preconditions and no fallback; original acceptance remains unchanged.+++### Minimal chapter explicit-action result++The single bounded10%/50% second-button coordinate delivered the real callback and chapter append, but no second minimal destination was constructed. Exact21events SUT3887B39E…; failed75.114 s; total101.941 s; source971exact; zero skips/runtimewarnings. Make2/wrapper124 is qualified by one birth-owned post-principal idleibtoold67764 SIGINT, with nohardtimeout and certain empty final drain. This establishes a version of the navigation failure without EntryDetailView and its loading/lifecycle event set. The earlier ordinary-click result remains inconclusive for delivery.++Next restores the full editor and actual paired UI baseline before a ScrollViewReader hosting counter. The release route has no requested focus entry; Work history read/select paths do not author Work refusal/error state or increment refusalScrollRequests. Removing the Reader and its contained task/observers is solely a component diagnostic; focused/refusal scrolling remain product requirements.+++### Reader-host removal: negative++Full-editor matched release case failed76.377 s (total155.214 s); exact971source; naturalMake/wrapper2; zero skips/runtimewarnings; certain empty drain. Exact28events SUT9F631F4E… confirm secondactualhistorycallback andappend withoutsecondchapterdestination. The Reader wrapper is unnecessary for this reproduced failure and is restored. This does not justify any focus/refusal behavior change. Next is a diagnostic forcing the existing List branch while retaining all real sections, Reader and outermodel/lifecycle/modifiers; no shipping forced-layout proposal.+++### Existing List branch: inconclusive control ownership++The artificial List branch failed before the first chapter: unchanged typed-card Chapters disclosure assertion at line1227,34.233 s (total121.520 s). Exact971source; naturalMake/wrapper2; no skips/runtimewarnings; certainemptydrain. No Back/reopen behavior was exercised, so no container attribution is supported. No driver/assertion adaptation was made. Original layout is restored. Next uses observer-only pure incoming-width logging in the existing geometry action with its original assignment intact; no geometry guard or threshold change.+++### Actual Work geometry observation++Observer-only normal-layout run failed76.678 s (total151.895 s), exact971source, naturalMake/wrapper2, no skips/runtimewarnings and certain empty drain. Actual30events SUT6728D818… retain bothcallbacks/appends and nosecondchapterdestination. Workwidthreported58.5(columnsfalse), then1324(columnstrue), bothbeforefirstchapter; noadditionalwidthchange, zero or nonfinite event was recorded around Back/reopen. This does not justify a width guard.++The loading Group has an intrinsic ProgressView while ready workList expands; source and observed58.5→1324 support testing available-width ownership. Critic approved a one-line fillframe before the existing geometry probe, retaining original assignment, policy thresholds, height, Reader and real controls. The initial transition is observed; its relationship to navigation remains unproven until that counter. If positive, real narrow/wide resizing and original editor journeys remain required.+++### Available-width frame: negative navigation result++The frame corrected the first observed width to1324 (columns true), but second reopen still failed75.662s (total154.72743129730225s). Exact971source; naturalMake/wrapper2; no skips/runtimewarnings; certainemptydrain. Actual29events SUT2B9A4D50… confirm both callbacks/secondappend withoutsecondchapterdestination. The initial58.5→1324 transition is unnecessary for this failure. Temporaryframe is reverted; no widthguard/threshold change justified. Next reviewed component counter removes only Today stack explicitid while retaining revisionstate/resetobserver/staleitemguards, adding existinglocalrevision to pure trace. This is not a shipping reset-policy change.+++### Explicit Today stack identity removal: negative++The exact component counter failed second reopen74.112s (total139.9860920906067s). Exact971source, naturalMake/wrapper2, zero skips/runtimewarnings and certainemptydrain. Actual30events SUTCB1A9F83… show ownerRevision0 throughout destination construction; both callbacks/secondappend, then Workdestination reconstruction but nosecondchapterdestination. Stackexplicitidentity is unnecessary for this failure; originalidentity/resetpolicy restored. No identityfix or placementvariant justified. Next investigation observes the actual native controller hierarchy against modelpath at firsteditor/completedBack/failedappend, retaining actual screens and all assertions.+++### Actual native controller ownership observation++Matched release diagnostic reproduced failure75.843s (total188.76501607894897s), exact971source, naturalMake/wrapper2, zero skips/runtimewarnings, certainemptydrain. Actual288events SUT1F0181FF… include all three command-invoked snapshots, each uniquely selecting the same main/key window, complete4controllers and58/81/83views, no truncation. Root/split/sidebar/detail controller identities remain identical. Native TextEditorScrollView/PlatformTextView exist at firsteditor and are absent aftercompletedBack and at failedsecondappend. Bothrealcallbacks/secondappend are confirmed, but nosecondchapterdestination. This establishes model/render disagreement within the same active detail host; no duplicatewindow or separatelyretained/presentededitorcontroller is established. Publicgraphs do not expose internalSwiftUIpathreconciliation; no repair is qualified. TemporaryobserverApp/UI source is preserved then reverted to the exact geometrybaseline.+++### Chapter path explicit copy/append/set: negative++Exact final writeback counter failed74.232s (total191.5639579296112s), exact971source, naturalMake/wrapper2, zero skips/runtimewarnings and certainemptydrain. Actual30events SUT03294696… show secondcallback/validappend and Workdestination reconstruction withoutsecondchapterdestination. Original append is restored; no writer/transaction variants justified. The passing small nativefixture still omits actualContentView/Today/Work lifecycle and uses syntheticText content. Next single full real-model ContentView host must reproduce with actual nativeBack before comparing ancestor boundaries; a passing nonreproducing harness cannot qualify a repair.+++### Full real-model native host: setup failure, no navigation verdict++Compiled the one actualContentView/seededmodel/private-defaults native diagnostic, but it failed21.958s beforefirstchapter on missinggenuine work-detail-character AXButton. Total72.95741176605225s; source971exact, Make2/wrapper124 fromonebirthowned postprincipalidleibtoold78385SIGINT, nohardtimeout/finalemptycertain. Workwidth58.5→62.0 differedfromactualapp1324; two structured toolbar-title width0 constraintwarnings and secondaryunexpected InvalidTransition idle→failed(deinit) are retained, not waived. Rootreviewidentifiedmissingcanonical Appscene minimumframe960×640/nativehost sizing setup; next minimalharness correction must establishmatchinggeometry/nativeAXcontrols before anynavigation inference. No firstchapter/nativeBack/reopen result exists. Exactsynthetic model/rootidentityattachment exported; no broadtmpsearch required.+++### Corrected full-host setup: native accessibility prerequisite still unqualified++The canonical minimumframe/explicitallocation correction removed structuredtoolbarwarnings, but actualWorkwidth settled960 (notactualapp1324). Exactone native test failed22.133s beforefirstchapter on missinggenuine work-detail-character AX identifier; total37.10197997093201s, exact971source, naturalMake/wrapper2, zero skips/runtimewarnings, certainemptydrain. RetainedownedwindowAX hasonly6window/chromenodes/noSwiftUIcontentIDs; this does not establish actualcontrols absent. Secondaryunexpected InvalidTransition idle→failed(deinit) remains unexplained. This harness has not reproduced navigation and cannot support a repair. Nativeharness source is archived and original6native tests restored. No additional host/modifier variants are running. The actual-app evidence still establishes correctsecondcallback/pathappend with absentsecondchapterconstruction/nativeeditor in the same detailhost; no qualifiedfix/commit yet.+++### Actual supplied Binding versus model at callbacks++The original failing release trajectory reproduced in73.263s (total136.63482213020325s), with exact971source, naturalMake/wrapper2, zero skips/runtimewarnings and certainemptydrain. Actual34events SUTEB521181… contain exactly four binding observations: before/after first successful open and before/after failed reopen. The captured projection supplied to NavigationStack equals AppNavigation.todayPath in all four, with one navigationobject: Work before each, Work+chapter after each. The chapter destination remains absent on the second append. Thus a stale captured getter at callback time is not established; internal graph consumption remains unobserved. The next separately reviewed single body-read observation deliberately adds an Observation dependency, and a passing instrumented case cannot qualify a repair.+++### Body-time Binding/model comparison: precise navigation blocker++The exact existing release no-edit/no-save diagnostic failed on second editor reopen in 84.851 seconds (155.848 seconds including build/runner). All 971 source inputs matched before and after. Native results contain exactly one failed method, no skips or runtime warnings; Make and wrapper exited naturally with code 2, with certain empty owned-process drain. Existing compiler warnings remain recorded in the result review.++The 44-event trace belongs to SUT `714344AB-3DC0-4B0F-BE62-26B2388491E6`, PID 80550. Both real callbacks appended the expected chapter. After the second append, a subsequent body evaluation at `15:17:52.283914+1100` explicitly read both the supplied Binding and model as Work→Chapter003. Navigation identity remained `0x000000010149e730`, stack revision remained zero, and the next construction event was Work only. There was no second chapter destination construction or editor appearance. Thus the blocker is **correct observed application inputs with unexplained navigation/render divergence**. These public observations do not prove internal SwiftUI consumption or an SDK defect.++Independent review sets the next justified investigation as a faithful App-scene reproducer retaining the actual hosting, command and environment composition, reduced only after it reproduces. Earlier standalone native hosts failed accessibility prerequisites and cannot substitute for that reproduction. Further binding, identity, modifier or timing variants have no established causal basis. No source repair or commit is qualified by this diagnostic.++The body observer and callback comparison were archived, then their two source files were restored to the exact geometry baseline: all 971 product inputs match `b39b654d…05a`. The five earlier verified journey repairs, original navigation owner, assertions and dashboard protection remain preserved. No phone operation, push, merge or new commit occurred. All Asterism jobs have drained.+++### Actual App-scene shared-action reproduction++Continued under explicit owner instruction to pursue repair. The real AsterismApp Window/commands/Settings, ContentView model/environment/sheets, WideRoot split and Today stack, Work state/model/tasks and full Entry editor were retained. An isolated DEBUG fixture-only top inset provides a genuine Button that looks up chapter003 in the loaded Work and invokes its existing onSelectEntry callback. A separate diagnostic method drives release shelf→shared action→full editor→native Back→same action→full editor, preserving actual saved UTF8 and association assertions. Original UI methods are byte-exact after removing the added method/launch opt-in.++This shorter sequence reproduces the same failure (41.125s method,105.835s total). All971inputs match before/after. Actual31events SUTE2738B77… show both callbacks/expectedappends, first full editor and nativeBack removal, then second Work destination without second chapter/editor. No history-card selection or note editing is required. Exactone failed method/no skips/runtimewarnings. Make2/wrapper124 reflects postprincipal cleanup of only birth-owned idleibtoold81541; final drain certain/empty, nohardtimeout. Naturaldrain criterion remains failed and is not waived. Compiler warnings are retained and peer-reviewed as inherited.++The matched next reduction changes only ready-state Work content to its real title Text. The common inset/button, exact target lookup, all outer Work lifecycle/presenters, real Entry editor, App scene and UI method remain unchanged. This is diagnostic reduction, not a shipping repair.+++### Reduced Work content and root presenters remain red++The matched ready-content-only reduction reproduced the same phenotype in40.520s (94.719s total), source971edaa… exact, naturalMake/wrapper2/certainemptydrain, no skips/runtimewarnings. Actual30events SUT231948CD… establish firstfullEditor/nativeBackremoved and secondcallback/append followed by Workonly. This removes Work's visual/content subtree and its inner presenters from the necessary reproduction set; retained lifecycle hooks remain candidates.++Removing the defined46-line root presenter group also reproduced in39.617s (92.600s total), source9710e735… exact, actual30events SUTF63DE03E… with the same first/pop/second-callback trajectory. No skips/runtimewarnings. Make2/wrapper124 includes only postprincipal birth-owned idleibtool83294SIGINT; certainemptydrain/nohardtimeout, naturaldraincriterionfailed and retained. The removal includes the record-copy sheet's onDismiss callbacks/lifetime, so no registration-only claim follows. Next diagnostic completes Work host reduction by removing its34-line appearance/geometry/edit-session group while keeping the common inset, real model load/refresh and remaining lifecycle hooks.+++### Work-host appearance reduction prepared; launch denied before execution++The next reviewed diagnostic removes exactly34lines of Work navigation title/inline title/back-button/edit-session/geometry/sky and bottom diagnostic inset modifiers. It retains the common top action, actual model load/refresh, subsequent observers and appearance/disappearance lifecycle, minimal title content, full Entry editor and App scene. Other970product inputs, including the entire UI test, match the completed presenter reduction. Parse/diff checks pass; source971bdb22592…7e11 is frozen.++Automatic approval review rejected starting its Mac compile/UI concurrently with the active Meddy iOS UI run: high host load, low unused memory and insufficient healthy-compatible admission guarantees. The action is known not to have executed. No workaround or immediate retry was attempted. A later read still showed high load and the foreign iOS UI job active; the prepared run remains pending materially improved ownership/capacity evidence. No repair/commit is qualified.+++The rejected launch remains unexecuted. Exact candidate Work/UI files and the frozen971manifest are preserved; both temporary files were restored and all971inputs verified against geometryb39. No Asterism job remains. Further execution requires a materially safer resource/authorization boundary; no direct retry occurred.+++### Approved single retry executed after improved resource boundary++The user approved one retry conditional on spare capacity. The execution directory was verified empty. Fresh one-minute load declined from114–149 to11.88, CPU samples59.32/74.42%idle, memory_pressure55%free, kernelpressure1 and zero current swap activity; no compiler/Mac test overlapped the independently isolated iOS UI runner. Exact two candidate files were reapplied and all971frozeninputs verified. The unchanged guarded/capped diagnostic then executed exactlyonce.++Stage4 reproduced the same second-editor failure in40.239s (102.643s total), actual28events SUT495808CB… with firsteditor/nativeBackremoved/secondrealcallback+expectedappend followed by Workonly. Source971bdb… exact, UI1/no skips/runtimewarnings. Make2/wrapper124 includes only birth-owned idleibtool86837SIGINT afterprincipalexit; finalcertainempty/nohardtimeout, naturaldraincriterionfailed and retained. The earlier denial receipt remains historical and has not been erased.++The next distinct targeted comparison removes exactly26remaining Work observer/lifecycle lines while preserving its genuine initial load. Actualscene, realmodel, commonaction, fullEntry and completeUI method remain. A source-only review separately identifies unconditional Work load state transitions as an unproven lifecycle hypothesis; no load/refresh policy change or shippingrepair has been made.+++### Minimal Work lifecycle and load observation remain red++The remaining26-line observer/lifecycle tail was removed while preserving the genuine initial model load. Stage5 reproduced the same second-editor failure in39.446s (96.548s total), with all971inputs exact, natural Make/wrapper2 and certainemptyprocessdrain. Actual28events show the first full editor, nativeBack removal and second callback/expectedappend followed by Workonly. No skips or runtimewarnings.++Stage6 added only gated DEBUG observations around the unchanged WorkDetailModel.load invocation/statewrites. It reproduced in39.312s (96.620s total), all971inputs exact. Its32events show one load reachingready before the first callback; the same retainedmodel had no observed second/overlapping/cancelled load around Back or failed reopen. This provides no positive evidence for a loading-policy repair. Missing logs alone are not absolute absence proof. Make2/wrapper124 reflects postprincipal cleanup of only birth-owned idleibtool88673; finaldraincertainempty/nohardtimeout, naturaldraincriterionfalse retained. The instrumentation was restored byteexact, then the full971Stage5baseline verified.++The next targeted comparison removes only the Today pane's20-line inspector/portrait-inspector/focus/keyboard group. Exact NavigationStack binding, identity, dashboard reset, itemguards and destinations remain. The sameUI1 method/cap/privatecache is retained. Any positive result localizes this group, not a unique inspector cause.+++### Today interaction partition changes the result++Stage7 removed only the20-line Today inspector/portrait/focus/keyboard group; all other970inputs matched Stage5. The identical UI method passed23.610s (72.551s total), with Make/wrapper0, natural certainemptydrain, no skips/runtimewarnings and all971inputs unchanged. Actual34events for SUT7787FF33… include first and second chapter destination construction/appearance, nativeBack disappearance after each, with the same navigation owner. Exact savedUTF8 and character/place association assertions remained. The only compiler warning was the inherited RuleSuggestionCoordinator344 capture warning/echo. This localizes the group under the minimalWork control; it does not establish an inspector-only cause or qualify removing required behavior. Narrower partition and matched restoration remain necessary.+++The exact20-line group re-add control returned all971inputs to the earlier Stage5 source. Stage8 reproduced the same second-editor failure in39.508s (93.470s total), actual28events SUT7A99A6FD… confirming first full editor/Back removal and second callback+expectedappend→Workonly. No skips/runtimewarnings; sourceexact. Make2/wrapper124 includes only postprincipal birth-owned idleibtool90488SIGINT; finalcertainempty/nohardtimeout, naturaldraincriterionfalse retained. This matched return of the failure strengthens group localization. The next narrower partition removes only its five-line inspector registration, preserving the other15lines exactly.+++### Inspector-only partition passes; genuine presenter relocation under test++Stage9 removed only the five-line inspector registration/content/environment group, retaining the remaining15interaction lines exactly and other970inputs. The identicalUI passed23.409s (80.059s total), source971be062… exact, Make/wrapper0/naturalcertainempty, no skips/runtimewarnings. Actual34events SUT162BA6FF… confirm both full Entry appearances/nativeBack disappearances and actualcallbacks/appends; exactsavedUTF8 and both association assertions passed. Inherited RuleSuggestionCoordinator warning retained.++The next candidate restores the genuine inspector and moves only its Mac host inside the existing TodayNavigationStack dashboard; iPad keeps its original outside placement. Binding/content/width/environment and other15interaction lines remain. Dashboard stack identity/reset/item guards remain. This is a placement repair candidate, not a claim about internalSwiftUI defects. Review identifies a specific new lifetime boundary: the Mac inspector now falls inside the dashboard reset identity, so retired presenter dismissal must not clear fresh inspector selection. That coverage is required before shipping.+++### Genuine Mac inspector relocation passes reduced trial; full source restored++Stage10 restored the genuine inspector at the dashboard root inside the same TodayNavigationStack on Mac; iPad retained its original outside placement. The identical reducedUI passed30.464s (80.835s total), source971dc2e… exact, actual41events SUT616EBD49… confirming two full editor/Back cycles and savedUTF8/association assertions. Make0/wrapper124 required only postprincipal birth-owned idleibtool91925SIGINT, finalemptycertain/nohardtimeout; the naturaldrain criterion remains false. Inherited compiler warning retained; no skips/runtimewarnings.++After exact source snapshots and peer review, full Work content/lifecycle/presenters were restored, all temporary navigation/construction logs and three diagnostic methods/actions removed, and fixture scheduling restored toHEAD. The original11UIjourneys remain. The candidate keeps all navigation ownership/path/identity/reset and iPad inspector placement. The Mac inspector's false dismissal now passes through the existing unchanged revision guard via a thin Bool adapter; true writes remain no-op and getter live. Four native ownership controls plus the existing mounted live-State proof cover retired dismissal/current transaction/directclear semantics. Those tests and the original full save/reopen journey are next required gates; this is not yet a qualified feature commit.+++## 2026-10-20: stronger iPad scroll control++The source-exact four-case iPad run passed three methods and reproduced the original560.5 versus584.5±2 failure. Removing only view-target registration passed that original method. The new additive nonzero-scroll regression then failed at the first Close restoration, so final Mac/Core/native packs remain dormant. Instrumented observation confirmed actual141.5pt row displacement with the same geometry/day and no inspector. Same-State stored offset180 became38.5 during width reflow; raw content estimates briefly fell below the viewport. Raw samples have no State identity and are only temporally correlated. No SDK-internal or precise clamping cause is claimed. The observation exited naturally with unchanged source and all11 source copies safe; the dedicated simulator was returned to its prior Shutdown state after the interval read. Instrumentation was restored exactly before preparing the separate outer-stack control. Full private evidence is retained in the ongoing repair qualification root; no code commit, push or device operation is claimed.+++## 2026-10-20: replacement Today restoration++The outer eager-stack control passed nonzero Close restoration but failed after actual Work/native Back. The separately gated observer distinguished both stages: Close retained row405.0; Work return changed it to584.5 with identical day/list/window geometry. The old Today State retained offset179.5. Replacement State2492 received an initial geometry callback0→0 that wrote179.5→0, then `onAppear` read target0. These are actual pre-teardown Work-return events; successor teardown events are excluded. Full private source/raw/native/log evidence and independent review are retained. Instrumentation was then restored exactly to the uninstrumented outer-stack candidate.++Initializing the existing `ScrollPosition` State from the saved binding, and removing only the late `onAppear` restore, passed all stages of the strict additive journey with natural Make/wrapper0 and unchanged971 inputs (`ecbdede7…aa33`). The native method took46.965s,146.144s total. All ten source copies are safe. This is a scoped pass, with33 inherited warning lines disclosed; broader gates and retained/virtualization coverage remain open. A single matched numeric update-count pair is being prepared to assess the new eager constructor read. It introduces no new timing budget or broad benchmark loop.+++## 2026-10-20: matched counts, retained returns and architectural seam correction++The matched initial native-drag interval recorded 13 constructors, 66 actual display-plan evaluations and 13 existing geometry writes for seeded restoration, versus 14/71/14 for the prior live restore. Both had one constructor per write; plans per write were 5.077 and 5.071. Independent review reconstructed each actual drag-to-first-note-tap window and verified all 174 counter events per arm with no gaps. Only the prior arm's later Work/Back failed; first Close passed. The same helper line was initially misclassified by a reviewer, then corrected from the ordered native actions. The failed arm and owned-helper cleanup remain failed/qualified, without relabelling. This is one descriptive count comparison, not a universal dependency, timing or large-day performance proof. Exact uninstrumented source restoration removed all counters and flags.++Adding the existing lazy noted-section wrapper to the stacked layout and extending the new regression with Home/activate and Reading-sidebar/Today return passed all five affected iPad methods on source807c. Every return used the original captured nonzero Y, followed by the unchanged day-reset oracle. The Mac13 attempt compiled but initialized zero methods: host logs show XCTest requesting Enable UI Automation and LocalAuthentication requiring user interaction. No system setting or service was changed and no blind retry was made. Human availability was requested.++Full Core on807c executed exactly 4,115 declarations: 4,059 passed, one real platform-seam failure and 55 standard skips. The six offending conditionals were in WideRootView, RecordHistoryView and WorkDetailView. The fix moves only compile-time adapters to existing Support/PlatformModifiers.swift; the allowlist and assertion remain unchanged. Independent static review confirmed exact inspector hosts, bindings and Mac/iOS accessibility/composition behavior, with the other967 inputs unchanged.++Corrected sourceb6de passed the unchanged ten-method seam suite in4.797s with zero warnings/skips/issues. The prepared reader initially expected tests.xml; SwiftPM produced tests-swift-testing.xml. The original reader/failure is preserved, and a separate report-only extractor retained all eight assertions. No tests or original reader were rerun. All eleven source copies were verified.++The same source then passed all five actual iPad methods in290.458s total, including the full60.887s strict nonzero Close/WorkBack/Home/sidebar/day-reset journey. Make/wrapper exited0 naturally, source971 stayed exact, runtime warnings/skips were zero, and all34 compiler-warning lines had unchanged inherited origins. Fresh unfiltered serial Core subsequently passed4,060 declarations plus55 standard skips: exact4,115 XML,273 executed parameterized declarations,2,778 arguments and6,565 expanded executions, with no warnings/issues and natural exit0 in219.728s. The strict raw UUID mismatch remains false; only the same two factory groups/three generated fields were separately source-qualified, with four unchanged whole-source proofs and eight rejected fixed-field mutations.++Native quick completed Make0 onb6de with all1,838 methods and157 arguments passing (1,943 expanded; no skips/runtime warnings). Its signed Mac app and embedded extension compiled, and strict host signature verification passed on exactly the same bytes after sandbox-only trust errors were preserved. The fixed launch-UUID disposable fixture was found through metadata-only probing. Wrapper124 records post-principal SIGINT cleanup of proven-owned ibtoold19473, not a hard timeout; final ownership drain is empty and certain. Independent warning/cleanup/source review completed with all14 checks true, all eleven source copies verified and three inherited warning lines qualified. Normal-host strict signature verification and the isolated fixture receipt were accepted. Both owned simulators are Shutdown, with no remaining build/test process. No code commit, push, merge, physical install or live-library action occurred. Current Mac13 remains unqualified pending human authentication during a coordinated attempt.+++## 2026-10-20: coordinated final Mac13 retry++The user directly confirmed readiness at12:12UTC for the actual macOS UI-automation request. After exact source/checkpoint/capacity verification, one preserved13-method retry launched12:13:55UTC. Automation initialized and the first real method began12:15:49UTC; no agent changed security settings or supplied authentication. The full selection passed13/13 with no skips/failures/runtimewarnings/issues, including original Save/reopen167.072s and exact NFD append/save/reopen/readback53.028s. Make and wrapper exited0 naturally at12:32:59UTC,1144.426s total, no hardtimeout/helpercleanup, empty certain owned drain. Source971 remained exactlyb6de963dccd259f5f5b15a500380b4f8d066e20da8f3de872ea408d8577f6486. The one postrun reconciliation passed all14 checks. Independent warning/source review and a separate follow-up evidence seal are recorded with this result; the prior sealed pending-authentication checkpoint remains historical and unchanged. No code commit/push/merge/install or broader publication qualification is implied.
diff --git a/specs/bugfixes/mac-chapter-history-qualification/report.md b/specs/bugfixes/mac-chapter-history-qualification/report.mdnew file mode 100644index 00000000..0f189a9e--- /dev/null+++ b/specs/bugfixes/mac-chapter-history-qualification/report.md@@ -0,0 +1,53 @@+# Bugfix Report: Mac chapter-history qualification++**Date:** 2026-10-20+**Status:** Scoped product repair preserved in `dc676a96`; five evidenced UI-test driver repairs now have accepted full phone 246-pass/two-standard-skip and full iPad 33/33 qualification on their recorded source bindings. Ordinary feature commit/push/draft PR preparation is authorized. Broader performance/full-inventory/publication gates remain open; no installation or merge.++## Issue and repair++Returning from a chapter to its Work on Mac could prevent the next genuine editor from appearing even though the callback selected the correct chapter. Controlled App-scene comparisons localized the failure to Today's inspector presenter placement. Hosting the Mac inspector on the dashboard inside the existing Today stack passed the original full Save/reopen journey. This establishes an app-composition repair without claiming an internal SDK defect.++The repair retains the navigation owner, typed path, destination factories and dashboard reset. A thin Bool adapter forwards dismissal through the existing revision guard so a retired inspector cannot clear a newer selection. iPad retains its original outside-stack inspector host. Real Mac history title/date views remain accessible beside the genuine preview Button; focused Edit and typed record cards expose their actual controls. Seeded navigation preferences reset consistently while preserving explicit restoration. Full Work content, sheets and lifecycle are present.++The affected iPad return checks exposed two additional scroll problems. Removing wide Today's target registration fixed the original zero-scroll return mismatch. A strict additive nonzero-scroll test then exposed inspector reflow and replacement-State restoration failures. The current candidate uses an eager outer composition with a lazy noted timeline in every wide layout, seeds ScrollPosition from the saved anchor during initialization, and removes the late live-binding restore. Real geometry writes and day-change reset remain unchanged; no tolerance, corrective scroll or original test body was relaxed.++A matched diagnostic pair measured the initial native drag before inspector behavior diverged. Seeded restoration recorded 13 constructors/66 display-plan evaluations/13 geometry writes; the prior version recorded 14/71/14. Both had one constructor per write, with 5.077 versus 5.071 plan evaluations per write. This one gesture showed no observed increase per write. It does not prove zero Observation dependency, universal performance equivalence or large-day rendering bounds. All counters and diagnostic flags were removed, with exact whole-source restoration verified before subsequent changes.++Full Core caught six platform conditionals outside the permitted seam. The correction moves only compile-time inspector, accessibility and history-preview adapters into existing Support/PlatformModifiers.swift. The actual hosts, bindings, modifier order and Mac/iOS view compositions are preserved. The platform allowlist and its assertion are unchanged.++## Current qualification++All results in the following scoped-product table bind 971 source inputs at `b6de963dccd259f5f5b15a500380b4f8d066e20da8f3de872ea408d8577f6486`.++| Check | Result | Qualification |+| --- | --- | --- |+| Standard fast cohort | 456/456 declarations; 552 expanded executions; 8.766s total | Current b6de source; exact fixed manifest, 17 parameterized declarations / 113 argument starts, zero warnings/skips/issues, natural Make/wrapper0 and unchanged source. |+| Platform seam regression | 10/10; 4.797s total | Zero warnings/skips/issues; natural exit0; exact source and eleven verified source copies. Original XML-filename reader failure is preserved; a separate report-only extractor retained all assertions. No test rerun. |+| Affected wide-iPad journeys | 5/5; 290.458s total | Close/day 26.152s, Edit 17.251s, original Work/Back 26.327s, strict nonzero/retained returns 60.887s, sidebar restore 17.986s. Natural exit0, no skips/runtime issues. All 34 compiler-warning lines have inherited, unchanged origins; none unknown. |+| Unfiltered serial Core | 4,060 passed + 55 standard skips; 6,565 expanded executions; 219.728s total | Exact 4,115 declarations, 273 executed parameterized declarations and 2,778 argument starts. Zero failures/warnings/issues; natural exit0 and exact source. Strict raw UUID mismatch remains preserved; only two source-defined factory groups are separately qualified, with eight fixed-field counterexamples rejected. |+| Native quick and signed Mac prerequisite | 1,838 methods / 157 arguments / 1,943 expanded passed; 139.501s total | Unfiltered selection, zero skips/runtime warnings. Mac app and extension strictly verified on the host; sandbox trust diagnostics preserved with unchanged signed bytes. Exact disposable-fixture UUID verified. Three inherited warning lines qualified. Make0/wrapper124 retains proven-owned post-principal helper cleanup; no timeout and empty certain drain. |+| Full Mac association selection | 13/13 passed; 1,144.426s total | One user-coordinated retry on unchanged b6de. All fourteen reconciliation checks passed; zero failures/skips/runtime warnings/issues. Natural Make/wrapper0, empty certain drain, no helper cleanup or hard timeout. All 34 compiler-warning lines have unchanged, previously qualified origins; none unknown. |++The new strict iPad journey captures one genuine nonzero row position and retains it through Close, Work/native Back, Home/activate and a real Reading-sidebar/Today return, then proves day reset at the original top. Every return uses the same captured Y and 2pt oracle. Sidebar return proves behavior, not a guaranteed retained State identity. No large-day rendered measurement is claimed.++Earlier scoped Mac evidence remains historical: native ownership 10/10, the full original Save/reopen journey, genuine Entry Open Work from both origins, and the two Close/keyboard/day/sidebar methods passed on their recorded source versions. All exact text, membership, draft/Save/Cancel, count, geometry and timing oracles remain. Current full 13-test Mac selection now passes, including the original Save/reopen journey (167.072s), exact NFD append/save/reopen/readback (53.028s), and inspector Work/Back routing. WideLayoutUITests is excluded from Mac compilation; no Mac result is inferred from its iPad selectors. The genuine Entry Open Work route does not qualify ordinary spine-button activation.++## Completed checkpoint and next step++The earlier zero-method attempt remains preserved as a host-startup failure. After the user directly confirmed availability at 12:12 UTC, one coordinated retry launched at 12:13:55 UTC. UI automation initialized and the first method began at 12:15:49 UTC; all thirteen methods passed and the process exited at 12:32:59 UTC. Authentication was left to the user. The agent changed no security/privacy setting, authorization database or system service; the successful startup does not prove which host setting caused the earlier timeout.++At the end of Mac qualification, the affected gate was complete on the same source as the accepted seam, iPad, full Core and native quick checks. The scoped review and feature commit subsequently completed as `dc676a96`; the pre-push follow-up below records later UI validation. No new product-contract decision was introduced. This checkpoint does not qualify ordinary spine-button activation or broader NoEpisode/performance/publication gates.++The qualification phase performed no commit, push, merge, physical-device install or live-library operation. Subsequent feature-branch preparation is tracked in the current feature checkpoint. Broader NoEpisode/performance and publication work remains outside this repair phase.++## Pre-push driver follow-up++Full standard iPad UI passed 33/33 on b6de in 826.463s. Full standard phone UI completed naturally in 9,525.721s: 245 declarations / 248 executions, 241 passed, five failed and two unchanged physical-performance simulator skips. Source stayed exact and there were zero warnings/runtime issues. The original native result, actual four launch argument labels, failed reader diagnostic and five failed-test artifact sets remain private and retained.++Native recordings/hierarchies show a saved second manual note outside the realized spine, an unscrolled two-page detached-note list, a largest-text review whose source rows continue below the search bound, and a visibly present Capture details header that the helper never tapped. Four UI-test-only repairs retain every semantic/count/text/size oracle. Seven affected journeys then passed on 971 / `efe8ac24…3992` in 864.299s with natural exits and exact source; one inherited metadata-tool warning has an identical historical target invocation and project input. At that stage, all other 967 inputs were unchanged. Focused success does not replace the failed full UI gate, and earlier b6de evidence is not relabeled. Complete current iPad UI passed 33/33 in 833.333s with exact efe8 source, zero warnings/skips/issues and natural exits; the unchanged strict retained-scroll/day-reset method passed in 61.313s. The complete efe8 phone rerun finished with 245 passed, one failed and the exact two standard simulator skips across all 245 declarations / 248 executions. All five earlier failed methods passed. The new failure is the record-pill assertion in `testReviewShowsExactSavedSourceWithoutGeneratedFacts`; its earlier pass is not a waiver. The complete result and native failure attachments are retained privately. Studio transport loss left the original launcher/guard completion receipts missing, so numeric wrapper exits, hard-timeout status and continuous drain remain unverified. Separate postrun checks prove all 971 source inputs and HEAD unchanged, no relevant process remaining, and both owned simulators Shutdown; these do not replace the missing receipts. The final series-token method passed in 574.372s with retained animation-idle diagnostics.++Native video and synthesized events show the intended Ada Keep tap near the sheet header while Ada's control was above the viewport, followed by four still-pending suggestions and no accepted pill. A fifth UI-test driver repair now requires full control visibility below its owning sheet toolbar before ordinary native tap, and waits for Ada's decision row to disappear before Done. The original saved-pill, alias and no-generated-facts assertions remain. Its candidate source is 971 / `25d23a0b…b023`; all other 966 inputs remain identical to the scoped b6de product qualification, and only this one test file differs from efe8. The focused 21-journey check (19 extraction plus two outcome journeys) passed in 1,155.297s with exact source, natural Make/wrapper exit 0, no failures/skips/runtime warnings, no timeout or helper cleanup and independently accepted certain drain. One inherited metadata warning has an identical earlier tool invocation and unchanged project input; unknown warnings are zero. The original record-pill method passed in 56.424s. The complete standard phone gate on this source finished with all 245 declarations / 248 actual executions accounted for: 246 passed, zero failed and the exact two standard physical-performance simulator skips. It ran without narrowed selection or added skips in 9,591.694s, with natural Make/wrapper exit 0, no timeout/helper cleanup, certain empty process drain, zero compiler/runtime warnings/issues and all 971 inputs unchanged. The original record-pill method passed in 55.985s. Four distinct actual launch configurations are preserved from this result, rather than copied from earlier runs. Root and independent final review accepted all 19 checks and the actual native/raw inventories. Both owned simulators were already Shutdown and no restoration action was needed. The accepted efe8 full iPad result retains its original source binding: only the private CharacterExtraction test helper differs, with no affected iPad suite, shared helper, fixture or product input. The current scoped full-phone UI gate is accepted; broader performance and publication acceptance remain open.++## Evidence++[Investigation history](investigation-history.md) preserves the complete chronology, original failures and source-specific results. Immutable private evidence roots are task-2/evidence/t2468-app-scene-continuation-20261020 (controlled comparisons) and task-2/evidence/t2468-mac-inspector-repair-qualification-20261020 (qualification). The completed coordinated Mac retry is retained separately in task-2/evidence/t2468-mac13-authenticated-followup-20261020; previous sealed roots are unchanged. Raw screenshots and native attachments remain private.
diff --git a/specs/character-chapter-associations/checkpoint.md b/specs/character-chapter-associations/checkpoint.mdnew file mode 100644index 00000000..4fc23d8a--- /dev/null+++ b/specs/character-chapter-associations/checkpoint.md@@ -0,0 +1,394 @@+# Preserved checkpoint++**Latest scoped UI acceptance:** full phone 246 passed / zero failed / two standard simulator skips on `25d23a0b…b023`; full iPad 33/33 on unchanged dependent source `efe8ac24…3992`. Root and independent review accepted both. Five UI-test driver repairs preserve every original semantic oracle; product/Core/native/Mac source remains the separately qualified b6de repair. Feature commit, push and draft PR preparation are authorized; broader performance and publication gates remain open.++## Current scoped repair checkpoint — 2026-10-20++The source at 971 inputs / `b6de963d…6486` has accepted unfiltered Core (4,060 passed declarations plus 55 standard opt-in skips; 6,565 expanded executions), standard fast (456 declarations / 552 expanded passes), native quick (1,943 expanded passes), signed Mac app/extension verification, five affected iPad journeys and all thirteen Mac association journeys. The native wrapper's proven-owned post-principal helper cleanup remains qualified separately; the Mac13 run exited naturally with no cleanup. See the [scoped repair report](../bugfixes/mac-chapter-history-qualification/report.md) for exact counts, source fingerprint, warning provenance and limitations. Earlier source-specific receipts below remain historical.++The scoped product repair is preserved in `dc676a96`. Full unfiltered iPad UI then passed all 33 methods on b6de in 826.463s with zero warnings/skips/issues and natural exit0. Full unfiltered phone UI completed naturally in 9,525.721s with **241 passed executions, five failures and two standard simulator skips**. Independent source/native review accounts for all 245 declarations and 248 executions, including four actual launch variants; source stayed exact, warnings were zero and owned processes drained. The original failed result and the initial reader's launch-argument schema diagnostic are retained, not waived.++Retained native evidence supported four test-driver repairs: reveal the complete lazy Work spine before counting, scroll the UUID-ordered recovery list before reading exact text, walk the actual long review list to its controls, and let native tap operate the visible disclosure while requiring its expanded-content witness. At that stage, only four UI-test files changed; all other 967 product/test/tool inputs remained exact. Seven affected semantic journeys passed on 971 inputs / `efe8ac24…3992` in 864.299s, naturally, with no failures/skips/runtime warnings and one separately qualified inherited UI-test metadata-tool warning. Every count, exact UTF-8, 44pt control, Save/Cancel, recovery, teaching and reparse assertion remains. The complete current iPad rerun passed 33/33 in 833.333s with zero warnings/skips/issues, natural exits and exact efe8 source; its strict retained-scroll/day-reset method passed in 61.313s. The complete efe8 phone rerun finished with 245 passed, one failed and the exact two standard simulator skips across all 245 declarations / 248 executions. All five earlier failed methods passed. The new failure is the record-pill assertion in `testReviewShowsExactSavedSourceWithoutGeneratedFacts`; its earlier pass is not a waiver. The complete result and native failure attachments are retained privately. Studio transport loss left the original launcher/guard completion receipts missing, so numeric wrapper exits, hard-timeout status and continuous drain remain unverified. Separate postrun checks prove all 971 source inputs and HEAD unchanged, no relevant process remaining, and both owned simulators Shutdown; these do not replace the missing receipts. The final series-token method passed in 574.372s with retained animation-idle diagnostics.++Native video and synthesized events show the intended Ada Keep tap near the sheet header while Ada's control was above the viewport, followed by four still-pending suggestions and no accepted pill. A fifth UI-test driver repair now requires full control visibility below its owning sheet toolbar before ordinary native tap, and waits for Ada's decision row to disappear before Done. The original saved-pill, alias and no-generated-facts assertions remain. Its candidate source is 971 / `25d23a0b…b023`; all other 966 inputs remain identical to the scoped b6de product qualification, and only this one test file differs from efe8. The focused 21-journey check (19 extraction plus two outcome journeys) passed in 1,155.297s with exact source, natural Make/wrapper exit 0, no failures/skips/runtime warnings, no timeout or helper cleanup and independently accepted certain drain. One inherited metadata warning has an identical earlier tool invocation and unchanged project input; unknown warnings are zero. The original record-pill method passed in 56.424s. The complete standard phone gate on this source finished with all 245 declarations / 248 actual executions accounted for: 246 passed, zero failed and the exact two standard physical-performance simulator skips. It ran without narrowed selection or added skips in 9,591.694s, with natural Make/wrapper exit 0, no timeout/helper cleanup, certain empty process drain, zero compiler/runtime warnings/issues and all 971 inputs unchanged. The original record-pill method passed in 55.985s. Four distinct actual launch configurations are preserved from this result, rather than copied from earlier runs. Root and independent final review accepted all 19 checks and the actual native/raw inventories. Both owned simulators were already Shutdown and no restoration action was needed. The accepted efe8 full iPad result retains its original source binding: only the private CharacterExtraction test helper differs, with no affected iPad suite, shared helper, fixture or product input. Current full-phone UI acceptance is green on the new source; broader performance/publication acceptance is not claimed. Focused passes never substituted for a full gate, and both earlier failed runs remain failed historical evidence. The earlier Core/native/Mac results retain their b6de source binding and are not relabeled as full efe8 runs.++The current continuation authorizes scoped repair review and ordinary feature-branch commit, push and PR preparation. It requests no installation or merge; earlier operational authority below is historical. The required complete phone UI and both complete iPad-only suites now have accepted results on their explicitly recorded source bindings. Existing duplicate observation/settling and capture performance failures, the complete current performance inventory and broader publication review remain separate unresolved gates. No budget or assertion is waived, and no performance redesign is added here. A draft PR must state these limits and retain the earlier fixes.++## Historical phone deployment and qualification++The owner requested a Devsterism test installation before merge. Xcode MCP built the current reviewed feature successfully in **46.36 seconds**, using **Asterism Development**, configuration **Development (`-Onone`)**, version **0.7.0 (1)**. That deployed build used HEAD **`9f71c5dc`** plus the reviewed working-tree repairs. After the strict recovery gates passed, the twelve-path repair was preserved in **`a9fe5b75`**; this did not reinstall or change the phone build. After the user confirmed the phone was unlocked, a single `RunProject(attachDebugger: false)` completed successfully in **11.438 seconds**, installing and launching Devsterism. The actual installed build passed strict signatures and the same development identity checks. Xcode refreshed signature blobs, but every byte outside the three app Mach-O signature blobs matches the preserved package; extension signed binaries are identical. The library App Group container path and released Asterism metadata are unchanged. iOS assigned Devsterism a new private data-container path; contents were not inspected, and no uninstall/reset/data-migration or account-switch command was issued. The installation receipt is retained outside Git at `../evidence/t2468-devsterism-feature-install-20261019/installation-receipt.json`.++During this Xcode build, localisation extraction rewrote only `Localizable.xcstrings`, adding the existing Day parameter metadata and refreshing the existing chosen-day intent description. Independent review confirms the keys match the unchanged intent source, all 39 translated entries are unchanged, and there is no new feature code. The deployed build’s source map is **971 / `33a479c2`**, including that generated metadata; it is not relabeled as the previously tested `17ec40d3` source. After installation completed, root restored only the exact preserved catalog bytes and verified all 971 working-source inputs match **`17ec40d3`**, with HEAD unchanged. No rebuild or device action followed that source restoration.++The targeted phone batch completed in **515.684 seconds** with all **12 exact journeys passed**, zero warnings, failures, skips or runtime issues, natural Make/wrapper exit 0 and certain process drain. Its source guard correctly failed because Xcode extraction changed the catalog during the run. The failed guard, before/after source maps, generated catalog and full xcresult are preserved in [`targeted-phone-environment-fix-catalog-source-failure`](../../../evidence/t2468-save-time-known-links/targeted-phone-environment-fix-catalog-source-failure/archive-manifest.json). It is not a green precommit gate. The preserved `17ec40d3` catalog bytes were restored after deployment. The fresh strict phone run then passed all **12 exact journeys** with zero warnings, failures, issues or skips in **525.180 seconds**, with natural Make/wrapper exit 0, certain process drain and all 971 source inputs unchanged. Root and peer accepted the result and verified the complete 95-file evidence manifest and all original copies. The separately admitted iPad gate then passed all **4 exact journeys** with zero warnings, failures, issues or skips in **166.395 seconds**, natural exits, certain drain and unchanged source. Root and peer accepted it and verified all 81 archived files and original copies. These completed the targeted precommit bars for **`a9fe5b75`**. The nine-line Mac-only test route remains uncommitted and awaits actual Mac runtime qualification.++The full phone/iPad/Mac publication runner is prepared but unrun. Human Mac authentication, required performance failures and final publication reviews remain open. The wider capture redesign remains paused. The requested test installation does not waive those merge gates.++## Qualified 971-input candidate and environment follow-up++The reviewed creator-history read, pure mark-overlap short circuit, singleton capture-basis selection and minor user-guide clarification were applied as exactly nine paths after the unchanged current/main controls completed. Two test-only fixture corrections followed; production bytes remained identical throughout. The qualification below binds **971 inputs at `8a241a730082d22caba7df03f3494cbffeda3da1b4df2d54a9f0fe8ef9951036`**. A later two-view environment repair was applied at 971 / `3cf884a7`, then received a native regression test at `17ec40d3`; the fresh Core, fast and native results below bind those later bytes. Earlier full-source receipts are not relabeled. At that qualification HEAD was `9f71c5dc`. The reviewed twelve-path follow-up is now committed as `a9fe5b75`; only the previously preserved Mac-only test route remains uncommitted. Prior bytes and application evidence are retained in [`nine-path-application-20261019`](../../../evidence/t2468-save-time-known-links/nine-path-application-20261019/receipt.json).++Latest verification source is **971 / `17ec40d3`**, adding one statically reviewed explicit-day/calendar native regression to the two-view repair. Fresh unfiltered Core passed **6,565 executions** (4,060 passed declarations plus the exact 55 opt-in skips) in **223.753 seconds**, with zero warnings/issues and natural Make/wrapper exit 0. Root accepted all eleven checks, including the same separately qualified two generated-UUID fixtures; the original raw false comparison remains preserved. Standard fast then passed **456 declarations / 552 executions** in **7.054 seconds**, with exact arguments/source, zero warnings/issues/skips and clean natural drain. The signed Mac/full native run has now completed: Make exited 0 and all **1,834 declarations / 1,939 expanded executions** passed with zero structured runtime warnings. Final warning, fixture and ownership review is accepted: all thirteen root and sixteen peer checks pass. Three inherited compiler warning occurrences, one destination warning and all 352 raw SQLite fixture-cleanup diagnostics remain explicit. The complete 4,940-file evidence manifest and original copies were independently hash-verified. The wrapper exited 124 solely after cleaning up one proven-owned idle `ibtoold` helper; this was not a test timeout or natural signal-free drain. Existing Development Mac app and extension both passed strict signature verification on the normal host, and the exact synthetic launch-UUID library was retained. Both owned simulators were already Shutdown. The new 12-phone affected-journey selection completed with zero runtime warnings but failed its source guard during Xcode catalogue extraction, as recorded above; the later strict recovery gates passed all twelve phone and four iPad journeys as recorded above. Native results alone do not establish rendered UI acceptance.++Focused correctness passed all **94 declarations / 139 executions**, including nine parameterized declarations and all 54 exact named argument tuples, with zero failures, errors, skips, runtime issues or emitted warnings. Make and wrapper exited 0 with certain natural process drain in **26.625 seconds** at 2026-10-19T18:42:27Z; all 971 inputs remained unchanged. Root independently verified raw XML IDs, all argument lines, passed terminals, expanded counts and source/drain. This warm incremental run is not a clean-rebuild claim. The prior compile failure and four new-fixture assertions remain archived; the corrections add explicit Sendable captures, a valid dated hiatus and a present empty identity check without weakening assertions.++The creator controls failed at 162 ms current versus 161 ms recorded main against 50 ms; all three capture controls also failed comparably on both sources against 250 ms. Those results support inherited-path repair, without isolating a feature cause. The original N10, creator and capture budgets, sample counts, fixtures, assertions and known-issue scopes remain unchanged. The separate capture operation-reuse draft was excluded.++| Gate on qualified 971 / `8a241a73`, before environment repair | Status |+| --- | --- |+| Focused correctness: 94 declarations / 139 executions | Passed; exact source, arguments and natural drain accepted |+| Full Core: 4,115 declarations / 6,565 executions | Passed: 4,060 started/passed plus exact 55 standard opt-in skips; source and arguments accepted |+| Standard fast | Passed: 456 declarations / 552 executions, exact arguments/source, zero issues/skips/warnings |+| Signed Mac/native quick | Passed: 1,833 declarations / 1,938 executions, strict app/extension signatures and isolated fixture verified |+| Original performance gates | Current original three-method diagnostic failed five hard assertions; creator detail passed at 42.8 ms; full52 remains owed |+| Targeted affected phone UI: ten journeys | All assertions passed; qualification blocked by eight actual SwiftUI environment runtime warnings |+| Full phone / iPad UI | Owed |+| Mac runtime | Awaiting actual human availability for Enable UI Automation |++The current original three-method diagnostic completed naturally at 2026-10-19T19:05:00Z in 876.105 seconds, including 629.96 seconds of Release compilation. Source stayed exact and owned processes drained without signals or uncertainty. Creator detail passed at 0.042777s against 0.050s; duplicate observation/settling failed at 4.148841s / 6.765119s against 2s, and capture medians 0.832219s / 0.451331s / 0.833851s failed all three 0.250s ceilings. All three rule-only arms passed. The complete three declarations / five executions / nine distributions preserve five hard issues and three original known issues; root accepts evidence integrity, not the failed gate. All 26 emitted compiler-warning occurrences are independently baseline-qualified, with the original unmatched report retained. The complete 1,024-file archive, including all 971 source files, is hash-verified by root. See `performance-attribution.md`.++The current unfiltered serial Core run completed naturally with Make and wrapper exit 0 in **223.505 seconds**. All **4,060 started declarations** passed, with the exact **55 standard opt-in skips** (4,115 XML declarations), 382 suites, 273 executed parameterized declarations, 2,778 argument starts and **6,565 expanded executions**. Source stayed exact at 971 / `8a241a73`; there were no warnings, issues, model known issues, signals or remaining owned processes. The original raw comparator reports two unchanged fixtures whose three UUID fields are generated at runtime. Separate source-grounded qualification verifies those fields, every other byte and all 264 other title groups / 271 declarations; eight fixed-field mutation controls reject changes. An initial root report confused title-group count with declaration count; both versions are retained, and the source-derived correction confirms 266 distinct parameter titles across 273 declarations. Root and peer acceptance, raw reports and all 971 source files are durably hash-verified in [`full-core-971-accepted`](../../../evidence/t2468-save-time-known-links/full-core-971-accepted/archive-integrity.json), 1,021 files in total. This is current Core correctness evidence only.++The standard unchanged fast cohort subsequently passed all **456 declarations / 552 executions**, including 17 parameterized declarations and 113 argument starts, in **7.677 seconds**. Exact source, raw XML, terminals and arguments match the same-source accepted Core evidence, with zero warnings, issues or skips and natural Make/wrapper exit 0. Root independently hash-verified the complete 38-file [`fast-971-accepted`](../../../evidence/t2468-save-time-known-links/fast-971-accepted/archive-integrity.json) archive.++The earlier `8a241a73` signed Development Mac build and unfiltered native quick also passed: **1,833 declarations / 1,938 executions**, 52 parameterized declarations and 157 argument nodes, in **257.005 seconds** with natural Make/wrapper exit 0. There were no failed/skipped methods, structured runtime warnings, signals or remaining owned processes. All 30 emitted compiler-warning occurrences (18 coordinates) and eight tool warnings were independently baseline-qualified. Raw SQLite fixture-cleanup diagnostics remain present: 359 current versus 356 prior occurrences; 358 current records have complete dedicated-simulator temporary paths and one interleaved fragment proves only the owned-device prefix. No claim of diagnostic absence or isolated cause for every fixture is made. The sandbox report-cache permission failure and signing trust diagnostics are retained separately; host report export and strict verification succeeded on the identical recorded app/extension executable, Info and sealed-resource hashes, without a test repeat, re-sign or rebuild. The exact launch-UUID temporary library and frozen pre-bootstrap mirroring-off policy were verified. Both dedicated simulators were already Shutdown when checked, so no shutdown request was issued. Root verified every file in the complete 4,083-file [`native-971-accepted`](../../../evidence/t2468-save-time-known-links/native-971-accepted/archive-integrity.json) archive, including the entire xcresult, source and diagnostic qualifications.++Rendered and performance qualifications remain separate. The private capture attribution completed naturally in 759.750 seconds, with all 66 projection calls and original assertions retained. Separate root/peer review qualifies all 43 inherited warning origins while preserving the original narrow-catalog rejection. All three hard capture ceilings and original known issues remain; clocks, helper closures, mutex and possible ARC lifetime effects prevent budget or exact baseline timing qualification. The complete 648-file evidence archive is hash-verified. See `performance-attribution.md`.++The earlier `8a241a73` affected phone batch completed naturally at 2026-10-19T19:52:48Z in 453.513 seconds. All ten exact journey IDs passed, with zero failures/skips, exact shipping source and certain process drain. Acceptance remains blocked by eight actual runtime warnings: the stored, uninstalled WorksView used by WorksSearchContent reads Calendar and publication-day environment values outside an installed View. The two original files match the older baseline. A statically reviewed two-file repair now makes installed WorksSearchContent own those environment reads and passes mandatory explicit day/calendar values into shared helpers; mounted WorkRow and locale behavior remain unchanged. At that pre-repair checkpoint, runtime verification and a value-level override regression were pending. The later native regression passed, and the subsequent twelve-phone batch reported zero runtime warnings but failed its source guard during catalog extraction, as recorded above. No warning is suppressed or waived. iPad is unadmitted and unrun. Each selected UI test supplies its own random fixture UUID and seeded scenario; frozen source proves contained temporary roots with CloudKit disabled, and fixture-specific assertions passed. The launcher-UUID filesystem probe remains unverified because individual test UUIDs were not logged; it does not establish production access or exact per-test filesystem correlation.++The two view files and one new value-level native test now bind 971 / `17ec40d3`. Static review confirms the test's fixed hiatus-return day and UTC/Los Angeles calendar distinction; that native method subsequently passed in the accepted 1,939-execution run. Strict phone/iPad acceptance remains pending after the catalog source-guard failure. The earlier production-only after-map was `3cf884a7`. A separate scoped capture-reader design/partial private draft is paused under Decision7 as material scope expansion after the morning checkpoint; no capture shipping change or run is admitted. All 607 shipping Package inputs remain unchanged by that draft. No current-candidate commit, push, merge or installation is claimed. Earlier receipts below retain their explicit source bindings.++## Preserved 970-input checkpoint and integrated follow-up++The approved feature was preserved in commit `14a7d887` and rebased to `3376bc2a` onto main `47eef29f`; the previous feature HEAD was `1c3a66a0`, with recovery ref `backup/T-2468-before-main-rebase-70444f08`. Rebase verification preserved all 233 feature-only blobs and main’s disjoint constructor/chosen-day work. Reviewed indexed pending lookup, empty-cast guards, operation-local performance repair and their regression tests are preserved in `9f71c5dc` (11 code/test files). All 970 product bytes are identical before/after this preservation commit; the source-bound correctness receipts remain applicable. A Mac-only test route and documentation follow-up remain uncommitted. That preserved source is 970 inputs at `435f8236af8db352e31100ca6432ca8e7120c0b002c9b65b569301972f3fea86`.++The lookup/empty-cast follow-up passed 55 declarations / 124 expanded executions on its earlier 969-input binding. The performance repair passed 95 declarations / 106 executions, exact arguments and zero failures/errors/skips on the current 970-input binding; all fourteen warning origins predate the feature. Real multi-plan source combination, ordinary deletion and failed-chunk replay are covered. Complete private attribution now has accepted physical-data, source-integrity and process-drain proof; its timings remain excluded from budget acceptance. Earlier Core/native/rendered receipts retain their original bindings. See `save-time-known-links/implementation.md` and `performance-attribution.md`.++The current original uninstrumented N10 completed naturally in 788.834 seconds, with only the two unchanged two-second median assertions failing: observation 4.167216s and settling 6.763732s. No semantic assertion failed; all 970 inputs and the original test/fixture/Make contract remained unchanged. The engineering performance blocker remains open; the measured settling reduction from the prior 7.115196s does not grant acceptance. Unfiltered current Core passed all 4,049 started declarations plus the exact 55 standard opt-in skips (4,104 total), with 6,512 expanded executions, 2,730 argument starts and zero warnings or test/model issues. Make and wrapper exited 0 with natural process drain in 222.313 seconds; all 970 inputs remained unchanged. The original historical-argument parser mismatched three generated UUID fields in two unchanged fixtures; the preserved source-grounded scoped proof and independent root review resolve only that parser qualification, without a runtime rerun or relaxed case/field checks. Durable hash-verified evidence: [`full-core-970-accepted`](../../../evidence/t2468-save-time-known-links/full-core-970-accepted/archive-integrity.json), including the original reconciliation, scoped proof and root review. Current standard fast passed all 456 declarations across 32 suites, including 17 parameterized declarations / 113 arguments and 552 expanded executions, with zero issues, skips or warning origins; Make and wrapper exited 0 with natural drain in 7.253 seconds. Exact source/arguments and independent XML review are accepted; durable hash-verified evidence is [`fast-970-accepted`](../../../evidence/t2468-save-time-known-links/fast-970-accepted/archive-integrity.json). Current native runtime passed all 1,833 declarations / 1,938 expanded executions, with no failures, skips or structured runtime warnings; both signed Mac host and embedded extension passed strict verification. Root accepted exact native identifiers/arguments, source parity, isolated fixture evidence and natural 260.080-second process drain. All 26 compiler-warning occurrences and eight tool warnings are preserved and baseline-qualified; the run is not warning-free. The original sandbox certificate-trust diagnostic is retained separately from strict-valid host verification of the identical signed binaries. Full hash-verified evidence: [`native-postrebase-read-reuse-970`](../../../evidence/t2468-save-time-known-links/native-postrebase-read-reuse-970/final-integrity-receipt.json). The full default host performance gate completed naturally at 2026-10-19T17:58:22Z with Make exit 2 after 1,630.539 seconds on the unchanged 970-input source preserved at `9f71c5dc`. All 52 declarations / 55 expanded executions ran across nine suites, with six hard assertions failing in three declarations / five expanded cases: creator detail 0.161948s > 0.050s; duplicate observation 4.261136s and settling 6.778212s > 2s; capture projection for duplicate Site rows, missing Site and duplicate identity 0.915654s / 0.493550s / 0.915392s > 0.250s. Nine issues remain confined to their original known-issue scopes; the outside regression ceilings remain hard failures. A separate offline report parser recognizes the three original state-argument known-issue lines, with missing/duplicate/unknown-state and outside-scope rejection controls; the original parser and reconciliation are preserved. Independent integrity review reconciles exact test/argument/XML counts, unchanged sources and certain natural process drain; root acceptance confirms report integrity while the gate remains failed. There are no errors, skips or missing terminals. The warm-cache run emitted no compiler warnings, without a clean-rebuild claim. This failed gate establishes no speed improvement or performance exception. Unfiltered phone/iPad gates remain owed. Mac runtime still awaits actual human availability for XCTest’s Enable UI Automation prompt. No threshold, assertion or runtime gate is waived. No push, merge or physical installation has occurred during this continuation. This section supersedes historical statuses below.++## Historical 900-input validation status++This historical section superseded earlier pending states at its recording; the current checkpoint above now supersedes it. Asterism T-2468 is a verified, uncommitted correctness checkpoint, not overall feature GREEN. The selected source retains the reviewed import-history reuse, lazy raw Work bucket, archive fidelity correction and captured-revision navigation guard. All three additional performance trials were rejected; exact restoration and the authoritative 900-input source check passed.++Final composed correctness is complete: unfiltered serial Core passed 3,962 declarations with the exact 55 existing opt-in performance test skips (4,017 total); fixed fast passed 456; signed Mac app/embedded-extension compilation succeeded; full native passed 1,791 declarations and 1,871 expanded cases. Exact identifiers, arguments, warning provenance, source checks and process drain are reviewed. The native wrapper's 124 is preserved separately from native exit 0: only a birth-verified post-Xcode ibtoold helper was stopped. The dedicated simulator is Shutdown, no heavy job remains, and no next run is admitted.++Readiness remains blocked by the original Release observation/settling budgets and incomplete full 33-test performance gate, plus the separately tracked inherited iPad cross-width restoration failure, which remains unwaived for full UI acceptance. The parent explicitly kept that defect outside T-2468; no feature position-contract decision remains pending. No budget, assertion or tolerance was waived. Full unfiltered phone/iPad UI acceptance remains a pre-push obligation. No feature commit, push, merge, physical install or real-library operation occurred.++| Area | Current evidence and remaining work |+| --- | --- |+| Import correctness | 80 declarations / 84 cases across eight suites passed, including corruption boundaries and failed-save rollback/retry. Existing save chunks and default batch size remain unchanged. |+| Lazy raw history bucket | Meaningful runtime RED exposed exactly two traversal-count failures while data semantics passed. GREEN passed five declarations / six cases, then 85 declarations / 90 cases across nine suites. Exact inventory, no skips/issues or new warning origins; guards drained. Complete raw history remains available for global validation. |+| Archive fidelity | 14 declarations / 17 cases passed, including both raw/effective title directions, split carriers, and exact-NFD export/import/readback. |+| Native editor/navigation | Editor suite passed 10 declarations / 13 cases. Navigation passed exact separate 62 AppNavigationTests and 28 AppNavigationTodayTests. Native Xcode results passed; ownership guards separately recorded cleanup of proven post-Xcode helpers. |+| Debug comparison | Same import archive: pure baseline A 30.233s; baseline plus common repairs B 0.717s; earlier feature snapshot C 0.741s. Post-bucket D 0.744s. Duplicate D observation 3.262s / settling 5.868s versus C 3.277s / 7.965s, with exact record/action counts and saved-data checks. These single Debug observations do not establish isolated causality or clear Release budgets. |+| Original Release budget | Selected original declaration completed all ten samples per distribution: settling median 6.648267s and observation 3.932553s, both above the unchanged 2s limits. Exactly two budget issues; no semantics issue or skip. Build 561.97s, test 153.168s, total 718.353s; source unchanged and processes drained. Buffered output prevented separate runtime-clock activation; actual test duration is independently recorded. Full original 33 remains open. |+| Mac rendered navigation | Captured-revision binding: meaningful RED ran all six methods and failed five stale-clear assertions; phone GREEN passed6/6 in0.021s and Mac GREEN6/6 in0.492s, including real mounted old-State readers, transactions and direct clears. Five affected navigation suites passed120 declarations/128 cases, no warnings/skips/issues. The final five original uninstrumented Mac journeys passed in242.216s, including Work→Back→Entry/day and exact Unicode Save/Cancel/relaunch. Source900 matched; Mac guards exited0 naturally, phone helper-only cleanup is separately root-reviewed. All inherited warnings are source-qualified. Actual Mac UI UUID-store isolation is verified; native Mac6 bootstrap namespace is unverified. This clears the observed Mac cohort without assigning the earlier nil caller; all failed/instrumented histories remain retained. |+| iPad scroll | Strict same-geometry original and candidate controls both failed with 24pt movement. Instrumented numeric run failed in 28.020s with 72pt movement; window/list geometry checks passed. A bounded boot/read/shutdown recovered 78 numeric events: inspector reflow changes the shared anchor, and later restoration consumes it. Observed insets were zero. A follow-up labelled run recovered 78 events and 26 complete callback brackets: the suspicious writes share one State-storage token, with no overlapping cross-token writes. Reflow plus repeated restoration is the observed seam. A scroll-position contract across width changes is a separate scope decision; no correction or assertion waiver is selected. Simulator is Shutdown and all diagnostic source restored. |+| Current attribution work | The excluded current-Release initial-generation profile completed naturally with exact counts and both samples inside the worker interval on the same kernel clock. It supports narrow hypotheses, not median attribution. The descriptor-only prefetch trial passed88 declarations/93 cases, then failed both original2s Release limits: settling6.281479s / observation3.682579s, N10 each (build567.74s, test146.912s). Exactly two budget issues; natural guard2/drained, candidate900 unchanged. Helper-birth clock activated; firstDistribution remained absent under buffered output, without retrofit. This modest single-run movement did not justify retention: both files were restored exactly and full900/binding green900 passed. The completed private value comparison rejected global roots-only warming: combined776.480ms→874.807ms per eight iterations, despite cheaper construction, with identical full outputs/counts. Default extraction queries must retain current caching. The mutation-capture/finish-only alternative passed329 declarations/31 suites, exactly442 expanded executions (288 ordinary plus154 argument executions) in19.455s. Each parameter value matches its source; no issues/skips/new warning origins. Guard0/drained59.802s, candidate901 exact. Initial greedy-title parser evidence is preserved; corrected read-only reconciliation changed no test/run. The original N10 Release trial then completed with exactly two budget failures: settling6.309745s/p957.237939 and observation3.796133s/p954.512053, n10 each against2s. Build567.02s, native149.095s, guard719.412s; natural2/drained/no tracking errors or signals. Helper-birth clock activated; buffered firstDistribution remained absent without retrofit. All26 warning origins/11 files are baseline-qualified. Root rejected the trial and restored all900 compiler inputs exactly, including authoritative binding green900; the private patch/tests and failed evidence remain preserved. No additional optimization is admitted. Final composed gates are being prepared on restored900. |+| Prior broad gates | Earlier source passed4,002 package declarations (3,947 passes plus55 explicit opt-in performance skips), fixed fast456, signed Mac app/extension compile and native1,784 declarations. These predate current repairs. Current inventories derive4,017 package declarations and1,791 native declarations (including the inspector control and six binding methods), with40 native parameterized declarations; runtime argument nodes are separate. The fixed456 fast manifest is byte-identical. Final composed revalidation is admitted one step at a time on restored900. The unfiltered serial Core gate now passed its exact4017-declaration inventory:3962 passed plus55 existing opt-in performance skips, across367 suites (356 started/11 skipped). All2573 logical argument starts match passed terminal counts across231 executed parameterized declarations, yielding6304 expanded executions; no test/model issue, no missing/unexpected/unpassed case. Source900 matched, natural guard0/drained319.535s (build122.12s). All20 compiler warning origins are inherited/root-reviewed. Initial single-line parser missed22 multiline values; the preserved-log v2 report corrected only reporting, without a rerun. The unchanged fixedfast456 gate then passed exact456 IDs/32 suites and552 expanded executions (17 parameterized declarations/113 arguments), no warnings/skips/issues, natural0/drained6.557s and source900 unchanged. Signed Mac app/embedded-extension compilation and full native1791/1871 then passed with no failures/skips. All120 Argument nodes passed across40 parameterized declarations. Three inherited tool warnings are reviewed; no compiler/structured runtime warning occurred. Native0 and wrapper124 are separately accepted: the sole verified post-Xcode ibtoold was stopped, leaving no owned process/error/uncertainty. Exact UUID-store evidence is retained and the dedicated simulator is Shutdown. Source233parameter attributes are distinct from expanded executions; currentcomplex argument expressions remain raw-evidence/root-reviewed, without false static-value claims. |+| Feature checkpoint | Not ready for a feature commit. Original Release budgets/full33 and inherited iPad restoration remain open. Preserve the accepted Mac cohort and current source, preserve the verified final-source correctness checkpoint, then resolve the performance failure and iPad contract before any feature commit or pre-push acceptance. No assertion or budget waiver is selected. |++Run3 used the independently reviewed bounded process tracker, with a 30-minute runtime deadline from the verified owned helper birth at 12:53:39Z. The first completed distribution satisfied the separate ten-minute first-distribution bound. INT was sent to the verified root group at13:23:39Z; later signal attempts encountered already-exiting/defunct process identities. The supervisor exited124 at13:23:52Z, reporting no remaining owned identities; a fresh complete session scan at13:24:24Z confirms no members of session60300. No unrelated process was signalled. Exact reconciliation includes the alternate known-issue pass glyph: five completed passes, including backup export's existing known 430MB/400MB memory issue; one failed duplicate declaration; one interrupted import;26 unstarted. No skips or unexpected declarations. All898 frozen compiler files and554 exact-baseline files remain unchanged; all four original M4 suite files are byte-identical to baseline. Private evidence: composed-m4-3-reconciliation.json, m4-3-session-drain-check.json and m4-3-source-postchecks.json. No sample, threshold or test assertion changed.++The read-only import audit confirms both current transition call arguments match baseline39696ad ignoring whitespace. Import first unions raw actions, then invokes a fresh public history writer per applicable Entry, saving every 500 records. No other direct raw-action mutation occurs inside that Entry loop. This path was deliberately excluded from the approved four-site duplicate repair; no import optimization has been applied. Reusing one session per actual import save chunk would require explicit scope authorization and pending-clear, global-conflict, failed-chunk/retry and between-chunk corruption regressions. The source-derived repeated-read model is not an actual in-flight row count or measured time attribution. Private evidence: noepisode-import-readonly-scope-audit.json.++An independent Mac source audit further qualifies the rendered failure: line64 checks the conditional work-title before line65 checks the note editor. Inspector Edit, showTodayEntry, the selected-ID destination and stack identity are unchanged from baseline; no source-confirmed product defect or baseline defect is established. A separately authorized diagnostic should inspect the existing destination UUID, loading/unavailable and note-editor markers after Edit. This distinguishes route loss from loading/title publication without weakening the original assertions. No additional Mac execution is authorized or started while the question remains unanswered.++The reviewed read-only prefetch probe completed successfully after run3 drained: build61.32s; bounded runtime7.47s. All six fresh-context calls returned exactly the same5,750 complete note facts, including timestamp bits; no pending changes or saves. Two measured counterbalanced pairs after warm-up gave total Entry-fetch-plus-facts medians0.451037s normal and0.280372s prefetched, a0.170665s diagnostic saving. Facts alone fell from0.263101s to0.028466s while fetch became more expensive. All205 retained original-store files and898 shipping compiler inputs remained unchanged. This copied synthetic Debug dataset/shared-container result is not an M4 verdict or sole-cause attribution, and does not remove the audited import amplification. No further shipping optimization follows from it. Evidence: noepisode-facts-prefetch-result.json, run-1.jsonl and postchecks.json under the private evidence directory.++Concrete next decisions remain pending: permission for one focused synthetic Mac route/load diagnostic using existing automation permissions, and whether to extend the narrowly approved NoEpisode repair to the separately audited import save chunks. No speculative import reuse, extra Mac run, feature commit, push, merge or physical-device operation is performed while these are unanswered.++### Authorized continuation after the decision checkpoint++The parent explicitly authorized the focused Mac diagnostic and narrow import history reuse within existing 500-record save chunks, preserving behavior, global checks, persistence boundaries and budgets. The earlier pending-decision paragraph is historical. The source checkpoint archive remains preserved unchanged.++The focused Mac marker journey executed exactly one declaration and failed the original title assertion in34.198s. Both retained app/window marker sets show the inspector closed, with no Entry destination, loading/unavailable, note-editor or title marker immediately after Edit or after the original20-second wait. No permissions changed. The native result confirms one failure/no skips. The guard reaped a lingering owned ibtoold helper after Xcode exited; no owned descendants remain. This establishes the missing-destination stage, not whether SwiftUI reset the selected value or lost its presentation. The route and stack-identity coupling are unchanged from baseline; no baseline Mac pass or feature-specific cause is inferred. A reviewed temporary value/binding trace preserves the exact binding transaction/value forwarding and routing, is gated to the Mac synthetic fixture, and must be removed before final validation.++Importer TDD reached meaningful runtime RED: after the absent-seam compile failure, the seam-only implementation still created a fresh session per Entry. All six declarations ran, with ten failures exclusively on expected per-chunk session/read counts; pending clears, overlap marks, empty chunks, global contradictions and failed-chunk/retry semantic assertions passed. The subsequent reviewed GREEN scopes the lazy session lexically inside each Entry chunk and releases it before the existing save; the default500, all other phases and every assertion remain unchanged. Focused GREEN and bounded matched-baseline evidence remain pending; no broad suite is repeated yet.++Historical run1 runtime detail: the Release build completed successfully in 698.40 seconds. The original duplicate-settling declaration started, but no distribution completed within the recorded 60-minute helper runtime bound. Main sent INT only to identity-verified helper37071 at22:36:33 local (launch21:36:19, actual60m14s); helper and parent34864 drained and the Make run exited2. Exact reconciliation reports expected33/started1/passed0/missing32, expected4 suites/started1, no unexpected IDs, no skips or known-issue lines. This is an incomplete timeout, not a measured median assertion failure or accepted budget breach. The measurement file was never created. Raw composed-m4-1.log, original-m4-33-reconciliation.json, m4-runtime-bound.json, m4-owned-stop-events.jsonl and three one-second stack samples remain private under /tmp/t2468-ledger-build. No unrelated process was signalled.++Samples show observation/settling code in existing NoEpisode history processing. Meddy UI, its later signed Release build, further notified regression/publication work, and the separately reported PR112 Development build occurred during portions of this long run; exact overlap is not fully measured. Default median assertions were retained, with no controlled quiet-host p95 claim. Warning provenance covers43 baseline-unchanged emitting expressions. The source freeze remains preserved; no performance optimization, baseline waiver, implementation commit, push or merge followed this timeout.++The bounded read-only dependency audit (m4-noepisode-dependency-audit.json) found the sampled NoEpisode writer/index/history and original Duplicate fixture byte-identical to base39696ad, with the same four transition call sites and normalized arguments; no new direct association-to-NoEpisode loop was found. Added feature work is nonzero: selected capture/after-read/fold per save chunk, fresh changed-scope barriers even with no links, batched ownership reads and Entry fingerprint clearing. This source comparison neither quantifies overhead nor attributes the long runtime; an actual pure-baseline measurement has not been supplied.++At the historical pre-repair checkpoint, Transit accepted comment CAD170B5-6398-473B-82E2-05C64A7732E2 at11:37:47Z; T-2468 remains in progress. No Asterism heavy process or next heavy launch remains in this phase. The actual-release message to Meddy returned the same unconfirmed earlier-turn submission; delivery is not claimed and no retry was made. Next actions are a working host Mac XCTest automation environment followed by the three isolated journeys, and an isolated exact-base/current comparison of the original duplicate-settling path before any performance repair. No new product decision is pending.++Failed initial runs, reviewed corrections, exact inventories and private log/result names remain below. Baseline warnings are recorded with source/log provenance; no inherited warning was silently relabeled as a new failure or cleaned up to hide it.++The prior implementation remains on branch `specs/character-chapter-associations`, documentation checkpoint `4b92df05` and source phase1 commit `80e91630`. Its uncommitted source/tests and trial evidence are preserved in that isolated checkout and a private non-destructive snapshot. Nothing is reset, removed or merged into this branch.++This branch starts from `39696ad851823a235749313df92f096e68735629`, the liveV20 baseline. Unpublished five-tableV21 stores are preserved separately; opening them under a different V21 model or deleting them is not a migration strategy.+++## Continued independent diagnosis after the bounded scale timeout++Parent requested retained-evidence diagnosis before any new broad run. Three sampled stacks demonstrate execution of the actual duplicate observation/settling production path, not a harness discovery wait. Original test loop is finite (warm-up plus ten measured generations); no completed distribution appeared before the bound. Earlier NoEpisode-only controls changed two production files and cannot establish pure-base timings.++Exact base39696ad851823a235749313df92f096e68735629 is now materialized read-only from git archive into a separate diagnostic directory, with554 file hashes recorded in exact-baseline-materialization.json. No feature source was copied into it and no existing checkout was changed. The smallest runtime check is now complete: an external public-API executable depending only on that exact baseline package built Core-only debug in67.35s (jobs1;300s cap) and completed in1.30567s (90s cap). It executed12 calls (one warm-up plus three diagnostics at100/1000/5000 synthetic action rows), keeping one touched Work/fact unchanged. Every call returnedfalse, preserved exact row count and left no pending changes. Warm-up-excluded medians were3.438875ms/31.554584ms/152.917625ms,44.467× for50× more unrelated rows (and more unrelated Works). This demonstrates cardinality sensitivity in the baseline production writer independently of Swift Testing or association code. It is debug/in-memory/single-entity, with only three diagnostics per size: not a statistical band, Release M4 budget verdict, full baseline/current comparison or measurement of feature overhead. Plan/result/source hashes and raw events are noepisode-exact-base-public-probe-plan.json, noepisode-exact-base-public-probe-result.json, noepisode-public-build-1.log and noepisode-public-runtime-1.jsonl.++Independent source review confirms300 nonempty structural history reads in each successful observation pass and500 in each settling pass:8,800 over the finite11 generations. Reseeding removes Entry/Work rows while retaining NoEpisode history and uses fresh keys. The29750-row/261.8M decode-visit figures in scale-diagnosis-retained-and-plan.json are loose source-derived upper bounds under stated successful/no-mark assumptions, not measured counts or duration estimates. Global decode/sort is repeated per transition in exact-base code; original runner silence is insufficient progress reporting while this finite production work executes. New association work remains nonzero and its relative cost is unmeasured.++A result-driven phase-only follow-up reused the unchanged baseline Core product and preserved v1 source/results. It built in1.76s and completed in1.274026s, with12 invariant groups and36 timed phase observations passed. Post-warmup median milliseconds:++| Synthetic action rows | Fresh index fetch/group | One anchor Work history | Global allActions decode/sort |+| --- | ---: | ---: | ---: |+| 100 | 1.214958 | 0.024541 | 1.717291 |+| 1,000 | 11.847041 | 0.080417 | 17.950791 |+| 5,000 | 58.442667 | 0.086791 | 87.207083 |++Both global phases grow with unrelated history; caching decoding alone would leave repeated global fetch/group work. Transit accepted phase evidence comment 5F9041CE-155E-4AE3-94CB-AEB03651B443 at2026-10-18T11:56:39.907Z. The anchor Work remains one action. This remains a debug/in-memory component experiment with three diagnostics per size, not whole-operation percentages, a disk-cost result, a full M4 baseline/current comparison or a budget verdict. Evidence: noepisode-exact-base-phase-probe-plan.json, noepisode-exact-base-phase-probe-result.json, noepisode-phase-build-1.log and noepisode-phase-runtime-1.jsonl.++The next smallest repair candidate must avoid repeated global history work without weakening contradictory-copy checks, pending clear visibility, Work-history repointing, atomic saves or rollback. A transaction-local history view needs explicit invalidation/update for these mutations; a narrowed query may change validation scope. Add focused semantic counterexamples and review that choice before changing shipping code. No production optimization or gate waiver follows from this component probe alone. Transit accepted the continued-diagnosis comment F87AB918-F6B3-467E-A613-33BAD7C4A11B at11:52:34Z. Postchecks verify all554 baseline files and149 shipping compiler inputs unchanged; the Git index remains empty.++Mac read-only host logs at20:20:26.867 explicitly report that the automation writer requires authentication; at.871 testmanagerd evaluates LocalAuthentication policy2 with reason “Enable UI Automation,” caller XCTest. coreautha receives that UI request, and no completion appears before20:21:26.887 timeout. Runner process authorization and daemon connection had already succeeded. Evidence is mac1-review-automation-auth.log and mac1-review-diagnostics. The exact user action is to authenticate the XCTest “Enable UI Automation” system request during one coordinated retry; disabled DevToolsSecurity status alone was not causal proof and does not justify an automatic settings change. No prompt/settings/app launch/test retry occurred during diagnosis.++## Continued implementation checkpoint, 18 October++The exact56 checkpoint passed in separate Intelligence6 and Core50 runners. Expanded210 reached all declarations (Intelligence97 passed; Core113 ran with one fixture failing two ownership assertions). The fixture changed a parsed display title deliberately absent from the authored deletion fingerprint; changing genericNotes instead retained the stale-plan refusal assertions. Focused AssociationDuplicateTests4/4 then passed0.340s with no skips. Raw logs are association-integration-green-4.log and association-duplicate-fixture-1.log under /tmp/t2468-ledger-build. This supplies declaration pass evidence across runs, not a composed final-gate pass.++Native84 is prepared for the task-owned T2468 iPhone18Pro E34807DE-B459-4DD0-807D-6E63D9BFD60D with seeded temporary root and CloudKit disabled; it has NOT launched. New simulator coexistence coordination to Meddy01a14c78-ea72-7638-8423-fbb64448b010 returned an unconfirmed earlier-turn submission. Read-only reconciliation did not show delivery; one checked retry returned the same pending status. No further blind submission or simulator boot. Prior bounded host-only coexistence authorization remains distinct. Independent note/archive source work continues; no terminal resource-wait report.++Note API RED17 exited2 before runtime on concrete missing repository note APIs. Compiler stopped on the first note-test file; archive API absence was source-expected but not independently emitted, and no claim is made all17 bodies compiled. GREEN note/archive/publication source integration is in progress. All tasks/gates remain honestly open. No code commit, push, physical install or merge.++Meddy subsequently confirmed its complete23-case UI run passed and the process exited0, with no further heavy job queued. That trusted release resolves the native coexistence dependency; message-transport acknowledgements remain unconfirmed but do not block an otherwise fresh, healthy isolated-native admission. Finish the current coherent source unit, resnapshot compiler inputs and take a new resource boundary before launching.++Note/archive GREEN89 compiled and executed all selected declarations, with 13 issues recorded in association-note-archive-green-2.log; it is not a pass. Bounded fixture/import corrections and the independently reviewed missing-Work intent distinction are preserved in checkpointnoteGREEN43closure. The focused 43-declaration rerun started after the healthy 18:18:13 local resource check. Its initial sandbox attempt failed before compilation/tests (sandbox_apply denied); diagnostics are retained in association-note-archive-green-3-sandbox-denied.log. The approved escalated retry uses the exact same frozen compiler inputs and writes association-note-archive-green-3.log. Runtime results, native84 and all later composed gates remain pending.++That focused retry exited0: 43 declarations across three suites passed in 3.552s after a 30.97s build. Both bool arguments, four normalization modes and three missing-Work modes executed without skips; only existing FoundationModels warning locations appeared. Independent critic subsequently verified the implemented closure guard and controls with no actionable gap.++Native84 actually launched after the healthy 18:19:56 local boundary (71.95% CPU idle, 67% memory free, zero swap/pressure1). The dedicated simulator was confirmed Shutdown before launch; the UUID temporary fixture and unavailable extraction are selected before bootstrap. Private native84-1.log/xcresult and native84-current-compiler-hashes.json preserve evidence; source remains frozen while it runs. The expected set is ReviewModel43 plus Coordinator41, not merely a successful selector exit. Halo and Meddy have both completed; the parent requested no further messages to those completed threads. Local fresh resource checks continue.++Native84 exited0 with TEST SUCCEEDED. Swift Testing reported84 tests/two suites in0.115s; native result summary confirms84 passed,0 failed,0 skipped,0 expected failures on the dedicated simulator. Exact nodeIdentifier reconciliation against native84-current-test-names.json found no missing/unexpected IDs. Raw native84-1.log, native84-1.xcresult and extracted native84-1-tests.json remain private. Source freeze is released for publication/editor continuation; full composed commit gates remain owed.++Rune tasks3/4 subsequently completed after the worker reconciled mutation source coverage and these runtime checkpoints. Task5 is in progress. Publication/editor tests/mock-only checkpointpublicationEditorRED contains17 new declarations: Core publication2, native editor10 + raw context1 + Entry publication4. Both sequential Make RED runs exited2 before runtime, with primary absent chapterAssociations Core member and absent native editor/detached models respectively. The native compiler stopped in the first new file; no claim all15 native bodies typechecked. Logs association-publication-red-1.log and native-association-red-1.log/xcresult retained. GREEN integration now proceeds against independently reviewed drafts: staged Clear until Save, exposed current destination heads, protected initial load, independently readable raw context. No new owner decision or external-thread coordination is needed.++Publication/editor GREEN at checkpointpublicationEditorGREEN: repository2/1suite passed0.149s after40.23s build. Native174/12suites passed1.347s, exit0/TEST SUCCEEDED. Result bundle confirms174 passed/0 failed/0 skipped/0 expected failures; exact declaration ID reconciliation has no missing/unexpected IDs and all12 parameter Arguments nodes passed. All prior draft-review findings are independently confirmed resolved in integrated source. Existing warning locations remain; new editor/publication sources emitted none. Source freeze released for rendered synthetic fixture/journey TDD; composed gates remain owed.++Fixture GREEN2 passed2/2 in0.196s after155.12s build; its source-only release guard correction is queued. Dedicated task iPad created, not booted: T2468 iPad Pro11-inch(M5), E4BAD8EB-6530-4172-82B4-BA6D087A22C3, iOS27.0. Rendered isolation peer found no bounded blocker; three platform journeys and native launch15 remain unrun. A late native coverage review found an executable in-flight/manual-on-already-covered-source restart gap. Core integration is reopened for gated regression and the independently reviewed coverage-only invalidation correction in the existing event table, before held publication. Native/rendered execution pauses for this correctness slice; prior passes remain historical evidence, not final composed acceptance. No external completed threads are messaged.++Actual coverageRaceRED: exact frozen inputs, dedicated synthetic phone, fresh18:59:55 local healthy boundary. Make exited2/Xcode TEST FAILED after2 declarations/three argument executions in0.618s, with7 expected eligibility assertion issues. Both save orders fail current/reopened eligibility; manual-after-covered fails current/reopened and restart-empty eligibility. Setup/control assertions passed. Raw native-association-coverage-red-1.log/xcresult retained. Revised minimal pending-review-key/explicit-ack semantics are independently reviewed in design/decision log; GREEN is not yet implemented or run. Rune3 reopened/4 pending/7 paused. Transit comment2BCEA1CA-F57B-4B96-8781-2C96018D841A committed2026-10-18T08:05:12.927Z records this actual result. No physical installs or code commit/push/merge.++Pending-review GREEN source is wired but not yet compiled/run. Independent review found two bounded completion edges: duplicate B settlement during an awaited Keep and removed-alias routing before association validation. The agreed narrow correction records typed Keep/Skip outcome on captured acknowledgement events, compares exact original marker semantics and requires current whole-receipt support for duplicate Keep satisfaction; prior Skip and broader spelling/target evidence cannot close later pending review. Existing generic routing/refusal gates precede association acceptance validation, both before mutation. Source is being finished for one coherent focused checkpoint. Fresh19:23:38 local boundary showed82.76% CPU idle,69% memory free,zero swap/pressure1 and no compiler; no build admitted on unfinished source. Composed compatibility review proceeds independently. No further external completed-thread coordination is used.++checkpointcoverageGREEN is frozen; compiler hashes matched before admission. Core126 started after19:29:50 local boundary79.8%idle/69%free/zero swap/pressure1/no competitor. Selection: pending10, integration24, ledger24, storage6, existing assembler33 and extractionLedger29. Independent critic confirmed exact typed witness/known-target guard, endpoint context and pre-mutation refusal ordering clear. Runtime results and separately admitted native102 remain pending; raw association-pending-green-1.log and snapshot archive/hashes preserve provenance.++Core126 completed, exit2: build157.64s; Intelligence62/two suites passed0.010s; Core64/four suites executed4.922s with one fixture setup issue in differing-target witness mode2 (Expected explicit decision). All126 declarations and146 argument-expanded executions ran. Duplicate canonical Bryn names triggered normal routing refusal before that control reached its assertion. The remaining pending controls passed; this is not a phase pass. Bounded fixture correction will use a distinct canonical name plus weaker alias, preserving differing-target assertions; focused pending10 retry and native102 remain pending. Removed-alias reroute/no-write and contradictory known-target acknowledgement controls passed. Selected600 mutation diagnostic0.2019105s/1200events/2event+3endpointfetches remains supporting evidence, not the original M4 gate.++Fixture-only checkpointcoverageGREENfixture2 preserves the original assertion and uses Other with accepted alias Bryn as the distinct target. Focused pending10 retry exited0: all10 declarations/25 argument executions passed1.317s, no skips; association-pending-green-2.log. Native102 actually started after19:34:14 local80.82%idle/69%free/zero swap/pressure1 and no competitor, with matching frozen hashes and task phone confirmed Shutdown. Its selection is race3 + review43 + coordinator41 + launch15; expected108 argument-expanded executions. Public diagnostics-never retains native results/assertions while avoiding optional teardown diagnostics. Native outcome remains pending.++Native102 completed exit0/TEST SUCCEEDED:102 declarations/four suites passed0.661s. Native result confirms102pass/0fail/0skip/0expected; exact ID reconciliation102/102 with all9 Arguments nodesPassed (108 expanded executions), no missing/unexpected. This closes the reproduced pending-review slice; Rune3/4 completed and7 in progress,8/9 pending. Transit commentA9C943C4-4E2A-4585-ACA3-493FF024A585 committed08:38:32.147Z records the substantive result (its other115 count is an undercount; the non-pending portion of126 is116, with125 declarations passing in the original run and the remaining fixture corrected/passed in focused10). Phone rendered3 started after19:37:48 local69.27%idle/69%free/zero swap/pressure1, no competing compiler. All rendered/composed gates remain pending.++Rendered phone3 completed exit2 with2pass/1fail: raw/missing context19.499s and explicit recovery30.114s passed; Save/Cancel/Clear journey failed24.886s before opening its first note, because the existing button was not hittable after10 app.swipeUp attempts. Raw log, xcresult summary/tests and all exported attachments/recording retained. Existing UIJourneySupport289–305 documents the exact TextEditor gesture capture and uses a drag below the editor to scroll the outer Form; the new cross-platform helper is being corrected to reuse that mobile technique, retaining Mac behavior and every assertion. No product mutation indicated by current evidence. All composed gates remain owed.++## Current resumed status after coverage GREEN++This supersedes the historical pending/coordination states above. Native84 and native174 passed; fixture Core2 passed. The meaningful coverage race RED was corrected using minimal durable pending-review keys and captured explicit acknowledgements in the existing event table. Core126 executed:125 declarations passed, one different-target fixture legitimately rerouted because it accidentally seeded a second canonical Bryn. That test-only fixture now uses Other plus alias Bryn, and focused pending10 passed all25 expanded cases. Native102 then passed all102 declarations/108 expanded cases, with exact ID reconciliation and no failures/skips. Rune1–6 are completed again;7 is in progress,8/9 pending.++First phone3 rendered attempt passed malformed-context and recovery journeys; Save/Cancel/Clear/relaunch stopped before its first editor because app.swipeUp scrolled EntryDetail's nested TextEditor. The documented existing outer-Form drag is now reused in the mobile test helper; Mac branch and all assertions remain, with an added kept failure screenshot. CheckpointrenderedPhone2 is frozen for parent-run retry and subsequent iPad/Mac3. Product source is unchanged by this navigation correction. Broad Core/fast/signed Mac+test-quick, original32 dependent M4 declarations and affected original phone26/iPad2 rendered consumers remain owed. All private scripts and exact names are under /tmp/t2468-ledger-build. No code commit/push/merge, physical install, real library access or CloudKit deployment has occurred. Main owns fresh resource admission and actual execution; no worker-owned build is active.++Phone retry2 completed2pass/1fail: context19.328s, recovery31.184s passed; Save/Cancel40.263s failed at the same pre-edit reachability assertion. Explicit retained screenshot267F5263-101A-4481-A46D-A4E5F159182C.png shows both link rows fully visible after the corrected drag, no keyboard/overlay. Thus the Form scroll correction is insufficient; remaining hit-testing/query diagnosis is pending actual enabled/frame/accessibility-tree evidence. Preserve all assertions; no coordinate-tap bypass or further blind scroll loop. Next selection narrows to the single failing method for diagnostics. Relevant composed original budget selection adds the directly touched EmptyLibrary arm to the32 inventory (33 declarations); no fixture/sample/threshold changes.++Single-method phone diagnostic3 exited2,1fail39.221s. Retained target diagnostics prove a unique enabled button with visible frame(16,546.7,370,68.7), but only narrow left-aligned text children. No duplicate target or overlay was found. Existing TodayView1269–1276 and WorkDetailView419–422 expand custom row labels and give them a rectangular hit shape; the new association row lacks this pattern. The next bounded product correction reuses it, preserving semantic label, navigation and every assertion; no coordinate-tap bypass. Raw association-ui-phone-3-diagnostic.log/xcresult retained.++Hit-shape focused4 exited2,1fail41.218s with the same unique enabled visible target. No green claim; the change did not resolve the failure. Applied local systematic-debugger workflow: problem/expected and actual behavior recorded; line inspection found only hypotheses (DEBUG background marker, automatic custom Button style, new root sheet), not a proven cause. Controlled diagnostic5 launched after19:53:54 local61.53%idle/68%free/zero swap/pressure1/no competing compiler and matching frozen hashes. It compares existing same-Form controls and a normal button tap, retaining the original captured isHittable assertion; no coordinate bypass/product guess. Transit clarification6DFAC37F-A290-44FF-9524-42D78DF73958 committed08:52:38.179Z corrects original125/126 and116 non-pending counts, records current UI failure honestly.++Controlled5 completed expected diagnostic failure1/54.245s: fully visible existing Move/Delete and Alice all enabled but isHittable=false; ordinary target element tap opened the correct Chapter link note editor (editorOpened=true, fieldenabled/hittable=true). Original captured assertion remained failed, so this is not a green journey. This proves shared AX predicate/action mismatch and rules out a solely new-label issue. Root marker causality remains an assumption pending one-variable isolation. Proposed controlled change makes only the decorative Color.clear background inside columnMarker ignore hit testing, matching an existing WideRootView marker precedent, with original tests/assertions retained. No universal marker API, coordinate-tap bypass or button-style guess.++Marker experiment6 completed1fail54.367s with the same shared AX predicate mismatch and normal tap opening the editor. This falsifies the marker hypothesis; remove only the experiment line. The new helper imposed a stronger prerequisite than the existing repository element-tap pattern, despite direct evidence that ordinary activation succeeds. Correct that new oracle to existence/enabled plus native element activation, preserving every opening/loading, Save/Cancel/Clear, exacttext, relaunch and both-kind behavior assertion; no coordinates or per-ID exception. This is not a baseline assertion/threshold change or a green product claim. Focused complete-journey verification remains required.++Native-action7 reached editing/Cancel/Save/reopen, then failed1/43.097s at exact persisted text: actual was decomposed Café reader note followed by Saved arrival note. This demonstrates a new replacement-helper cursor assumption, not loss/normalization in storage: backward deletion at caret-start removed nothing and input prepended. Local ChapterNotes313/other helpers share the backspace assumption; no deterministic Select All helper exists to reuse. New suite needs native selection plus immediate exact draft assertion before Save, preserving downstream persistence assertions. Marker experiment diff is empty. Raw association-ui-phone-7-native-action.log/xcresult retained; no full journey pass.++Phone9-caret completed exit0/TEST SUCCEEDED: exact single complete editing journey passed111.550s, native ID1/1/no missing/unexpected/nonpassed/skips. Immediate exact UTF8 draft check, Cancel/no-write, staged Clear/Cancel, terminal Clear Save, persistent exact text after relaunch, both kinds and concurrent Place resolution all executed. Input driver reuses ChapterNotes309–315 caret placement for known one-line fixture strings; Mac Cmd+A unchanged. SelectAll checkpoint/script remains UNRUN. New3 iPad + two original wide journeys and Mac3 remain next; final phone29 combines new3+original26 on final source, followed by all composed Core/fast/signedMac/quick/originalM4 gates. No code commit/push/physical install/merge.++## Latest rendered boundary++Phone Save/Cancel/Clear/exact UTF8/relaunch/both-kind/conflict journey now passed111.550s, exact1/1/no skips. Input replacement uses established ChapterNotes deliberate caret placement with an immediate exact draft assertion; native navigation follows the reviewed wait-exists/enabled→normal element action pattern. Failed width/marker causal assumptions and controlled false-predicate diagnostics are preserved in implementation.md/logs; experimental marker source is fully reverted. Current compiler unit is checkpointrenderedPhoneCaret. Parent has launched combined iPad5 (new3+originalWide2) against that frozen source. Final combined phone29 (new3+original26), native Macnew3 with no-unrelated-dev-process check, unfiltered Core/fixed fast/signed Mac+full native quick, and original dependent M4 host33 remain owed. Rune7 stays in progress,8/9 pending; no implementation commit.++iPad5 completed exit2, exact5/5 expected IDs/no missing/unexpected/skips: raw context19.591s, recovery25.931s, original InspectorEdit16.698s and rating-only manual note29.676s passed. New editing journey failed29.655s at its compact-only openChapter expectation. Source confirms Today row opens inspector at wide width (AppScreens99), whose Edit action opens existing EntryDetail (WideRoot268); original WideLayout913–918 just passed this route. Correct only new helper to observe inspector/editor state, use normal Edit action, retain loaded work/editor assertions and rerun only that method. Mac may use the same observed wide route. No product fix indicated.+++iPad focused editing retry (`association-ui-ipad-2-route`) exited0/TEST SUCCEEDED: exact1/1 complete journey passed118.282s, no missing/unexpected/skipped cases. Across the initial five-case run and focused retry all five selected journeys have passed; this is not a single composed five-case verdict. Wide-route correction is test-only, preserving all behavior assertions.++Mac3 `association-ui-mac-1` compiled and signed the app, extension and native/UI bundles, then exited2 before any journey method: XCTest runner failed initialization with XCTFuture1000, “Timed out while enabling automation mode.” Result/log retained; zero journeys executed, no Mac UI green claim. Read-only escalated DevToolsSecurity status reports Developer mode disabled. Console diagnostic reports on-console true; login/lock fields absent, so no unlocked-session inference. No OS settings changed or blind retry. Required unfiltered Core composed gate started on frozen source after20:23:34 local boundary70.17%CPUidle/68%memoryfree/zero swap/pressure1/no compiler; private jobs2 cache, runtime outcome pending.+++Composed unfiltered Core1 completed EXIT2: build0.79s; ConstellationKit42decl/8suites passed0.046s, Presentation 304/20 passed0.094s, Intelligence 235/14 passed14.874s. Core reported3410 tests/322suites over182.180s and failed58 recorded issues (opt-in performance declarations remain skipped here and have a separate required gate); no compiler warnings emitted in this warm build. Exact failure inventory is private composed-core-1-failure-inventory.json; raw complete log retained. Source freeze released only for actual-failure closure. Known groups: stale live marker/schema20 expectations and migration inventory that accidentally replaced frozen20 instead of adding21; current-format diagnostic expectations; current-state roundtrip consumers using an old exporter after newly persisted barriers; coverage fixtures that mistake legacy facts coverage for the new association completeness basis; sanctioned source-reach inventories and exact event counts. No wholesale historical codec replacement or assertion suppression is authorized. Original semantics remain tested, with explicit feature re-review where Req3.1 requires it.++Final independent bounded source reviews found no additional concrete production blocker in mutation/barrier/whole receipt/note/import/pending paths or schema/archive closure. They explicitly do not clear the actual failed composed gate or zero-case Mac UI. Required full native quick still includes all affected integration/settings/export/EmptyLibrary/diagnostics/background/launch consumers. Generic code-commit readiness remains false. Reusable asynchronous coverage knowledge was captured separately in the configured vault, outside Git.+++The independently reviewed failure closure is frozen as checkpointcomposedClosure306. Its exact 21-suite focused Make selection exited 0: 306 declarations passed in 27.988 seconds after a 108.50-second build, with no skipped tests or issues. Nine macro-warning source locations were verified present in the earlier pending GREEN log; no new warning location was introduced. The clipboard operation now uses the existing RuntimePlatform seam, with no platform-test allowlist expansion. Current-format roundtrips preserve full restore assertions and add exact raw feature arrays; predecessor-format controls remain unchanged. Fact coverage assertions remain explicit and separate from association eligibility. The deletion test expects exactly one scope barrier.++Unfiltered Core retry started on the same frozen source after the 20:35:33 local boundary (71.28% CPU idle, 64% memory free, zero swap, pressure 1, no competing compiler). Fresh composed-core-2.log and composed-core-2.xml preserve output; the required default selection is unchanged. Runtime outcome pending. Mac reconciliation confirms all three requested journey IDs missing, with only the unexpected runner-startup failure in the result; no behavior pass or permission workaround.++Focused declaration/suite multiset reconciliation is complete: expected = started = passed = 306; expected/actual suites = 21; missing, unexpected, unpassed and missing/unexpected suites are all empty. Private composed-closure306-reconciliation.json and its reproducible script retain the check. Parameter-case starts were excluded from declaration counts.+++Unfiltered Core2 exited 0: Core reported 3,410 tests across 322 suites, passing in 183.484 seconds. ConstellationKit 42/8, Presentation 304/20 and Intelligence 235/14 also passed. (Earlier progress shorthand mislabeled the last two supporting modules; the counts and outcomes were correct, and the source/log module labels are corrected here.) Exact all-target source/log reconciliation: 3,991 source declarations = 3,936 started and passed + 55 explicit opt-in performance skips; 364 source suites = 353 started + 11 skipped, including two unnamed suites. Missing/unexpected/unpassed titles and suites are all empty. Private composed-core2-reconciliation.json and reconcile-full-core.py retain the check. Build 0.56 seconds, no compiler warnings. The accepted --xunit-output flag produced no XML; raw-log/source reconciliation is the evidence, and no run was repeated only for reporting.++Fixed fast gate exited 0: the unchanged manifest verified all 456 identifiers. Presentation 304/20 passed in 0.099 seconds and Core 152/12 in 0.484 seconds. Full native test-quick then started on frozen source after the 20:39:58 local boundary (68% CPU idle, 65% memory free, zero swap, pressure 1, no compiler). Its signed Mac app/embedded-extension prerequisite is retained; UUID-isolated synthetic phone configuration/private outputs are unchanged. Native result remains pending.+++Full native quick1 completed with EXIT2/TEST FAILED. Its signed Development Mac app and embedded-extension compile prerequisite passed; native units reported 1,784 declarations / 128 suites in 35.480 seconds. Native result confirms 1,782 passed, two failed, zero skipped/expected failures. The two actual failures are IntegrationSafetyNetTests.completeRealRecordBackup and backupV3FillEmpty: feature-bearing roundtrips still call the legacy exporter and are correctly refused. The worker owns bounded consumer corrections preserving all real-record, readiness and released-format assertions; no ledger change is indicated. Source freeze is released for those native fixtures only. Core/fast production and package inputs remain unchanged, so their passed gates are not repeated solely for a native-test correction.++Initial full native source inventory also misassigned two AppNavigationTests extension methods to AppNavigationTodayTests; runtime IDs expose the inventory parser mistake. All 1,784 declarations are present. Initial reconciliation and source inventory are preserved, with a source-backed ownership correction required before the next native comparison. There are 120 argument nodes. The 17 unique Swift warning entries match prior native logs and exact unchanged baseline expressions; native-quick-warning-provenance.json records each check. Failed logs and native result remain retained.++A newly active Meddy validation uses separate outputs and phone/Watch IDs. Brief overlapping startup CPU saturation was reported to its active thread; memory remained 62% free, zero swap, pressure 1. Asterism's actual native exit was reported. No completed older threads were contacted, no other process was interrupted, and no additional Asterism heavy job runs during fixture correction.+++Frozen checkpointnativeCurrentClosure17 corrects only the two actual current-format IntegrationSafetyNet roundtrips. Independent review confirms whole-payload equality now includes raw feature arrays, every real-record/relationship/Unicode assertion remains, and the fill test retains generic import, exact record counts, extension reopen and note/ownership/readiness checks. Historical exporter controls remain untouched. The focused whole suite exited 0: 17 declarations in one suite passed in 3.333 seconds; native identifier reconciliation is exact with no missing/unexpected/nonpassed/skipped tests. AppNavigation source ownership correction is grounded in the explicit AppNavigationTests extensions at lines 1646/1663; no product or test method was moved.++The full native quick2 retry started with its signed Mac prerequisite retained. Fresh 20:48:02 local boundary: 19.44% CPU idle, 53% memory free, zero swap, pressure 1 and no Swift frontend; a separately owned Meddy correctness suite was active. This is warm-cache correctness validation, not a quiet-host performance measurement. Its new log/result and UUID fixture preserve provenance. No concurrent Asterism job is active; Core and fast inputs remain unchanged.+++Full native quick2 exited 0/TEST SUCCEEDED: all 1,784 declarations across 128 suites passed in 38.396 seconds. Native summary confirms 1,784 passed, zero failed/skipped/expected failures. Exact identifier comparison against the corrected source ownership inventory has no missing/unexpected/nonpassed tests, and all 120 Arguments nodes passed. Signed Mac app/embedded-extension compile passed again. Private result, summary, test tree and reconciliation retain the evidence. The two stale current-export fixtures are closed; no package or production source changed after their earlier passed gates.++Phone29 began on the same frozen source after the 20:50:26 local boundary: 56.74% CPU idle, 49% memory free, zero swap, pressure 1, no compiler. Dedicated phone E34807DE was available/Shutdown and cold-booted only for this task. The separately owned Meddy UI run uses a different device; actual start was reported to its active thread. The original 33-declaration M4 selection has been source-audited (15 Scale + 10 Tolerated + 7 Duplicate + 1 Empty Library), with all four original suite files unchanged against the base. No performance sample, threshold or fixture was altered, and no M4 run has started.+++A late exact source-ownership audit caught an error in the phone inventory and admission shorthand: CharacterExtractionUITests.swift declares CharacterExtractionOutcomeUITests separately at line 813. Its testAPassThatFoundNothingSaysSo and testTheManualTriggerIsAbsentWhileTheModelIsAway were wrongly inventoried under CharacterExtractionUITests and therefore are not selected by the active whole-class command. The active run covers 27 of the intended 29 journeys. Its initial expected inventory is preserved; corrected source-owned IDs and a focused two-test follow-up are required. No product/test source change or scope reduction; no combined-29 green claim. Completed unchanged journeys will not be repeated solely to correct the selector. The targeted acceptance evidence will reconcile all 29 across source-qualified runs.++The newly active Meddy owner has now confirmed its full gate exited, all owned devices are Shutdown and no further compile/runtime is planned. Asterism's run continues untouched; no further message to that completed thread is needed. M4 remains a separate admission after Asterism rendered work exits.+++Phone rendered acceptance is now complete for the intended affected selection. Active27 exited 0/TEST SUCCEEDED: 27 passed, zero failures/skips/expected failures, exact expected IDs; runtime 1,668.793 seconds. Separate Outcome2 exited 0: empty-result messaging passed in 32.933 seconds and unavailable-model manual-trigger absence passed in 30.679 seconds. The combined, explicitly source-qualified test tree reconciles all 29 intended IDs with no missing/unexpected/nonpassed tests. This is 27+2 across runs, not an initial combined-29 pass. No source changed between runs; both task-owned phone/iPad were verified Shutdown afterward.++The required original M4 release gate was admitted once after the 21:23:57 local actual boundary: 60.39% CPU idle, 61% memory free, zero current swap rates, pressure 1, no Swift frontend; separately owned Meddy xcodebuild 34044 was idle at 0% CPU. Allocated swap remained 766.88 MiB and is not described as zero. Default median assertions and p95 reporting are retained (CONTROLLED remains empty per Make policy); this is not a controlled-p95 quiet-host claim. Exact 33 original source declarations, sample counts, budgets and ceilings remain unchanged. Private composed-m4-1.log/measurements retain the actual run; runtime outcome pending. No simulator or physical device is used by this host-only gate.++Two authorized resource-notification attempts to the reopened Meddy thread returned “An earlier turn submission is not yet confirmed,” including a fresh request after learning its durable host identity. The read-only receipt check did not establish delivery; no identical notification was blindly retried and no delivery is claimed. Minimal diagnostics are private meddy-rebase-coordination-unconfirmed.json. Local process/pressure checks continued, and the other owner supplied fresh actual job starts independently.+++The one owner-authorized Mac retry exited2/TEST FAILED. Exact native reconciliation: expected3/actual3, passed2/failed1/skipped0, no missing/unexpected IDs. Recovery and malformed/missing endpoint context passed; save/cancel/staged Clear/relaunch failed before reaching its editor assertions because Inspector Edit did not expose entry-detail-work-title. Raw log, result, summary, test tree, failed attachments and mac-2-authretry-reconciliation.json are retained privately. The read-only auth observer showed automation enabled; no permission prompt was accepted or OS setting changed. Further source diagnosis proceeds independently, with no blind Mac retry.++The focused NoEpisode history-session RED exited2 at compilation on the expected missing HistorySession API; zero tests ran, and no claim is made that all test bodies typechecked. Ten declarations/twelve parameter cases were inventoried before RED; a meaningful real reconciler failed-save/rollback/refault/replay regression is being added before GREEN. Independent critic cleared the private implementation boundaries, including deferred raw Work repoint validation and fresh per-replay sessions. No original performance budget, fixture or sample count changed.+++The reviewed narrow history-session GREEN passed the exact 138-declaration focused Make cohort: build38.62s, runtime4.094s, all9 source suites matched, no missing/unexpected/unpassed declarations or skips. This includes11 new declarations/13 parameter cases and actual deletion-chunk save failure→rollback/refault→fresh replay, with exact persisted-clear counts and no subsequent row growth. Both production file hashes match the independently reviewed private drafts. One newly introduced unnecessary-try warning in the new replay assertion was removed afterward without changing its expectation; its focused11 verification is pending. Existing warning provenance remains separate. Original M4 tests/fixtures/sample counts/budgets were not changed; bounded single-generation comparison precedes any broad rerun.++Warning-only cleanup verification exited0:11 declarations/one suite passed0.121s after17.17s build, no compiler warnings/skips. Shipping repair is unchanged from the reviewed138 pass. Transit committed the substantive Mac+history status as comment2D1E29A8-4E5A-4D97-B533-651577F2AAC2 at2026-10-18T12:15:33.172Z. A read-only peer confirmed the bounded single-generation diagnostic matches original public seed/open semantics and same-repository settling state; extra untimed count reads warm caches, so no N10/budget/sole-cause claim. Baseline arm started after23:15:58 local boundary86.56%idle/65%free/current swaprates0/pressure1/no compiler.++The exact-baseline initial fixture has now been counted at10,000 NoEpisodeAction rows,6,000 Entries and1,100 Works before observation. Setup completed17.900s but emitted retained external-data clone diagnostics, so it is not described as clean. A one-second owned baseline observation sample independently reaches DuplicateReconciler→NoEpisodeWriter.recordNoteTransition→NoEpisodeIndex.allActions/history→NoEpisodeHistory.Action.decode. This proves the repeated global-history path exists at exact39696ad; it does not measure feature-only overhead or establish a budget verdict. A focused Mac rendered-diagnostic permission question is pending; the completed one-retry authorization is not reused. No physical phone or install work is owned by this task.+++Bounded actual original-generation comparison is complete. Baseline build 58.24s/setup 17.900s; observation reached declared 120s alarm without completing, settling not reached. Current build 75.95s/setup 14.425s; observation3.434260166s (0collapse/300settling sets/250moves), settling6.599527125s (300collapse). Counts:10000actions/6000Entries/1100Works before,12250/6000/1100 after observation,12250/5750/1050 after settling. Binary SHA and resolved filesystem dependency retained for each successful build; both drivers identical, all554 baseline files and898 current compiler inputs unchanged. Both setup raw logs retain external-data clone errors; counts/duplicate correctness succeeded in current but these diagnostics are not suppressed. Extra untimed count reads warm caches. This is one initial debug generation, not N10 accumulation, Release budgets, full M4 green, a completed baseline elapsed ratio or feature-only attribution.++Current-source unfiltered Core3 started after23:22:08 local boundary72.82%idle/64%free/pressure1/current swaprates0. One separately owned Personal phone compiler was active with separate output/cache; no conflict with this host package correctness run. Product source remains frozen. Original performance gates and Mac route remain open; focused Mac diagnostic permission is pending.+++Current-source unfiltered Core3 exited0: Core 3421 declarations/323 suites184.982s; Constellation 42/8 0.048s, Presentation 304/20 0.096s, Intelligence 235/14 14.599s. Exact all-target source/log reconciliation: 4002 expected = 3947 started/passed + 55 explicit opt-in performance skips; 365 suites=354 started + 11 skipped. Missing/unexpected/unpassed declarations and suites all empty. Warm build 0.69s, no compiler warning lines. Raw output and composed-core3-history-reconciliation.json retained. The unchanged fixed-fast cohort starts next after 23:26:31 boundary 87.22%idle/65%free/pressure1/current swaprates0/no other compiler; private outputs, no device.++The unchanged fixed fast cohort exited 0: its manifest verified all 456 identifiers; Presentation 304/20 passed in 0.096s and Core 152/12 in 0.472s. Full native quick3 started after the 23:27:00 local boundary (76.38% CPU idle, 64% memory free, pressure 1, zero current swap rates). Both owned phone/iPad were Shutdown before launch; only the phone is selected. It uses a fresh synthetic run UUID, unavailable extraction before bootstrap, private outputs and the signed Mac compile prerequisite. This gate does not execute the paused Mac rendered diagnostic or use a physical phone.+++Current-source full native quick3 exited 0/TEST SUCCEEDED. Signed Development Mac app and embedded extension compiled successfully; native Swift Testing reported 1,784 declarations/128 suites in 31.881s. Native result summary confirms 1,784 passed, zero failed/skipped/expected failures, on exact task phone E34807DE. Exact ID reconciliation and all 120 Arguments nodes pass with no missing/unexpected/nonpassed IDs. Seven emitted Swift warning locations are exact unchanged baseline file expressions and occur in earlier retained logs; quick2 was warm and therefore did not emit them, so provenance uses whole-file exact-base checks plus earlier native/Core logs. No new warning expression. Both owned simulators are verified Shutdown; shutdown request found the phone already Shutdown and changed no other device.++The original33 Release wrapper was reviewed before launch. A real cleanup hole under repeated process-enumeration failure/signal-exit race was corrected in the private wrapper, not product/tests: all monitor/grace/final checks now use guarded ownership proof; uncertainty yields nonzero and preserves diagnostics; ProcessLookupError means already gone. Root verified the changes; independent rereview is pending. Original target/filter/Release flags/samples/budgets and median policy remain unchanged. Fresh 23:30:28 local boundary:76.75% idle/65% free/pressure1/current swaprates0; separate Meddy xcode was1.3% CPU, no Swift compiler, private outputs. No resource conflict or controlled-p95 claim.+++Original33 Release run2 was stopped during compilation after actual ownership evidence disproved the wrapper’s same-process-group assumption. Make58195/SwiftPM58201 used PGID58195, but compiler59221 and plugin59226 used PGID59221 within the same fresh session58195. No tests, distributions or budget assertions executed. Root first sent INT only to identity-verified SwiftPM58201; Make exited2 after320.656s, while the separately grouped compiler remained orphaned. Root verified its private Release command, PGID and original SID58195, interrupted only that group, and a complete read-only SID scan confirmed zero remaining members. Original log/wrapper/stop/drain evidence and partial cache are retained. This is an orchestration interruption, not a performance failure. A corrected guard will track all owned session/descendant groups and prove cleanup with a small harmless nested-process fixture before a new bounded run; source/tests/samples/budgets remain unchanged.++The active Meddy owner requested a concrete start/end notice. The fresh actual start message returned “An earlier turn submission is not yet confirmed”; a newest-turn read did not show the exact notice, so delivery is not claimed and no blind retry was made. Local fresh pressure checks supported coexistence; no other task process or simulator was signaled. Private meddy-m4-2-coordination-unconfirmed.json records this transport uncertainty. Mac diagnostic authorization remains pending.+++Corrected run3 ownership fixture passed in3.5376s without any Swift/app build: it retained a nested-PGID orphan through the fresh root SID and a child-created SID through observed ancestry, stopped only those two verified groups, proved the original SID empty, and left an unrelated fresh control alive. Independent critic cleared the matching-hash wrapper. The default-sandbox attempt is retained as failed infrastructure proof; its initial PID receipts were missing, so exact old-PID drain is not claimed, while its self-limited sleepers have expired. The corrected attempt records launch identities immediately and all child sleeps are≤10s under a15s overall fixture fuse.++Original33 Release run3 started at2026-10-18T12:43:34.696Z, owned Make/fresh root session60300. Wrapper SHA adf394d32492452a1abc253d2eb5ed19268e205b864f38fefa016ca0c8e19d0b; source compiler inputs898 match the verified host snapshot. Fresh23:43:13 boundary54.13%idle/58%free/pressure1/current swaprates0, no destination conflict with the separately active Meddy UI. The existing source, target/filter, Release flags, original N10/N20 samples, medians/ceilings and900/600/1800-second bounds are unchanged. Guard now follows verified descendants across process groups/sessions. No runtime verdict yet.+++The owner-authorized continuation superseded the earlier pending diagnostic questions. The import repair now creates one lazy NoEpisode history session inside each existing Entry save chunk; the default 500-record boundary, upfront imported-history validation, later record phases and persistence semantics remain unchanged. The seam-only runtime RED ran six declarations and failed ten count assertions while semantic checks passed; GREEN passed all six. The broader eight-suite cohort passed 80 declarations / 84 expanded executions with no missing, unexpected, skipped or unpassed cases and no compiler warnings. Private logs, exact source manifests and reconciliation are retained.++Mac diagnostics separately established that the text field can accept input despite reporting AXDisabled. Keyboard-typed NFD arrived as NFC before saving, so that diagnostic did not prove storage normalization. The subsequent ASCII diagnostic passed editing, Save enablement, Cancel and exact original-byte reopening. The value-traced route reached the editor with no selected-ID clear or binding-set event, but instrumentation can perturb SwiftUI timing; no navigation fix is established. All failed and successful runs are retained. Reviewed temporary-diagnostic cleanup and a permanent readiness/input oracle with a separate repository-seeded exact-NFD save/reopen/readback control are the next focused changes; no speculative navigation change has been selected.++The public A/B/C Debug diagnostic has completed and all owned processes have exited. Identical synthetic v19 archive, normal public importer and full saved-data checks: pure baseline A confirmation 30.233337750s; matched baseline-plus-common-repairs control B 0.717099666s; current C 0.740946875s. Each validated 600 Entries, 120 Works, 1,800 physical actions, exact 1,200 imported payloads, 600 new visit clears and inactive imported marks. Current 216 Core inputs and all 554 exact-baseline inputs remained unchanged. This isolates the large repeated-history import cost as common baseline behavior, while the small C/B difference has no established statistical significance. The archive contains no dense association inventory.++The same original initial-generation duplicate diagnostic measured B observation 2.837791709s / settling 4.841581375s and C observation 3.276672417s / settling 7.965175667s. Both produced the exact expected 300 collapses, 250 moved Entries and action/Entry/Work counts. The conditional current increment is 0.438880708s observation and 3.123594292s settling; its mechanism remains unassigned. B preserves original baseline chunk guards/order and is a counterfactual containing the common NoEpisode repairs, not pure baseline. B/C also differ in the feature’s pre-existing convergence partitioning. These single Debug observations do not satisfy or replace original Release distributions, samples, two-second limits or the incomplete/failed full gate. Evidence: /tmp/t2468-ledger-build/import-public-comparison/ABC-comparison-result.json.++Automatic approval review initially denied B N1 before execution, alleging a 600-second wrapper against the admitted 240 seconds. Inspection proved the actual retained execute.py cap was 240 seconds. The exact same action was retried once with that source evidence, approved and completed; the original denial and successful receipt remain retained. No approval blocker remains from this mismatch.++Transit confirmed the comparison progress comment DB12892E-AAC6-4929-8DDC-24258C1A6C11 at 2026-10-18T14:12:05.628Z. The first sandbox-localhost attempt failed before connection; the same idempotency-key request succeeded after the allowed network escalation. No uncertain duplicate write. Exact temporary Mac diagnostic cleanup completed with all before/after hashes verified, followed only by the seven-file reviewed oracle/NFD patch. AppNavigation and WideRootView match their pre-diagnostic hashes; no navigation candidate applied.++The permanent oracle fixture Core selection completed non-green: four declarations / five expanded cases, four cases passed and the new archive control failed because synthetic Entry ...003 had an absent chapter with non-none provenance under prospective import validation. Build 29.95s / suite 0.449s / guarded command 35.839s; all seven input hashes unchanged, no owned processes remain. The exact failed result is retained and strict validation/Unicode assertions are preserved while correcting fixture validity. Two emitted Intelligence sampling-initializer deprecations are in unchanged files (FoundationCharacterExtractionModelClient:35 and FoundationRuleSuggestionModelClient:40), not new warning expressions. Native/Mac follow-ups have not started.++Source diagnosis corrected the initial fixture hypothesis: authorTarget creates a valid authored chapter without writing a legacy raw chapter title. The shared archive mapper incorrectly combined effective snapshot.chapterTitle with raw legacy provenance, also producing the symmetric loss when an authored note hides a raw chapter title. No date sanitization caused this. Independent critic cleared the one-line raw value/citation row correction plus both authored-target directions, split-carrier tuple and full V20 exact-NFD roundtrip regressions. Public snapshots/display, authored-target bytes, sequence and strict validators are unchanged; focused RED then GREEN precedes native/Mac controls.++The optional retained C store inspection used SQLite mode=ro/query_only metadata counts only; DB and WAL hashes were unchanged. It confirmed 5,750 Entries / 1,050 Works / 12,250 NoEpisodeActions / 750 entry-scoped invalidation events / zero PairNoteVersions, with no validation blobs. The required invalidation work is real even without accepted pairs. Its timing is not established. The reviewed retained-binary sample is excluded from budgets and current-source timing; its immutable compiled snapshot predates the oracle/export correction.++The corrected, independently reviewed raw/effective export repair is GREEN: 14 declarations / 17 expanded cases / two suites passed in 1.027s (11.53s build, 17.519s guarded total), no warnings/skips/missing cases and no owned processes left. Both valid authored target directions, split carrier raw/citation pairing, full exact-NFD archive/import/readback and all original predecessor/refusal controls pass. The initial test-only split-row alias setup error was corrected separately and its failed RED retained; clean RED2 reproduced six actual mapper issues before the production fix. Final mapper SHA b405138fc37a74c4a3118c6cb750b7fc75b545fdb43e54071cfafaa35cd3a3ea; exact reconciliation is private raw-chapter-export-green-reconciliation.json. Current production/native inputs are now frozen for the next whole editor native suite (10 declarations / 13 expanded cases) and two uninstrumented Mac UI controls.++Current native editor state verification passed all ten declarations / thirteen cases in 0.075s, exact expected IDs and five parameter argument nodes, zero skips/failures and unchanged 898 recorded Swift/project inputs. Xcode exited0/TEST SUCCEEDED. The reviewed guard returned124 solely because a proven task-owned orphan ibtoold remained after Xcode; it sent SIGINT only to that verified helper group and final ownership scan was empty/uncertainfalse. Native test and infrastructure outcomes are retained distinctly; no unchanged suite rerun. Both task simulators were already Shutdown when checked. The two uninstrumented Mac controls are now running on that frozen source, without the navigation candidate.++The return-only candidate native plan initially counted ninety file-level test declarations as one suite. Actual source ownership is62 AppNavigationTests (including extensions) plus28 AppNavigationTodayTests. The62 selected cases passed first; the remaining28 were then selected separately without repeating62. Combined exact-source ownership reconciliation has no missing/unexpected/nonpassed IDs, and all898 recorded inputs stayed unchanged. Both Xcode exits0/TEST SUCCEEDED; both post-Xcode guard exits124 followed proven owned ibtoold cleanup, with no remaining/uncertain processes. The original overbroad inventory is retained rather than relabeled. Whole Mac5 started afterward on the same frozen source, no other heavy compiler at admission and59%memory free.++Mac5 completed non-green: all original three journeys plus the new exact-NFD journey passed, but the additional navigation regression failed at the final Work→Back→Inspector Edit boundary. It successfully rendered Entry1→Back→Entry2→Back, rendered the focused Work, backed to the dashboard and passed absent-Work/day assertions; the final Entry title never appeared (line64). Guard exit2/283.065s, reasonnull/uncertainfalse, no owned processes remain. No navigation acceptance claim. Both prior clean control failures and this candidate result stay retained. Existing iPad2 runs independently on the same frozen source while a scoped state trace is prepared privately; no delays, selection rewrites, broad routing redesign or weakened assertion selected.++Transit confirmed progress comment AF34A7E4-0B7C-44CB-98AB-6618B9FF4108 at2026-10-18T14:36:57.742Z. Later iPad2 finished InspectorEditpass18.567s / WorkBackfail24.417s at the new scroll Y assertion (560.5 versus1033.5±2). Source review found initial Y measured after inspector opening/narrow-pane layout versus full-width return; this cannot isolate scroll preservation. A same-geometry pre-tap fixed-row/list/window oracle is privately reviewed, with original-policy control planned and tolerance unchanged. The minimal Mac state diagnostic was admitted/applied only after all candidate runs drained: DEBUG validated-synthetic categorized events, selected/path didSet and existing revision markers, no binding/lifecycle replacement or state writes. It runs the same exact failing navigation test once; instrumented success would be timing-sensitive evidence, not a fix. Exact reverse cleanup/hash recipe is retained privately. NoEpisode buckets remain private/unapplied.++The minimal Mac state trace failed the same final reopen after152.317s guarded total, exit2/drained. Its38fixed synthetic events show WorkBack path1→0 and revision2→3, then about11s later showTodayEntry selected the first UUID and returned with it;150ms later selected-ID changed to nil and revision3→4 followed. That rules out a skipped explicit Edit selection/immediate return reset but not the caller: several app-owned clears were unmarked. All four temporary trace files were exactly restored. The reviewed residual trace now marks all eight direct app assignments without a Binding/lifecycle/state change and runs the same assertion once. The strict same-geometry iPad control was run under original and candidate policies with only policy source differing: both failed560.5versus584.5±2 after matching list/window frames. Baseline28.167s /candidate28.442s, nativeMake2; guards124onlyafterdrainingownedpost-Xcodehelpers, no uncertainty/remnants. This establishes existing24pt drift, not candidate-only behavior or its coordinate cause. No magic subtraction/tolerance change.++Residual all-writer diagnostic completed60.243s/nativeMake0/guard0,76.156s total, no uncertainty/remnants. Its41fixed events retain final selected first UUID/revision3; no failing nil transition occurred, so no caller attribution/fix claim. Initial summary was empty because the local Python fromisoformat parser rejected +1100 timestamps; strptime reconciled all41raw events without rerunning. Raw files are retained. Exact four-file TEMP cleanup restored candidate/source hashes and corrected iPad oracle, diffcheckclean. The next classifier is privately reviewed and only observes after nonnil→nil, emitting bounded fixed caller categories; no live UI code applied. The independently reviewed lazy NoEpisode raw-row buckets are now admitted to source/test TDD while UI work remains private, avoiding another idle core phase.+++Transit confirmed the failed mutation trial/rejection/restoration update as commentA504DEA2-E5D3-49E6-BB61-56BAFE66D9B2 at2026-10-18T17:29:20.481Z. The restored900 final Core gate uses the explicit new composed-gates-restored900-v3 pack and reviewed prepared-artifacts-v2 manifest2eb6bea785064372cb41a8331a97a6892927a641debb63361c4c31242fdf5195. Prelaunch review corrected only private case-title parsing and historical-source comparison; original preparation receipts remain preserved. No test/assertion/source changed. Current4017 declarations/367 suites/233 parameterized attributes, exact55 existing performance test skips plus11 suite skips, and actual argument-start/terminal reconciliation are separate obligations. Unchanged-source historical argument counts apply only to88 whole-file-hash-proven rows;77 source-resolved counts and156 complex expressions are explicitly distinguished. No overall feature acceptance or automatic next gate follows.+++## Final composed checkpoint, 2026-10-18++The selected source is restored900. Final Core root review is `composed-gates-restored900-v3/core-root-review.json`: 4,017 declarations accounted for, 3,962 passes, 55 exact existing test skips and 11 exact suite skips; 2,573 logical argument executions across 231 executed parameterized declarations yield 6,304 expanded executions. Natural exit0, source checks and drain passed. Reporting corrections read the same preserved raw log; no test was rerun or assertion changed. All20 warning origins are baseline-qualified. Complex argument source expressions remain explicitly distinguished from independently resolved values.++Fixed-fast root review is `fast456/fast-root-review.json`: exact456 identifiers/32 suites and552 expanded executions, including113 argument values matching the accepted same-source Core run. No warnings, skips or issues; natural exit0/drained/source900 unchanged.++Native root review is `native-execution-v1/native-root-review.json`: signed Mac app plus embedded extension present; exact1,791 declarations/40 parameterized declarations/120 passed Argument nodes, 1,871 expanded cases, no failures/skips/expected failures or runtime warnings. NativeMake0 and wrapper124 remain separate; root accepted only the birth/ancestry-verified post-Xcode ibtoold cleanup, with no tracking errors/remaining identities/uncertainty. All three tool messages match prior raw messages. One dictionary argument-display key ordering difference is semantically identical to all three current source dictionaries, independently checked; the original receipt remains unchanged. Exact launch-UUID temporary-store files are retained and the dedicated simulator is Shutdown.++These results close final composed correctness on the selected source. They do not clear the original Release budgets/full33, the inherited iPad restoration issue, or full pre-push UI acceptance. No additional optimization or run is admitted. The next technical step is a reviewed attribution plan for the remaining observation/settling cost on restored900; the parent has now decided that inherited iPad restoration stays separate, with assertions unchanged. Any future product trade-off must instead be grounded in measured performance costs.+++Transit confirmed this final correctness checkpoint and remaining blockers as comment48801ADB-60F6-43C5-8EE6-28C997A68B23 at2026-10-18T17:49:10.269Z. All heavy work is drained, the owned simulator is Shutdown, source900 is verified and the index remains empty. This is a preserved uncommitted checkpoint, not overall feature acceptance.+++## Approved measured-attribution continuation++The parent confirmed that the inherited iPad scroll defect remains separate from T-2468, with no weakened assertion or feature-scope expansion. Continue toward feature readiness through measured performance attribution. Before any broad run, compare unchanged baseline with the selected feature for observation/settling, identify the added persistence cost, and select the smallest semantics-preserving fix. If the existing budgets cannot be met safely, report measured costs and a concrete minimal product trade-off rather than merely deferring attribution. The final168-file checkpoint/archive remains preserved; no merge or install is authorized.++Read-only provenance audit confirms exact baseline39696ad554 retained files unchanged and retained current Release binary/Core216 inputs exactly match selected900. Previous B is a repaired counterfactual, not unchanged baseline. Exact A has only a Debug observation120s cap, with settling unreached; it cannot substitute for a matched Release result. A private matched Release plan will build only A and reuse the retained feature binary with identical driver/count-warming semantics, after verifier review and separate stage admission. Current once-per-save-chunk capture is confirmed; no speculative per-set capture repair is selected.+++Matched unprofiled Release comparison completed: exact unchanged A observation96.163457s/settling170.459822s versus selected C observation2.932167s/settling5.230809s. Both exact fixture oracles, source/binary integrity and natural clean drains passed. This single-generation diagnostic includes common history repair and does not isolate association cost or close original N10 budgets. C postshutdown private metadata oracle confirms750 unique Entry invalidation scopes×1, zero acceptance/pair-note/malformed/validation-blob rows; DB/WAL hashes unchanged. See performance-attribution.md. Transit confirmed comment6DD7E714-AA52-4400-9E09-CC31B6A39F81 at2026-10-18T18:10:51.128Z, correcting old iPad-pending status to parent-decided separate scope. Private coarse instrumentation preparation continues; shipping900 unchanged.+++## Completed measured attribution, 2026-10-18++The matched comparison and timing-only private C attribution are complete. All source inputs, semantic checks and read-only saved-association checks passed; all jobs drained naturally. Endpoint source snapshot/grouping/fingerprint measured0.209064s observation/0.454735s settling; duplicate raw-event re-decode <1μs/5.583ms. No shipping microoptimization is justified by these results, no safe2s fix demonstrated, and no additional broad run selected. Inclusive stages cannot be added/subtracted into original N10 residuals. Selected900 remains unchanged; complete results/caveats/evidence are in performance-attribution.md.++Original N10 observation3.932553s/settling6.648267s versus2s remain failed, full33/pre-push acceptance incomplete. Default remains performance-blocked. Necessary owner decision: continue broader duplicate-pass performance work under existing gates, or explicitly accept a documented T-2468 performance exception with wider work tracked separately and actual failures/thresholds retained. No exception granted. The inherited iPad defect remains separate; no association contract decision pending. No commit/push/merge/install/live-library operation.++Transit confirmed final attribution commentCE4C0550-78A4-4976-B1D7-614EE16EC990 at2026-10-18T18:26:07.037Z. Implementation/tasks/Rune were refreshed factually, with g/j still in progress and h/i pending. Private v1 precompile package identity failure is preserved; v2 correction left all library/driver Swift bytes identical. Final code900 correctness checkpoint remains intact.+++## Authorized device-first test preparation, 2026-10-18++Owner chose “Let's test it on device first.” Parent authorized an in-place Devsterism Development installation despite failed budgets, preserving existing data; no merge/permanent waiver or uninstall/reset/repair. All170 files matched archive d325ee4b86c43725c148459c9df82164ea15ac1937a505c63cea1ee5fcd6d804 before this documentation change. Current900 source fingerprint remains abd717d90e04cae2e7e2991be51f70fe66a07597024efd6acdfe9c6bfe4b93ae. `make verify-identity` passed; exact Makefile phone resolution and intended Development identity are recorded in device-testing.md and `/tmp/t2468-ledger-build/device-development-20261018/preparation-receipt.json`.++Installation is NOT complete. Required XcodeOpenWorkspace explicitly returned a recorded request waiting for user approval: unsigned Python bridge client plus this worktree's Asterism folder. Xcode MCP is enabled and reachable outside the sandbox; no grants/security settings changed. No project opened, build started, app installed/launched or data touched. Pending setup action is approval through Xcode MCP or restoration of native MCP integration plus folder approval, then status inspection before retrying the known-unexecuted open request. No CLI signing fallback. Exact IDs and tool response are preserved in the preparation receipt.++No new correctness blocker was found in this read-only preparation review; retained final Core/fast/native and migration-preservation coverage remain applicable. Physical launch/upgrade remain untested, and failed original N10 medians3.932553/6.648267 versus2s, full33 and pre-push UI remain unchanged. Existing Chapter links note editor and Settings Detached link notes support the source-backed manual checklist. Character-centric all-chapters display remains deferred. No tests of nonexistent UI requested.++Transit confirmed device-first preparation/setup-blocker comment 21425115-6C38-497E-9CBC-1D8111CE11ED at 2026-10-18T23:51:44.418Z. Final Xcode status confirms no open workspace and the same two approvals pending; known-unexecuted open action, no uncertain installation outcome.+++## Devsterism device installation completed, 2026-10-19++Owner confirmed the pending Xcode request approved. Fresh status verified both agent/folder grants effective; no approval was repeated or self-granted. Xcode MCP opened the exact ledger project, explicitly selected Asterism Development and the physical phone matched to current Makefile resolution. RunProject attachDebugger:false returned “The app was launched successfully”,52.088s, no build errors. Installed Devsterism0.7.0(1), bundle me.nore.ig.Asterism.dev, teamV24684SCZN; strict app/share-extension signature and development-only AppGroup/CloudKit verification passed. AppGroup library container unchanged; private app-container path changed per iOS metadata, contents not inspected; Personal metadata exact. No uninstall/reset/repair/fixture arguments or scripted data edits.++Source900 remains exact pre/post: abd717d90e04cae2e7e2991be51f70fe66a07597024efd6acdfe9c6bfe4b93ae, uncommitted feature changes atop82d3f6df6032152525e7476827fc90de94a5ee97. Durable receipt/evidence: `../evidence/t2468-devsterism-install-20261019/installation-receipt.json`. Updated device-testing.md gives actionable checks using existing Chapter links, Chapter link note Save/Cancel/Clear, source removal/Skip and Detached link notes. All-chapters character display stays deferred; no nonexistent UI requested. Manual behavior testing remains user-owned, not marked complete by deployment.++Original N10 observation3.932553/settling6.648267 versus2s, full33/pre-push acceptance gaps and separate inherited iPad issue remain unchanged. This is device testing only, no permanent performance waiver or merge approval. No further build/test/device operation queued.++The optional Transit deployment comment was denied before execution by automatic approval review over exact external disclosure authorization. No post or retry occurred. Local installation receipt/checklist are complete and unaffected; a minimal proposed ticket update is retained outside the feature repository for separate approval.++## Current Mac authentication and remaining performance scope++A read-only inspection of the existing Xcode window and current processes found no pending authentication dialog or running `EnableUIAutomation` / `LocalAuthenticationUI` process. The earlier startup log explicitly requests XCTest “Enable UI Automation.” During one coordinated retry, the user must approve that native macOS authentication dialog on this Mac with their own Touch ID or password. No new prompt, test start or permission change was triggered by this inspection; human availability remains pending. Hidden windows beyond the inspected Xcode/process evidence are not claimed.++Matched main controls establish inherited creator/capture budget failures; current creator detail is repaired at 42.8 ms against 50 ms, while capture remains 0.832 / 0.451 / 0.834 seconds against 0.250 seconds. Broader capture redesign is paused and should be handled as a separately scoped follow-up, without waiving its required gate. N10 remains an unresolved feature performance blocker: observation 4.149 seconds and settling 6.765 seconds against 2 seconds. Association work is included and its contribution has not been isolated. No inherited-only attribution or safe dominant replacement is established. Preserve the reviewed work after bounded qualification; merge and installation remain held by performance and incomplete publication gates.
diff --git a/specs/character-chapter-associations/decision_log.md b/specs/character-chapter-associations/decision_log.mdnew file mode 100644index 00000000..9095956e--- /dev/null+++ b/specs/character-chapter-associations/decision_log.md@@ -0,0 +1,206 @@+# T-2468 — Decisions++## Quick Decisions++| ID | Decision | Authority |+| --- | --- | --- |+| Q1 | Use the existing extraction model call, grounding/matching, review and budgets; links remain independent of facts. | Existing owner scope and18October lighter-direction approval. |+| Q2 | Use stable Entry UUID plus RecordKind/record UUID, including URL-free chapters; generic/standalone notes remain fact sources only. | Existing owner-approved meaning. |+| Q3 | Retain V16–V20, add V21 with two tables, new archive20/schema21 and bounded predecessor conversion. No prototype-store reset or physical install. | Existing migration policy; feature V21 is unpublished. |+| Q4 | One implementation stream; targeted checks at each TDD slice, broad required code-commit gates once on composed source, full UI only pre-push. | AGENTS phase policy; proportionate execution. |+| Q5 | Do not apply further speculative association microoptimizations; retain performance block unless an explicit exception is accepted. | Completed matched Release/coarse attribution and independent critic; no exception granted. |+| Q6 | Test the preserved candidate on the paired phone as in-place Devsterism, retaining failed budgets and no merge/permanent waiver. | Owner: “Let's test it on device first”; parent delegated explicit Development install/data-preservation scope. |+| Q7 | Preserve the private scoped capture-reader design/draft, paused as material scope expansion; no shipping adoption or execution. | Morning continuation: distinguish matcher delivery from inherited performance failures and avoid unrelated optimization expansion. |++## Decision7 — Private scoped capture-read proof++Status: Paused following the morning scope checkpoint. A partial external draft is preserved; it is uncompiled and unreviewed, with parity tests unwritten. No shipping adoption, build admission or budget pass.++Later authority: The parent requested a concise morning checkpoint, separation of requested save-time matcher progress from pre-existing performance failures, and no expansion into unrelated optimization. Root therefore stopped this wider read redesign. All 607 shipping Package inputs remain unchanged. Preserved inventory and partial patch: `/tmp/t2468-ledger-build/scoped-capture-reader-draft-971-package8a-v1/PAUSED.json`. The following technical design records the earlier limited preparation decision, not permission to resume.++Context: Current original capture projections fail all three unchanged 250 ms ceilings. Completed private attribution identifies substantial global Entry fetching/grouping and taught projection work; singleton grouping alone is insufficient. The scoped-reader proposal and independent critique find no stable-input closure counterexample, but SwiftData predicate completeness is unproven.++Decision: Draft a separate operation-local reader used only by fresh-context public `projectCapture`. Keep complete relevant physical UUID buckets and the entire Source inventory. Loaded redirects/manual assignments or incoming redirects to selected candidates escape to the unchanged original full reader. Public `projectChapterCapture`, commit, refresh, caller-owned contexts and every global reader/writer remain full. Initial and nested capture bases remain independent. No cross-operation model/history cache, lazy authored-field substitution or new redirect engine is authorized.++The root accepts deliberately narrower unrelated read-property/storage-error reach and additional best-effort observation points for this limited public read. This is not exact original-error or atomic-snapshot equivalence. The existing multi-fetch read already supplies no atomic external-CloudKit snapshot; authoritative save must still revalidate using the complete original graph. This technical acceptance changes no association recognition, persisted identity, authored note, rejection or product-display decision.++Alternatives: PID membership can miss late or pending-deleted physical Work owners; a conservative fallback reads almost every unrelated Work ID and has no evidenced benefit. Partial fetching can defer faults and has contrary historical measurements. Pure grouping or payload memoization does not demonstrate sufficient recovery. No timing waiver or fixture/assertion change is accepted.++Validation and consequences: The original full reader is the stable-input value oracle. Actual recorded-store controls must prove complete relationship/string predicate supersets, physical duplicate and nil/off-Work carriers, global duplicate Source ownership, unscoped rejection, redirect/manual escapes, scalar-distinct URLs and fresh-versus-pending eligibility. Preserve explicit concurrent-arrival limitations. Stop if relevant rows or authority checks can be missed. Only a separately reviewed patch and bounded runtime admission may follow; original performance methods remain required and no speed is promised. Design and critic artifacts: `/tmp/t2468-ledger-build/scoped-capture-reader-design-971-8a-v1/`.++## Decision1 — Association ledger and authored note versions++Status: Independently reviewed; implementation authorized within the owner-approved simpler direction.++Decision: Two relationship-free tables extend the existing extraction acceptance transaction. AssociationEvent stores acceptance, narrow rejection, retirement, scoped invalidation and coverage; PairNoteVersion preserves exact text and explicit parent-head consumption. A normal accepted pair adds one acceptance row. Relevant edits add compact scope barriers and update an atomic current-validation receipt on supported known acceptances; they add no carry graph. Per-pair note parents preserve conflicts/Clear without membership proof ancestry.++Alternatives: A mutable text field on a disposable join loses durable retirement/replay and concurrent authored text. The five-entity source×record proof architecture automatically composed stronger offline histories but imposed broad preparation, mutation and archive integration. Its prior work remains a separate checkpoint branch; none is discarded.++Consequences: Known coherent local edits retain supported links automatically. Validation mismatches await metadata arrival or review; they are never repaired by combining partial receipts. Known identity operations rebind only observed acceptances/active note heads. Unknown late loser branches remain recoverable/inactive.++## Decision2 — Conservative ambiguous offline review++Status: Owner approved; do not ask again.++Authority: The owner accepted: “if conflicting offline edits make a link genuinely ambiguous, we’d ask you to review it rather than resolve it automatically, while preserving your written notes.” The owner answered “Yes” and authorized revised design/tasks, independent reviews and continued implementation.++Decision: Incoherent, incomplete or opposing association branches are held inactive for review. Preserve all raw authored note variants and existing facts. Ordinary coherent supported edits stay automatic. No clock timeout, last-loop election, partial-receipt union or universal offline composition is introduced.++Consequences: Current requirements6.3/6.5 replace the stronger automatic-composition obligation. Existing removal, suppression, linkless identity, exact authored text, explicit recovery and unchanged facts remain required. No additional architecture approval is needed for this agreed tradeoff; genuinely new material decisions must still be surfaced.++## Decision3 — Compact invalidation without endpoint histories++Status: Independently reviewed.++Decision: Mint a scope invalidation on every actual relevant source or matching-field mutation, even with zero known links. Acceptance receipts bind current fingerprints to domain-tagged SHA256 digests of known typed-scope barrier IDs and relevant pair rejection/reconsideration decisions. One atomic Data blob holds the whole receipt. Known before-active supported roots may be revalidated in the existing mutation save; inactive/unknown roots require explicit review. Retire known roots on final support loss. No endpoint scalar tokens, parent epoch graph or per-edit pair carry rows are required.++Rationale: Text hashes alone cannot distinguish A→B→A. Barriers defeat a late previously unseen acceptance once the barrier is known. Independent receipt(S2,R1) and receipt(S1,R2) do not prove(S2,R2). Digests keep receipt size constant as barriers grow. No system can infer a wholly unseen event before it arrives; missing evidence is not a deletion signal.++## Decision4 — Coverage is source plus matching eligibility++Status: Independently reviewed.++Decision: Keep legacy fact coverage intact. New source-scoped coverage receipts certify mention completeness for the saved source fingerprint, relevant barrier/decision basis and normalized typed matching directory. Absence provides one-time older-note eligibility; new records/aliases and support loss/return invalidate it. Reuse the existing bounded lane and held-proposal bookkeeping. Certify only completed source decisions over an unchanged basis; changed post-acceptance matching state remains eligible for a later bounded pass.++## Review clarifications++Independent critic and requirements peer identified bounded technical clarifications, without a new product decision: spelling-scoped immutable rejection acknowledgements; complete historical rebind closure before consumption, independent of current retirement; authored-note operations excluded from membership/coverage; same-pair ordinary recovery; exact saved evidence spelling; coherent archive bundles restored without artificial local barriers; and one operation-local selected inventory with batched physical-ID validation. These contracts are now explicit in design.md and the regression tasks. Both independent reviewers confirmed all must-fix findings resolved.++## Implementation clarification — Known rebind identity++Use each immutable acceptance event UUID plus its typed existing-operation descriptor and predecessor acceptance IDs. Do not introduce a second operation UUID with independent global identity authority: it would require extra lookup metadata without adding authorization beyond the immutable event and validated mapping. Shared-parent opposing destinations remain inactive, dependent branches are quarantined, and known predecessor consumption cannot revive under later conflicts. This follows the critic's explicit option to remove a redundant operation-identity claim. No extra entity, lookup index or owner decision is required.++## Implementation clarification — Atomic identity-operation chains++An existing RecordEdit session can combine A→B and then convert B→Place C before its one save. Preserve this verified finite sequence as typed rebind cores referencing captured before-active roots or earlier cores created in that same transaction. Intermediate B has no current receipt and need not remain a live endpoint after Save. Fold the batch once; only final supported C receives current validation, and exact authored note heads follow the same known steps. Final unsupported text remains recoverable. This implements existing in-order atomic editing, without a general route graph or normal-edit carry rows; no new owner decision is needed.++Independent critic confirmed both implementation clarifications. The combined-operation regression includes already-active A and B, final pair deduplication, differing authored heads and rollback atomicity.+++## Implementation clarification — Coherent archive and known inactive roots++Independent critic confirmed a bounded archive counterexample: local G_other accepted against B becomes inactive after a sync-only source change to A; an otherwise coherent bundle restoring B for G_new could revive G_other without rewriting its receipt. Grant the no-artificial-barrier bundle exception only when the staged merged-scope fold introduces no known before-inactive root through changed source/matching fields. Otherwise use ordinary scoped invalidation, without rebasing incoming receipts, and preserve all events/authored text for explicit review. Missing endpoints or unchanged fields with metadata-only arrival alone do not trigger this guard. This uses the existing two-table mechanism and approved conservative ambiguous-branch rule; no additional product decision or proof subsystem.++Missing-Work closure must also respect existing assignment intent. An unresolved valid pattern assignment may regain its referenced, previously absent Work when the incoming bundle supplies it, the assignment citation and nonownership fields are unchanged, no competing owner exists, and complete final receipt validation succeeds. A manual intentionally-unattached Entry remains deliberate unattachment; an invalid manual/nil-owner tuple remains ambiguous and requires review. Fingerprint equality alone cannot authorize closure because that fingerprint omits assignment provenance and the intentional-unattachment flag. Character ownership has no corresponding intent flag and uses the strict absent-Work/content checks. Independent critic confirmed this distinction against the existing validator and then verified the implemented guard and regression. The focused 43-test run passed, including unresolved pattern closure and deliberate/invalid manual controls; final composed gates remain owed.++## Implementation clarification — Durable pending mention review++Independent peer found a source-backed race: a manual pass can settle sibling B after A samples the held ledger but before A's save completes. An existing-target acceptance can leave the original coverage basis unchanged, so A may certify while B exists only in memory. A manual pass on an already-covered unchanged source exposes the same restart gap even without overlapping saves. Coordinator serialization alone is insufficient.++Independent critic confirmed the bounded correction: save a coverage-only invalidation UUID in AssociationEvent before publishing each nonempty settlement as held. Mention completion binds these IDs; membership, literal support, source guards and legacy fact coverage do not. Preserve old immutable coverage. Either save ordering leaves the source eligible, and replay cannot remove the additive marker. Retry the same settlement with the same UUID. A returned completion basis may refresh held metadata only if its original source/matching basis still matches; failed persistence cannot claim durable review. Gated regressions precede implementation. This repairs requirements3.2/3.6 within the approved two-table design; it introduces no product choice, entity, model call or endpoint history graph.++Follow-up critic counterexamples refine completion: after restart, an empty/deduplicated-empty model result must not certify away still-current pending B. Persist only minimal original review keys, source guard, grounded spellings and known typed target; explicit Keep/Skip acknowledges captured keys. Pending validity is separate from global directory/coverage churn, so an unrelated C edit or harmless supported B rename cannot silently discharge B. Genuine source revision/eligibility changes or positive coherent support loss can stale it. Missing, conflicting or rerouted targets require review, and conflicting marker variants block affected coverage. No full facts/proposal queue is introduced. This refinement is independently reviewed and awaits runtime regression/implementation evidence.++The critic reviewed duplicate settlements arriving during an awaited decision: an already-current supported acceptance may satisfy a redundant Keep obligation only for the same guarded source and known typed target, with every original spelling present in unsuppressed receipt evidence. Keep explicit acknowledgements scoped to captured marker IDs; never let a prior Skip or partial spelling overlap discharge later manual reconsideration. The existing generic routing/refusal check precedes association acceptance validation, both before the first mutation, so removed aliases reroute normally instead of repeatedly returning staleSource. Focused regressions and GREEN execution remain pending.++A subsequent spelling-set counterexample tightened that Keep proof: receipt evidence may contain names beyond the original decision. Require an explicit Keep acknowledgement with its committed target, referencing an immutable marker item with exactly the same source guard, original key, original typed target and spelling set, together with current active whole receipt support. This narrow witness also covers a new candidate becoming a saved target. Do not infer acknowledgement from broad current evidence or timestamps. The witness stays in the existing coverage acknowledgement event case/table.++## Approved validation closure — Narrow NoEpisode history reuse++On18October2026 the parent explicitly authorized focused counterexamples and a narrow history-reuse repair within the approved implementation, preserving pending clears, conflict validation, Work moves and rollback. This supersedes the earlier exclusion of speculative old NoEpisode optimization only for this reviewed, evidence-backed closure; it does not authorize copying the prior prototype or widening feature scope.++Exact-base public-API probes establish that both global fetch/group and decode/sort costs grow with unrelated history. Original M4 samples show the existing production path doing this repeated finite work, while total feature overhead remains unmeasured. Preserve the original failures, samples, assertions and budgets; bounded exact-base/current checks precede broad reruns.++Use one explicitly passed, context-bound history session per existing save chunk, fresh for each replay after rollback/refault. Keep the public single-call writer on a fresh session. Lazily fetch/validate all physical history on the first nonempty transition, preserve the complete same-call planning snapshot, and incorporate inserted stable/random clears only for subsequent calls. No persistent model, schema/index change, global context cache or narrowed corruption-refusal scope.++Independent critic verified an important legacy boundary: an empty transition does not decode history, and the subsequent Work-stage raw workID repoint does not validate payloads or coalesced conflicts. Preserve that timing: move raw rows, invalidate decoded state without eager validation, then globally validate at the next nonempty transition. Own repoints may retain complete raw rows; external invalidation must drop raw and decoded inventories. Never validate at teardown merely to populate a cache. Discard sessions after save/rollback; test cold/warm raw moves, later conflicts, pending clears and fresh replay explicitly.++Mac UI remains pending the proven user authentication request; no unattended retry, prompt acceptance or security-setting change is authorized by this closure.+++## Subsequent Mac retry authorization and actual outcome++The owner supplied trusted evidence that XCTest approval had been granted and explicitly authorized one retry using existing permissions, superseding the earlier no-retry status for that single attempt only. The retry ran all three declared synthetic Development journeys: two passed and the editor-opening save/cancel journey failed at its existing line64 assertion. No new authentication blocker was observed. The retained failure is now a behavior/test-driver diagnosis; no further retry, security change or prompt acceptance is inferred from this authorization.++## Authorized bounded continuation after performance run3++The parent subsequently authorized one focused Mac journey diagnostic within existing verification scope, using current automation permissions without changing settings. Inspect existing destination/loading/editor markers before the original failing assertion; preserve the route and all assertions. This supersedes the pending permission status for that diagnostic only.++The parent also explicitly authorized investigating and implementing narrow NoEpisode history reuse within the existing 500-record import save chunks. Keep all approved behavior, persistence boundaries, global correctness checks, pending clears and historical data, with unchanged performance budgets. This expands the earlier four-site repair to the audited live import Entry loop only. Focused importer regressions and independent review precede production changes. No cross-phase/cross-import cache, transaction change or validation narrowing is authorized; report any necessary departure before implementation. Preserve the prior source/evidence checkpoint and distinguish inherited baseline cost from feature-added overhead using bounded comparable evidence.+++### Continuation: archive raw/effective title coherence+The new exact-NFD archive control exposed a real shared mapper mismatch: a valid title-bearing authored chapter has raw legacy chapterTitle nil/provenance none, but the shared legacy archive projection takes the effective authored title from EntrySnapshot while retaining raw provenance. Strict prospective restore rejects that contradictory legacy tuple. The symmetric authored-note case can hide a present raw legacy title. Preserve the strict importer and the failing control; prepare a narrow mapper correction selecting raw chapterTitle from the same representative/carrier branch as its citation, with authoredTargetData retained independently by the current format. This is persistence fidelity within the approved implementation scope, not a display or transaction policy change. Peer/critic review and targeted RED/GREEN are required before native/rendered follow-ups. Do not change the fixture simply to avoid a valid title-bearing authored target.+++### Conditional Mac navigation comparison admitted+Both clean uninstrumented Mac controls reproduced the original Inspector Edit failure at AssociationNotesUITests:64 before the Entry editor rendered (31.998s and30.554s; exact two IDs, no skips, unchanged inputs, exit2/drained). This meets the critic-reviewed conditional trigger. Apply the minimal view-local Today stack revision: retain identity through forward navigation and reset only when the final coalesced state returns from a pushed destination to the dashboard. The observer remains outside the identity boundary; do not rewrite selections/bindings, introduce asynchronous delays or remove the known Work→Back stale-controller reset. This is a candidate until native state, original Mac Save/Cancel/relaunch/NFD and different-Entry/WorkBack/day controls plus the affected existing iPad scroll/Back regression pass. Native state tests do not independently prove SwiftUI render coalescing.++### Lazy raw Work buckets within the existing history session++The retained synthetic sampling identified repeated raw Work-owner traversal inside the already authorized history session. The reviewed correction builds a per-Work index only when the first raw repoint occurs. It retains the complete physical inventory for the original global validation, moves the same row references, merges target buckets, incorporates pending inserts, and drops both inventories on external invalidation. No session crosses a save/rollback boundary; record-only imports do not build the index.++Runtime RED preserved data semantics and exposed exactly two excessive-traversal counters. Focused GREEN passed five declarations / six cases, followed by the exact 85-declaration / 90-case affected cohort. The unprofiled Debug D comparison preserved every expected import payload, clear and record count. Import remained near the prior C observation (0.744 versus 0.741 seconds); duplicate settling fell from 7.965 to 5.868 seconds while observation remained near 3.27 seconds. These are single observations across qualified source snapshots, not an isolated causal estimate or a Release budget waiver. The unchanged original ten-sample Release duplicate test is the next admitted gate. Both warnings in its clean external predecessor build were proven to originate in an entire-file-identical baseline file.++The selected original Release declaration completed with ten samples in each distribution and exactly its two original budget failures: settling median 6.648267 seconds and observation median 3.932553 seconds, both above two seconds. No semantics, sample or threshold was changed. The reviewed narrow history work has no further evidenced correction; the small prior Debug prefetch experiment does not establish a remedy for this remaining gap. The next verification is bounded read-only attribution on the current Release source, before any broader implementation proposal. The actual test duration was 153.168 seconds and total guarded duration 718.353 seconds; buffered output prevented the separate runtime-clock state from activating, so those independently observed timings are retained without claiming that clock was enforced. Owned processes drained without signals or uncertainty, and all 898 compiler inputs remained unchanged.++### Captured-revision binding invariant: meaningful RED and phone GREEN++The minimal native invariant retains the current view-local stack revision and forwards the original binding transaction. It discards only a nil written by a binding captured under an earlier revision; nonnil writes, same-revision nil and direct app navigation continue unchanged. A mounted host test retains the old State reader through an actual body update, rather than substituting reference storage. This addresses an independently testable ownership boundary; it does not establish who caused the observed Mac selected-ID clear.++The seam-only runtime RED executed all six methods and failed five assertions in three methods. The original four-issue plan omitted an existing write-count assertion; its retrospective correction changed no test or source. The same six phone GREEN methods then passed in0.021s, including the live State, transaction and direct-clear controls. Root accepted native exit0 separately from wrapper124: only a birth-verified post-Xcode ibtoold was signalled, with no tracking errors, remaining processes or uncertainty. Six warning fingerprints match reviewed inherited origins. The same six Mac native tests are the next admitted check; no rendered-navigation or overall feature acceptance follows yet.++Mac native verification passed the same six methods in0.492s, including the actual AppKit mounted-State control. The guard exited0 naturally. Root reconciled all28 unique inherited warning fingerprints against prior source/tool evidence. The affected whole navigation cohort then passed120 declarations/128 expanded cases across five actual suites (62 AppNavigation,28 Today,15 Intent,7/8 PrePush,8/15 RecordCopy). Tests declared in extensions retain their suite owner; filename or before/after-struct counting is insufficient. Exact900 source inputs remained unchanged, with no skips/issues/warnings. Native0 and wrapper124 are separately retained; root verified the sole orphan ibtoold cleanup and an empty final ownership scan. The original five uninstrumented Mac journeys are the next admitted behavior check.++The relationship-prefetch hypothesis first passed three test-only baseline controls after six missing fixture timestamps were corrected. All assertions remained unchanged, and the exact baseline test file/full900 source map was restored afterward. The reviewed future trial changes only the ordinary Entry descriptor's Work relationship prefetch and appends those controls. One whole88/93 affected cohort avoids a redundant immediate focused run. Any benefit claim still requires the unchanged original Release N10 distributions and two-second limits; correctness alone does not admit retention. A private clock-only correction starts its conservative600-second helper-lifetime ceiling from verified owned helper birth, avoiding the earlier buffered-output activation gap. Ownership and signalling logic remain unchanged, and the prior failed budgets/clock qualification are preserved.++The final uninstrumented Mac candidate cohort passed all five original journeys in242.216s, including the previously failing Work→Back→Entry/day sequence, Save/Cancel/relaunch and exact Unicode readback. Source900 matched before/after; native and guard exited0 naturally, without signals, uncertainty or remaining processes. Runtime open-file evidence confirms the per-test UUID-scoped synthetic Development store; it is distinct from the native Mac6 run, whose actual bootstrap namespace was not retained. No compiler/runtime warnings occurred; the sole prior destination-selection warning was independently matched. The observed candidate Mac cohort is accepted, without claiming who caused the earlier nil transition. Existing iPad restoration and original Release budget failures remain open.++Transit confirmed progress comment B6F2840F-1A4C-4751-B2F2-A8707E457161 at2026-10-18T16:33:59.107Z. The descriptor-only candidate was then applied with exactly two expected Core-file deltas under the comprehensive900 map; one whole88/93 correctness cohort is admitted. Original Release verification and retention require separate review.++The descriptor-only trial passed88 declarations/93 cases, then the unchanged original Release test completed all ten samples per distribution with exactly two budget failures: settling median6.281479s (p957.430748) and observation3.682579s (p954.440666), both against2s. Build567.74s, native test146.912s, guarded total717.985s; native/guard2 ended naturally with no signals, tracking errors, remaining processes or uncertainty. Exact candidate900 integrity passed. The birth-verified helper clock activated after570.958s build/startup; the firstDistribution field remained absent under buffered output and was not retrofitted. All20 warning origins across seven files were source-qualified inherited expressions.++Root chose not to retain this trial: the modest single-cohort numerical reduction does not establish repeatable benefit or close either budget. The checked restoration changed only the two admitted Core files, returned the complete900-file baseline and passed the authoritative binding green900 check. Existing raw facts/history, all tests and prior failures remain preserved. A separately reviewed pure cache-warming hypothesis remains private: unconditional hashing of every invalidation scope is observed during folds, but bulk extraction also repeatedly queries individual scopes. A bounded source-shaped comparison must assess that tradeoff; neither correctness parity nor a duplicate-only improvement may be called extraction nonregression.++The private source-shaped cache comparison completed with both variants' build/runtime guards exiting0 naturally and all900 shipping inputs unchanged. It used identical frozen Core copies (common unused prefetch source explicitly qualified), a fixed448-event fixture, nine fixed measured samples and exact expected public-call counts. All fixture/ordered128-Entry output bytes matched. Global receipt-root-only warming reduced combined-mode construction78.56ms→9.86ms per eight iterations, but increased repeated public queries694.02ms→860.80ms; combined776.48ms→874.81ms. These observations are excluded from original budgets. Root rejected the global candidate, which was never applied to the worktree.++Independent caller review supports a narrower technical alternative: preserve all-observed warming in the public initializer and ordinary storage/extraction/coverage/pending reads, and opt in only mutation capture and finish. Complete maps, physical-copy validation, barriers, fallback digests, notes and save boundaries stay unchanged. The capture inventory can still answer repeated per-mention source guards, so it is not described as exclusively receipt-only. The exact three-file internal-plumbing patch and three value/storage parity regressions passed critic source review; execution preparation is admitted, not source application or performance retention. Existing original N10 failures remain the performance RED without invented counter tests or changed budgets.+++The mutation-only candidate was then admitted with an exact900→901 universe, preserving the three original production-file backups and owning one new three-test file. Its single whole correctness cohort passed329 declarations across31 suites in19.455s, with288 ordinary executions plus154 argument executions matching every source value and terminal count (442 total). No test issue, skip or new warning origin occurred; all eight warning origins were matched to baseline. The initial greedy-title parser receipt remains preserved; corrected read-only reconciliation changed neither tests nor runtime. Source901 matched after the natural59.802s guard exit and complete drain. Correctness is accepted; one original N10 Release trial is separately admitted under the reviewed900s build/600s helper-birth runtime bounds, with both2s limits and all original assertions intact. Neither performance benefit nor retention is decided.+++The separately admitted mutation-only Release trial completed its original warm-up plus ten measured samples per distribution. Settling median6.309745s (p957.237939) and observation3.796133s (p954.512053) both failed their unchanged2s limits; exactly two budget issues and no semantics/count issue occurred. Build567.02s, test149.095s, guarded719.412s; natural native/guard2, no signals/tracking errors/remaining identities or cleanup uncertainty. Source901 matched. The owned helper-birth runtime clock activated after569.927s; buffered firstDistribution remained absent and was not retrofitted. Root independently checked all26 warning expressions against baseline. The modest single-cohort movement does not establish repeatable benefit or close budgets, so root rejected this optimization. Checked restoration wrote only three exact backups and removed the owned trial test, returning comprehensive900 and authoritative binding green900. Private trial patch/tests/evidence are retained; no further optimization is admitted. Final composed correctness gates remain owed on restored900, with original budgets/full33 and inherited iPad scope decision still open.+++### Final restored-source correctness checkpoint++The selected900-input source passed the final unfiltered serial Core inventory:3,962 declarations passed and55 exact existing performance test skips (4,017 total), with6,304 expanded executions and no test/model issue. All20 warning origins are inherited. A read-only multiline-report correction accounted for22 literal-newline argument records in the same immutable log; initial reports/manifests remain preserved and no test was repeated. The fixed456 fast manifest then passed all456 IDs/552 expanded executions, no warnings/skips/issues, with exact same-source argument values.++Signed Mac compilation retained the embedded-extension assertion and succeeded. Full native then passed1,791 declarations/1,871 expanded cases; every120 Argument node passed and no method/skip/expected failure or runtime issue remained. Source900 matched. NativeMake0 is accepted separately from wrapper124: the reviewed guard stopped only post-Xcode ibtoold23804, proven by birth/ancestry, leaving no errors/remaining identities/uncertainty. Three tool warning messages match prior raw evidence. One historical dictionary-display ordering difference is semantically identical to the three current declared inputs; no test or receipt was changed. Exact UUID-only store evidence is retained, and the task simulator was already Shutdown.++This closes final composed correctness without implying feature readiness. The original Release budgets/full33 and inherited iPad position-contract decision remain open; full pre-push UI acceptance is still owed. No feature commit, push, merge, physical operation or further optimization/run follows. Preserve the checkpoint and concrete blockers for parent review.+++### Scope decision: inherited iPad scroll remains separate++The parent explicitly keeps the inherited iPad cross-width scroll defect outside T-2468. Its assertion remains unchanged, and its failure remains open for full UI acceptance; this is not a baseline waiver. Feature work continues with measured observation/settling attribution, requiring an unchanged-baseline comparison, source-backed cost identification and the smallest safe fix. No broad rerun or additional optimization is justified solely by another unmeasured hypothesis. If the existing budget cannot be met safely, present concrete measured baseline/candidate costs and the minimal product trade-off.+++## Measured performance disposition, 2026-10-18++Status: Technical disposition reviewed; performance exception **not approved**.++Context: Matched unchanged baseline A ran96.163457s observation/170.459822s settling; selected C ran2.932167s/5.230809s with identical fixture/outcome checks. Common history repairs are included. Original repeated C medians remain3.932553s/6.648267s against2s. Coarse timing-only C preserved all operations,750 unique Entry barriers and zero acceptance/pair-note rows. Endpoint source snapshot/grouping/fingerprinting measured0.209064s/0.454735s; raw re-decoding measured <1μs/5.583ms. Inclusive spans do not support N10 subtraction, a database-write-only claim or an impossible-budget claim.++Decision: Do not ship a decode microoptimization or speculative fingerprint/cache rewrite. Keep selected900 unchanged and preserve the verified correctness checkpoint. Default is blocked on existing performance gates. The owner may explicitly accept a recorded T-2468 performance exception with broader duplicate-pass performance work tracked separately; without it, continue targeted wider-path attribution before new implementation/broad runs. No budget change, assertion weakening, merge or install is implied. The inherited iPad defect remains separate by the parent's prior decision.++Consequences: Attribution is complete for the examined successful empty-acceptance fixture. There is no demonstrated small semantics-preserving2s fix. Target-record/replay/failure-path costs remain unmeasured. Reliable saved associations remain the agreed product behavior; the pending choice is performance acceptance, not a new data/association contract. See performance-attribution.md for exact receipts and tables.+++## Device-first testing authorization, 2026-10-18++Status: Device testing authorized; installation blocked on Xcode MCP agent/folder approval, not denied. No performance/merge acceptance implied.++The owner chose physical testing before deciding performance acceptance. The parent explicitly authorized Development/Devsterism in-place install preserving existing data. Normal signed deployment must use Xcode MCP and the current Makefile's paired phone. No uninstall/reset/live-data repair, security-setting changes or inherited iPad scope expansion is authorized.++Preparation verified all170 preserved checkpoint files and all900 shipping inputs; identity lint passed. No additional source correctness blocker was found beyond recorded incomplete performance/pre-push acceptance. XcodeOpenWorkspace for this worktree's project returned a pending-user-approval error. The bridge works outside the sandbox, but Xcode sees the fallback bridge client as unsigned Python and this project folder has no grant. No grant was self-approved and no build/install/launch started. See device-testing.md and the local preparation receipt for exact pending request identifiers and actionable test steps after installation.+++## Approved device deployment completed, 2026-10-19++Status: Installed and launched; user manual testing pending. No merge/permanent waiver.++Authority: Parent supplied trusted owner reply “I approved it” to the Xcode blocker and directed resumption. Effective agent/folder grants were verified before retrying the known-unexecuted open request. No further grant or setting changed. Xcode MCP opened this exact worktree, explicitly selected Development and the Makefile-matched phone, and RunProject with no debugger confirmed launch52.088s. Source900 pre/post fingerprint remains abd717d90e04cae2e7e2991be51f70fe66a07597024efd6acdfe9c6bfe4b93ae. No feature commit was created.++Signed app/extension identity and strict validation passed. Devsterism library App Group metadata stayed fixed; iOS reported a new private app-container path, contents uninspected. Released Personal metadata remained exact. No uninstall/reset/repair/fixture launch or scripted data edit. Durable installation receipt and real-control checklist are linked in device-testing.md. Performance failures/full33/pre-push gaps remain recorded; the installed Development build is not a Release timing verdict. Inherited iPad scope stays separate.
diff --git a/specs/character-chapter-associations/design.md b/specs/character-chapter-associations/design.mdnew file mode 100644index 00000000..6cb30b4c--- /dev/null+++ b/specs/character-chapter-associations/design.md@@ -0,0 +1,83 @@+# T-2468 — Extraction-owned chapter associations++## Architecture++Extend the existing extraction/review transaction with a typed association ledger and independent authored note versions. Membership is a current saved-note claim; inconsistent offline branches await review (Decision2). All writes remain under the existing repository lock/save strategy. There is no second model call, endpoint revision graph, carry-proof subsystem or universal routing table.++### Storage and value contracts++Add two relationship-free models nested under liveV21. Keep existing V20 model fields unchanged, freeze V20, retain V16–V20 and add the lightweight20→21 stage. No unique constraints. Nonunique indexes on event work/Entry/record lookup fields support selected reads. New value types/codecs/folds live in AsterismCore beside RecordFacts; Intelligence consumes value snapshots only.++| Model | Stored shape | Contract |+| --- | --- | --- |+| AssociationEvent | id, workID, optional entryID/recordKindRaw/recordID lookup columns, immutable typed eventData, optional mutable validationData, recordedAt | Payload cases: accept, reject, retire, invalidate, coverage, pending review and explicit review acknowledgement. Lookup columns must agree with payload. An accepted pair normally adds one row. |+| PairNoteVersion | id, workID, originPairData, attachmentAcceptIDsData, parentHeadIDsData, operationRaw, exact text, originalContextData, authoredAt | Immutable text/Clear/recover/rebind operation. No source/record proof closure. Raw content remains readable if metadata cannot fold. |++Association accept core contains the typed pair, original grounded normalized spelling keys and explicit rejection IDs being reconsidered. Normal review acceptance has no predecessor acceptance. A known combine/conversion may create a rebind acceptance referencing observed before-active acceptance IDs or earlier cores minted in the same verified atomic operation chain; those old roots are historically consumed and cannot revive. Reject is scoped to one chapter, kind, target and equivalent normalized spelling, preserving candidate/fact suppression separately. Retire names acceptance IDs irreversibly. Invalidations identify a typed Entry/Character/Place/Work scope and an independent UUID; coverage identifies an Entry and eligibility digest.++A receipt is ONE atomic Data value: current pair, source fingerprint, target matching fingerprint, source/record scope-barrier digests, spelling-scoped rejection/reconsideration digest, and current supported spelling keys plus exact current evidence spellings/source spans. Evidence may instead be deterministically reconstructed from the current saved note bound by that receipt fingerprint; immutable acceptance-core spelling is historical and never substitutes for refreshed current evidence. Scope fingerprints include ownership and chapter eligibility; matching fingerprints include normalized current name, retained key and accepted aliases, excluding record prose/facts and display-only chapter fields. Hash input is domain-tagged, length-framed typed scope plus sorted unique UUIDs; timestamps are not a causal basis. Only overlapping normalized spelling keys contribute rejection IDs and their immutable acknowledgement acceptance IDs. Unrelated ordinary acceptances and every authored-note operation (including Clear/conflict resolution/recovery) are excluded from membership, suppression and coverage digests. Every physical immutable-body copy for encountered IDs must validate, including off-scope copies; conflicting cores yield review/refusal. Mutable receipt variants are whole values: never merge fields, combine partial tuples, choose by loop order or manufacture a matching receipt.++### Membership and mutation rules++Current membership requires live coherent same-Work eligible Entry/typed record, literal support, an unretired/unconsumed acceptance and at least one complete receipt matching the current fingerprints/barrier/decision digests. Equivalent physical receipts and same-intent roots deduplicate by application identity/pair. Missing parents, opposing decisions, unknown roots and incomplete receipts remain inactive/reviewable. Missing sync endpoints never imply intentional deletion.++Every actual note/kind/ownership or record matching-field change writes a compact scoped invalidation, even with zero known links, so a later unseen old acceptance cannot bypass a known removal/return. Read projections never create barriers. Before a repository mutation capture its selected current associations; after fields apply, refresh the atomic receipt only for roots that were already active and remain literally supported. Retire known roots losing final support/eligibility. Inactive/unknown roots are never stamped into acceptance by a benign edit. No barrier for unchanged fields or unrelated facts/prose/rating/title/URL edits. All effects share the existing save and rollback boundary.++Save-time mention removal also checks a narrow observed transition: for coherent before-active and final endpoints, intersect maintenance evidence with each side’s unsuppressed whole receipt. Maintenance evidence requires complete-name boundaries for spellings containing cased scalars and preserves established literal support for fully uncased spellings. Before-supported → final-unsupported retires the captured roots before ordinary refresh; verified rebinds still preserve typed historical cores and exact note-head transfers but receive no final membership receipt. Existing literal-loss retirement remains. Unchanged/rating-only legacy partial receipts are not reinterpreted, missing/torn endpoints do not prove removal, and before-inactive roots gain no authority. Public AI grounding and whole receipt evidence/format remain unchanged (save-time S4).++For a rejection/reconsideration, capture the displayed spelling-scoped decision basis. An acceptance core acknowledges exact rejection IDs only for the same typed pair and overlapping equivalent spelling keys. A proposal spelling is suppressed while any applicable rejection lacks a structurally valid acknowledgement; acceptance retirement does not undo that historical acknowledgement. Rejecting A does not suppress a genuinely different supported spelling B. Acknowledgement identities enter the relevant receipt digest, so later acceptance G2 reconsidering A does not revive inactive G1 or attach G1 notes. On a local rejection, refresh only before-active roots still supported by an unblocked spelling; retire roots losing final unblocked support. Manual extraction may propose reconsideration; it never writes acceptance by itself.++On known combine/conversion/work merge, inspect only affected current pairs using existing survivor IDs. Create a verified rebind acceptance for each supported destination, consume/retire old roots, and preserve known active note heads by exact-text system rebind versions attached to the new acceptance. Historical rebind validation checks complete immutable parent closure, typed scopes and the immutable acceptance identity and persisted typed operation descriptor, independently of whether parents are currently retired. A child arriving before a missing/conflicting parent consumes nothing. Only a structurally coherent complete rebind consumes parents; its current membership still requires its own valid receipt/support. Conflicting destinations consuming the same parent keep both rebind branches reviewable and do not silently elect a destination. An existing atomic session may combine then convert: batch one finite typed historical core per verified in-order step, and fold once. Intermediate cores need no current receipt/live endpoint; only the final supported destination receives a current receipt. Exact-text note versions follow the same known steps; final unsupported text stays detached. These are identity-operation steps, never normal-edit carry rows or inferred routing. Preserve concurrent differing heads. Late unknown loser roots/notes remain inert/recoverable; no name-based redirection is inferred. Ordinary Move To that loses ownership/support retires membership; moving back requires review.++For arrivals/import, build one operation-local grouped event inventory for selected scopes and live endpoints. Batch-fetch all physical copies for encountered immutable IDs, memoize typed-scope barrier digests and historical parent validation, and share one normalized matching-directory signature per Work. Never fetch/scan full history per pair or issue per-ID queries. Validate affected/current roots and publish coherent values. Use selected changed IDs where available; fallback traverses active association candidates rather than every chapter plus a proof inventory. Unchanged receipts and inactive unknown branches cause no metadata growth. Do not add unrelated NoEpisode/duplicate optimisations.++### Existing pipeline integration and parity audit++| Existing site | Equivalent needed | Change |+| --- | --- | --- |+| SourceRef.entry / ChapterCaptureResolver | yes | Retain Entry UUID; reject standalone-note kind for new links. Facts keep dangling-citation behavior. |+| CharacterGrounding / RecordMatching | yes | Share the existing pure literal/name rules with AsterismCore support validation; retain precedence and kind separation. |+| CharacterExtractionAssembler.survivor/grouped | yes | Carry per-source grounded mention proposals through fact/alias dedupe; current pair/suppressed equivalent evidence controls repetition. |+| ExtractionCandidate / CharacterExtractionSource / ledger / coordinator | yes | Add value-only mention eligibility and source context to the existing lane; no prepare-history write or extra candidate reread/model call. |+| commitDecision/applyAcceptance/writeCoverage | yes | Recheck live eligible source and shown target, then save record/facts/aliases/links/decisions/coverage together. All-facts-unticked still saves displayed mentions. Stale Skip remains allowed. |+| Capture/manual Entry/reparse/correction/record edits | yes | Central selected before/after association helper; only changed matching fields invalidate. No writes before editor Save. |+| DuplicateReconciler/WorkMerge/deletion/conversion | yes | Use affected survivor/loser IDs, scoped barriers, known rebind/retire and note-head preservation in existing transactions. |+| Backup builders/projection/reference checks/import | yes | Add both raw arrays and bounded conversion, immutable-ID validation, exact-note preservation and selected revalidation. No epoch carriers. |+| EntryDetail/provider/mock / reconcile publication | yes | Entry-local association/note value snapshots separate from fact citations; no models escape lock. |+| Settings recovery / inventory / diagnostics / Empty Library | yes | Raw detached-note recovery and both model types in existing inventories; destructive checks use synthetic fixtures only. |+| Fact citations/ranking/chips/RecordCopy | no new behavior | Existing facts/rank/search remain; copying records creates no destination chapter evidence or notes. |++Coverage uses new source-scoped AssociationEvent receipts; legacy fact coverage remains unchanged. Eligibility binds note fingerprint, source barriers, association rejection/reconsideration basis (excluding authored notes) and normalized typed Work matching-directory signature including relevant matching barriers. Missing receipts make legacy covered chapter notes eligible once. New records/aliases and support loss/return re-arm unchanged notes. In-flight/attempt/held bookkeeping uses this composite eligibility basis. Certify only when every proposal for that source across both kinds is decided and the current basis still matches; produced-none may certify, failure/unavailability may not. Acceptance changing the matching directory conservatively leaves the source eligible. Existing automatic/manual budgets remain authoritative.++Nonempty mention settlement must durably re-arm review before publishing held proposals, including manual processing of an already-covered source. Store coverage-only invalidation UUIDs and minimal original review keys/source guards/grounded spellings/known typed targets in the existing event table, without facts or full proposal DTOs. Explicit Keep/Skip acknowledges captured keys atomically; none/dedup-empty cannot discharge pending review. Pending validity uses current selected source/target support, separately from the global coverage digest: unrelated directory churn or harmless supported rename preserves it; genuine source revision/eligibility change or positive coherent support loss may stale it. Missing/torn/rerouted targets and conflicting marker variants remain review-needed and block completion. A redundant Keep obligation is already satisfied only with an explicit Keep acknowledgement witnessing the same source guard, original review key, original typed target and exact original spelling set, plus its committed typed target and a current active whole receipt proving every spelling. This also maps an originally new candidate to the target actually created by Keep. Pair existence, broader current receipt evidence, partial spelling overlap and prior Skip are insufficient. Explicit acknowledgements remain scoped to captured marker identities, so a future manual reconsideration after Skip remains pending. Coverage-only metadata never affects membership receipts, source guards or legacy fact coverage. Either ordering of a stale completion and new marker leaves review eligible. Publish held output only after persistence succeeds; retry the same settlement UUID and refresh completion metadata only over unchanged original inputs. This independently reviewed correction is implemented; its focused restart/ordering regressions and the composed Core/native gates passed. Rendered and performance gate status is recorded in checkpoint.md.++### Evidence-backed NoEpisode validation closure++The parent approved a narrow save-chunk-local transient history session after exact-baseline probes identified repeated global work. Keep all existing writer validation and random-clear semantics; public single calls create fresh sessions. Load and validate globally only for a nonempty transition, plan from one unchanged per-call snapshot, and publish inserted clears into the session for the next call. Repoint raw Work history without decoding, then invalidate decoded state; a later nonempty call performs global revalidation. External invalidation drops raw rows too. Sessions end at actual save/rollback boundaries and each failed-chunk replay gets a fresh session. No persistent schema/index, context-global cache or narrowed validation scope is introduced. See decision_log.md for authority and the independently reviewed deferred-validation boundary. Correctness RED and bounded scale checks precede broad reruns; the original M4 timeout is retained.++## Authored notes and APIs++Expose value-only Entry associations and supported/current, awaiting-review and detached-note snapshots. Repository APIs accept captured pair/receipt/decision/active-acceptance and complete current note-head bases. Re-derive under the lock; refusal/save failure preserves the exact draft and prior data.++Note folding validates immutable bodies, complete direct parents and acyclic references with operation-local memoization. Parent consumption is historical and happens BEFORE current active/detached projection; membership retirement must not undo Clear. Ordinary text/Clear consumes only the complete captured active heads and shares an attachment acceptance with each parent. Ordinary explicit recovery targets only the same typed pair and consumes selected detached heads plus all current active destination heads, with captured attachment references; unselected detached groups remain unchanged. Cross-pair note rebind is available only to a verified existing combine/conversion operation, never arbitrary destination selection. Validate each parent's typed scope and complete immutable closure before consuming it; a system rebind references the historically valid association rebind, even after its old acceptance retires. Historical validation uses persisted operation/parent attachment references, never current endpoint epochs or current membership as authority for an old Clear.++A surviving text head attaches only through its current active acceptance IDs to one coherent current pair. A new acceptance ID for the same pair does not attach an old note. Resolve/recover are explicit; conflicting Save/Clear preserves unseen text as a separate head. Invalid metadata never becomes a fake empty head basis: refuse writes, expose raw exact variants/context for recovery. No authored text enters extraction DTOs or supports membership.++Entry-local note editing reuses CharacterEditorView/ManualEntryFormModel value-draft and Save-terminal patterns. Settings detached recovery reuses existing backup/recovery navigation and explicit same-pair recovery; it remains reachable after endpoints disappear. No history browser, cast redesign or auto-generated note UI.++## Migration and archive++LiveV21 contains the two new models plus unchanged V20 models. New archives are format20/schema21, with raw event/note arrays and bounded19/20 and18/19 conversion to empty feature arrays. UUID upsert is additive; absence never deletes local decisions. Preserve immutable contradictions for named refusal/raw-note recovery and whole receipt variants without arbitrary election. Existing newer-local base-record guards remain. A complete coherent incoming bundle restores its exact source/matching fields, barriers, events and whole receipts without minting artificial local invalidations. This exception requires that the staged merged-scope fold does not revive a known before-inactive root through changed source/matching fields. If it would, treat that merged scope as ambiguous and use ordinary scoped invalidation without rebasing incoming receipts; preserve all events/text for review. Missing endpoints or unchanged fields with metadata-only arrival do not alone trigger this exception guard. Stage the operation's incoming fields/events before revalidation; intermediate alias/source chunks never intentionally retire roots. With existing chunked saves, determine and stage any genuinely required ambiguity invalidation before the earliest affected base-field chunk can commit, so a later chunk failure cannot persist an implicit revival. After staging the complete winning bundle, reuse selected before/after revalidation for known before-active, unopposed roots that remain coherently supported, preserving incoming whole receipt variants; never refresh inactive, unknown, retired, consumed or conflicting roots. Preserve newer-local base-record guards: if local fields win, mismatching incoming receipts remain inactive. Legacy/unproved genuine field changes use the ordinary selected before/after invalidation path. Incomplete arrivals may remain inactive until coherent metadata arrives; they never imply deletion or manufacture acceptance. Old-format export refuses if it cannot preserve feature content.++Use fresh and populated recorded-V20 fixtures; no eager model backfill or model calls during migration. Prototype five-tableV21 files stay in their checkpoint and are never opened/reset by the new schema. Update marker/bootstrap/extension/archive envelope/model inventory together per schema-migration.md.++## Validation++First implement pure synthetic counterexamples: unseen acceptance after A→B→A; independent receipt tuples requiring review; routine remaining-spelling continuity; narrow rejection/manual reconsideration; alias/new-record coverage on unchanged text; Clear surviving retirement; concurrent note text/recovery; known rebind versus late unknown loser; reject A/accept B and explicit A reconsideration without old-root revival; child-before-parent/retired-parent/conflicting rebind replay; alias-first then source-change coherent archive restoration; note Clear having no effect on membership/coverage. All referenced retire/rebind/note parents must validate typed scope. Use deterministic shuffle/idempotence tests over event order; no new testing dependency.++Then real SwiftData fixtures cover physical duplicate bodies, pending writes, failed-save atomicity, migration, archive/reopen, both kinds, URL-free/same-URL distinct Entries, and existing pipeline/protocol consumers. Declare exact selected tests/counts before runs. Check large-Work selected reads and the unchanged relevant M4 duplicate/consumer budgets once at the composed boundary; report baseline failures honestly and do not launch speculative optimisation loops. No threshold/sample/assertion weakening or temporary probes in final gates.++Before the single code commit: unfiltered serialCore/no new warnings, fast, signed Mac+extension compile, test-quick for app/native changes and affected targeted synthetic phone/iPad/Mac journeys. Full unfiltered phone+iPad UI is pre-push only. Use Make, private caches/jobs2, one Asterism heavy job and fresh resource checks. Coordinate actual ownership with other projects; bounded coexistence requires their explicit agreement and healthy measured headroom. Fixture hosts must select isolated roots/mirroring off before bootstrap; bare launch tests need test-harness isolation without skipping assertions.++Risk: event/receipt reads may exceed existing budgets at library scale | Verify: early selected large-Work fixture and composed original performance selections | If wrong: stop and report the measured local regression; simplify selected reads before adding infrastructure.+Risk: incomplete arrival cannot reveal a wholly unseen invalidation | Verify: reorder source/barrier/acceptance imports and require quarantine once evidence is known | If wrong: hold the affected pair inactive, preserve text and request review; no inferred deletion.
diff --git a/specs/character-chapter-associations/device-testing.md b/specs/character-chapter-associations/device-testing.mdnew file mode 100644index 00000000..4d9beb68--- /dev/null+++ b/specs/character-chapter-associations/device-testing.md@@ -0,0 +1,47 @@+# T-2468 Devsterism device test preparation++The owner said “Let's test it on device first.” This authorizes an in-place **Development / Devsterism** installation preserving existing app data despite the recorded performance failures. It does not approve a merge, a permanent performance exception, a changed threshold, or uninstall/reset/repair of data. The inherited iPad scroll defect remains separate.++## Latest known-link feature installation, 19 October 2026++The owner requested “Deploy to my phone” and confirmed unlock. One Xcode MCP `RunProject(attachDebugger: false)` installed and launched **Devsterism 0.7.0 (1)** successfully in **11.438 seconds**. The Development build uses `-Onone`. Its source was HEAD `9f71c5dc` plus reviewed working repairs and Xcode-generated localisation metadata (`33a479c2`); the reviewed twelve-path repair was subsequently committed as `a9fe5b75` without reinstalling. Required RunProject signing refreshed signature blobs, while every byte outside the three app Mach-O signature blobs matched the preserved package. The embedded extension's signed binaries were unchanged.++The existing Development App Group library path and released Asterism installation metadata are unchanged. iOS reported a new private data-container path for Devsterism; contents were not inspected. No uninstall, reset, data-migration command or developer-account change occurred. The verified local receipt is outside Git at `../evidence/t2468-devsterism-feature-install-20261019/installation-receipt.json`. The source catalog was restored to exact `17ec40d3` bytes afterward; no build or physical-device action followed that restoration.++For the save-time matching check, use a test chapter in a work with existing, unambiguous character and place records:++- Save a note mentioning their complete known names, then open each record's **Show chapters** and verify the chapter and saved note.+- Save again without adding mentions; there should be no duplicate links. Change mentions and Cancel; stored links should remain unchanged.+- Try an accepted alias. Unknown names, embedded-word matches and ambiguous character/place spellings should not create automatic links or records.+- Remove the final supporting mention and Save. Its link should disappear; any authored **Your link note** text should remain available in **Settings → Detached link notes**.++The separate strict recovery gates passed twelve phone and four iPad journeys with zero warnings and unchanged source after restoration. Full publication, Mac authentication and performance gates remain open; this device installation grants no merge exception. Earlier deployment and measurement records below retain their original bindings.++## Earlier installation, before the latest known-link repairs+++**Devsterism installed and launched successfully** through the required Xcode MCP `RunProject(attachDebugger:false)` route in52.088s. Both previously pending approvals were verified effective; the exact worktree opened, Development was explicitly selected, and Xcode's eligible physical phone destination was matched to the current Makefile device resolution. No approval request was repeated after approval, no additional security grants/settings were changed, and no CLI signing/install fallback was used.++Installed identity: **Devsterism0.7.0(1)**, configuration **Development**, bundle `me.nore.ig.Asterism.dev`, team `V24684SCZN`, App Group `group.me.nore.ig.Asterism.dev`, CloudKit `iCloud.me.nore.ig.Asterism.dev`. Share extension `me.nore.ig.Asterism.dev.ShareExtension` grants only the development App Group, with no CloudKit entitlement. Strict signatures and embedded entitlements were verified outside the sandbox, and the existing build identity assertion passed. Development uses `-Onone`; this is not a Release performance measurement.++Exact installed candidate source: uncommitted `feature/T-2468-association-ledger`, HEAD `82d3f6df6032152525e7476827fc90de94a5ee97` plus preserved feature changes. All900 shipping Swift/project inputs match source-map SHA256 **`abd717d90e04cae2e7e2991be51f70fe66a07597024efd6acdfe9c6bfe4b93ae`** before and after deployment. It is a source fingerprint, not a new feature commit. App code-bearing `Asterism.debug.dylib` SHA256 is `300804b51e6c98868c8b5b5cc32422e72ac47fd871accf2a4d98355d1deef13e`; the receipt records all executable/extension hashes.++This was an in-place update with no uninstall, reset, fixture arguments or data repair. The development library's App Group container path stayed unchanged. iOS reports a new private app data-container path; its contents were not inspected, and no byte-identical data claim is made for normal app launch/schema upgrade. The separate released Personal Asterism's identity and complete returned app/container metadata stayed unchanged. The app was launched without a debugger for manual testing; no scripted edits or destructive data actions were performed.++Retained final correctness remains Core6304 expanded executions, fast552 and native1871 passing on the same source. No new source correctness blocker was found; the successful physical launch does not replace manual behavior verification. Full pre-push UI and full33 performance remain incomplete. Original N10 observation3.932553s and settling6.648267s each still fail2s. This deployment is device-testing authorization only: **no merge approval, permanent performance waiver, changed assertion or iPad scope expansion**.++Durable local receipt and supporting evidence (outside the feature repository, containing private device metadata): `../evidence/t2468-devsterism-install-20261019/installation-receipt.json`. The evidence manifest hashes all retained files, including source freeze, Xcode success, signed identity and before/after metadata. Historical pending preparation and its unexecuted request remain under `/tmp/t2468-ledger-build/device-development-20261018/`.++## Manual checks on installed Devsterism++Use only new test chapters/notes in Devsterism. Do not alter important existing content for this test. Extraction depends on the device's model being available; if it cannot produce suggestions, report that state rather than inventing expected candidates. Nothing is inferred from book text that was never saved as a note.++1. **Accept literal saved-note mentions for both kinds.** Save a chapter note such as “Mira arrives at Harbor. Mira carries a red map.” On the Work's reading page, choose **Look for characters and places**, then **Review suggestions** when proposals exist. Check/reclassify Mira as character and Harbor as place, then **Keep**. Reopen that chapter's editor. **Expected:** a **Chapter links** section exposes the accepted character/place rows. Reopening/relaunching retains them. Existing fact-citation sections are separate from these saved links.+2. **Known character, new chapter, no new biography required.** Save a second chapter mentioning the already-kept Mira by a known name or accepted alias; review and Keep its grounded mention even if no new fact is proposed. **Expected:** the second chapter gets its own link; saving notes alone does not silently accept a model proposal. A real chapter with no URL remains eligible; a standalone/generic note is not a chapter link.+3. **Authored link-note Save/Cancel/Clear.** In **Chapter links**, tap Mira. The **Chapter link note** sheet exposes **Note for this chapter link**, **Copy draft**, **Save**, **Cancel** and, for saved text, **Clear note**. Save distinctive text, reopen/relaunch, and verify it. Edit then Cancel: saved text stays. Clear then Cancel: saved text stays. Clear then Save: text becomes empty but chapter membership remains. Repeat a simple Save/reopen for Harbor. These controls exist in this candidate; they are not a proposed future design.+4. **Remove literal support without deleting a fact.** In the new test chapter, remove every accepted Mira spelling/alias from the saved chapter note while leaving Harbor, then Save. **Expected:** the unsupported Mira chapter link becomes inactive; Harbor stays supported. Existing authored link-note text is not destroyed. **Settings → Detached link notes** keeps detached text copyable with available original context. Recovery is offered only when a coherent current destination is available; it never auto-reattaches ambiguous text. Cancelling the source edit must leave the previously saved state intact.+5. **Skip/suppression uses existing review UI.** For a separate proposed test mention, choose **Skip** instead of Keep. **Expected:** it creates no accepted Chapter link and ordinary automatic extraction must not silently override that decision. An explicitly requested manual pass may show skipped material again under the existing manual-review policy; only an explicit Keep can reconsider it. There is no separate chapter-link “Remove” button to test: source mention removal is check4.++The character-centric “every chapter this character appeared in” browser/large-list display remains deferred. Do not look for an all-chapters list, automatic inferred story presence or automatic old-library backfill. This candidate provides reliable persisted accepted saved-note associations plus the chapter-local link-note and detached-note controls above.++Installation is verified; the manual checks above remain for the owner. No completed manual test result or merge acceptance is inferred from deployment.
diff --git a/specs/character-chapter-associations/implementation.md b/specs/character-chapter-associations/implementation.mdnew file mode 100644index 00000000..6e2369f6--- /dev/null+++ b/specs/character-chapter-associations/implementation.md@@ -0,0 +1,432 @@+# T-2468 — Implementation evidence++**Latest scoped UI acceptance:** full phone 246 passed / zero failed / two standard simulator skips on `25d23a0b…b023`; full iPad 33/33 on unchanged dependent source `efe8ac24…3992`. Root and independent review accepted both. Five UI-test driver repairs preserve every original semantic oracle; product/Core/native/Mac source remains the separately qualified b6de repair. Feature commit, push and draft PR preparation are authorized; broader performance and publication gates remain open.++## Current state++The source at 971 inputs / `b6de963d…6486` has accepted unfiltered Core (4,060 passed declarations plus 55 standard opt-in skips; 6,565 expanded executions), standard fast (456 declarations / 552 expanded passes), native quick (1,943 expanded passes), signed Mac app/extension verification, five affected iPad journeys and all thirteen Mac association journeys. The native wrapper's proven-owned post-principal helper cleanup remains qualified separately; the Mac13 run exited naturally with no cleanup. See the [scoped repair report](../bugfixes/mac-chapter-history-qualification/report.md) for exact counts, source fingerprint, warning provenance and limitations. Earlier source-specific receipts below remain historical.++The scoped product repair is preserved in `dc676a96`. Full unfiltered iPad UI then passed all 33 methods on b6de in 826.463s with zero warnings/skips/issues and natural exit0. Full unfiltered phone UI completed naturally in 9,525.721s with **241 passed executions, five failures and two standard simulator skips**. Independent source/native review accounts for all 245 declarations and 248 executions, including four actual launch variants; source stayed exact, warnings were zero and owned processes drained. The original failed result and the initial reader's launch-argument schema diagnostic are retained, not waived.++Retained native evidence supported four test-driver repairs: reveal the complete lazy Work spine before counting, scroll the UUID-ordered recovery list before reading exact text, walk the actual long review list to its controls, and let native tap operate the visible disclosure while requiring its expanded-content witness. At that stage, only four UI-test files changed; all other 967 product/test/tool inputs remained exact. Seven affected semantic journeys passed on 971 inputs / `efe8ac24…3992` in 864.299s, naturally, with no failures/skips/runtime warnings and one separately qualified inherited UI-test metadata-tool warning. Every count, exact UTF-8, 44pt control, Save/Cancel, recovery, teaching and reparse assertion remains. The complete current iPad rerun passed 33/33 in 833.333s with zero warnings/skips/issues, natural exits and exact efe8 source; its strict retained-scroll/day-reset method passed in 61.313s. The complete efe8 phone rerun finished with 245 passed, one failed and the exact two standard simulator skips across all 245 declarations / 248 executions. All five earlier failed methods passed. The new failure is the record-pill assertion in `testReviewShowsExactSavedSourceWithoutGeneratedFacts`; its earlier pass is not a waiver. The complete result and native failure attachments are retained privately. Studio transport loss left the original launcher/guard completion receipts missing, so numeric wrapper exits, hard-timeout status and continuous drain remain unverified. Separate postrun checks prove all 971 source inputs and HEAD unchanged, no relevant process remaining, and both owned simulators Shutdown; these do not replace the missing receipts. The final series-token method passed in 574.372s with retained animation-idle diagnostics.++Native video and synthesized events show the intended Ada Keep tap near the sheet header while Ada's control was above the viewport, followed by four still-pending suggestions and no accepted pill. A fifth UI-test driver repair now requires full control visibility below its owning sheet toolbar before ordinary native tap, and waits for Ada's decision row to disappear before Done. The original saved-pill, alias and no-generated-facts assertions remain. Its candidate source is 971 / `25d23a0b…b023`; all other 966 inputs remain identical to the scoped b6de product qualification, and only this one test file differs from efe8. The focused 21-journey check (19 extraction plus two outcome journeys) passed in 1,155.297s with exact source, natural Make/wrapper exit 0, no failures/skips/runtime warnings, no timeout or helper cleanup and independently accepted certain drain. One inherited metadata warning has an identical earlier tool invocation and unchanged project input; unknown warnings are zero. The original record-pill method passed in 56.424s. The complete standard phone gate on this source finished with all 245 declarations / 248 actual executions accounted for: 246 passed, zero failed and the exact two standard physical-performance simulator skips. It ran without narrowed selection or added skips in 9,591.694s, with natural Make/wrapper exit 0, no timeout/helper cleanup, certain empty process drain, zero compiler/runtime warnings/issues and all 971 inputs unchanged. The original record-pill method passed in 55.985s. Four distinct actual launch configurations are preserved from this result, rather than copied from earlier runs. Root and independent final review accepted all 19 checks and the actual native/raw inventories. Both owned simulators were already Shutdown and no restoration action was needed. The accepted efe8 full iPad result retains its original source binding: only the private CharacterExtraction test helper differs, with no affected iPad suite, shared helper, fixture or product input. Current full-phone UI acceptance is green on the new source; broader performance/publication acceptance is not claimed. Focused passes never substituted for a full gate, and both earlier failed runs remain failed historical evidence. The earlier Core/native/Mac results retain their b6de source binding and are not relabeled as full efe8 runs.++The current continuation authorizes scoped repair review and ordinary feature-branch commit, push and PR preparation. It requests no installation or merge; earlier operational authority below is historical. The required complete phone UI and both complete iPad-only suites now have accepted results on their explicitly recorded source bindings. Existing duplicate observation/settling and capture performance failures, the complete current performance inventory and broader publication review remain separate unresolved gates. No budget or assertion is waived, and no performance redesign is added here. A draft PR must state these limits and retain the earlier fixes.++### Scoped repair explanation++**Beginner:** Returning from a chapter to its Work should leave Today usable and allow the chapter editor to open again. The Mac inspector now belongs to the Today dashboard it presents. A dismissal from an older dashboard cannot clear a newly selected chapter. Wide Today also restores the saved scroll position when its view state is recreated.++**Intermediate:** The Mac presenter is inside the existing Today navigation stack; iPad retains its outside-stack presenter. A Bool adapter forwards only dismissal through the existing revision-owned UUID binding. ScrollPosition is initialized from the saved anchor; the outer wide composition is eager while the noted timeline stays lazy. Existing geometry writes and day reset remain authoritative. Platform-specific modifiers live in the existing compile-time seam, and native Mac chapter headings remain real text beside the preview button.++**Expert:** The repair changes presenter lifetime without introducing another navigation owner, path or restoration protocol. Revision checking applies to stale writes, while the binding getter stays live and transactions are forwarded. Initial saved-position state avoids replacement-view geometry overwriting the anchor before a late onAppear restore. Strict nonzero rendered tests reuse the original captured Y through Close, Work/native Back, Home and sidebar returns with the existing 2pt tolerance. The matched diagnostic does not establish universal Observation or large-day performance equivalence.++**Completeness assessment:** The affected scoped journeys and previously qualified b6de Core/fast/native checks pass; all 966 inputs outside the five UI-test drivers remain identical. Full b6de iPad UI passed; full b6de phone UI failed five methods. Seven repaired-driver journeys and both complete iPad suites passed on efe8; the complete efe8 phone gate failed one new method and has missing wrapper receipts; the fifth driver repair passed all 21 focused journeys and the full phone gate passed with independent final evidence acceptance. Ordinary spine-button activation and broader performance/publication readiness are not inferred from these checks. No additional product decision was introduced.++### Historical implementation chronology++The owner-approved note-first follow-up was being implemented at the following checkpoint. Its current source and verification status is recorded in [note-first implementation](note-first-redesign/implementation.md); the restored900 results below qualify the preceding preserved checkpoint, not the changing follow-up source. Development phone deployment for the follow-up is authorised, but remains pending completed implementation and validation.++The two-entity feature and approved save-chunk-local history repair are implemented on `feature/T-2468-association-ledger`, based on live-V20 commit `39696ad851823a235749313df92f096e68735629`. The final restored900 source passed the root-accepted unfiltered Core, unchanged fast456, signed Mac app/embedded extension build and full native quick gates. Overall verification remains incomplete: original Release budgets/full33 and pre-push full UI remain open. The inherited iPad scroll defect is tracked separately from T-2468, without an assertion waiver or pending feature contract decision. No code commit is ready or made. The prior five-entity worktree and all rejected optimization evidence remain preserved.++## Specification checks++Independent requirements peer and design critic reviewed the revised architecture. Their bounded clarifications cover narrow rejection acknowledgements, historical rebind consumption, note-independent eligibility, coherent archive restoration, same-pair recovery, exact spelling evidence and batched selected reads. Both reviewers confirmed the final contracts; no remaining must-fix or new owner decision.++Self-check: saved chapter evidence is independent of facts; a whole receipt certifies one current source/target state; retirement and note parent consumption retain history independently. For a reader, accepted chapter links survive supported routine edits and ambiguous offline links await review. For an implementer, existing review and mutation transactions own the two new tables. For a storage reviewer, immutable identities and complete historical parents validate separately from current fingerprints; no partial receipt can be composed into a new proof. Requirement groups 1–6 are traced to the nine Rune tasks.++## Verification policy++Targeted synthetic TDD first. One composed pre-commit gate: serial unfiltered Core/no new warnings, fast, signed Mac compile, test-quick and affected rendered phone/iPad/Mac checks with isolated fixture roots. Relevant original performance gates retain their thresholds, samples and assertions. Full unfiltered phone/iPad UI remains pre-push. The final composed correctness gates below have run; their acceptance does not waive remaining performance/rendered/pre-push gates. No physical install, real/shared library access, push or merge is authorized by this plan.++## Foundation slice++Source: AssociationLedger.swift, AssociationModels.swift, live V21 and frozen V20. The first RED build was blocked at the SwiftPM manifest by a default Clang cache outside writable roots (no source compiled). The corrected private-cache build reached the new tests and failed on the deliberately absent ledger API. No infrastructure failure is counted as test RED.++First GREEN: 18 pure ledger tests plus two real SwiftData V20 migration/shape tests, 20/20 passed in two suites, no skips (0.774 seconds test time). Second GREEN: 22 pure plus the two migration tests, now including cited character and place facts, 24/24 passed, no skips (0.549 seconds). These are historical slices, not the composed feature gate. Raw private build logs are retained outside the repository under the task's isolated build directory. Existing FoundationModels deprecation and NoEpisode unnecessary-try warnings were visible; no new foundation warning was observed.++An independent foundation critic found removal replay and partial acknowledgement counterexamples: a batch retirement must keep a known correctly scoped root inactive if a sibling later becomes contradictory, and an acknowledgement for spelling A must not clear spelling B in the same rejection. Additional regressions cover immutable operation-UUID contradiction/descendant propagation, holding known predecessors inactive under a later operation conflict, actual Clear replay after retirement, and exact NFC/NFD authored-byte preservation including system rebind. Those fixes remain part of the next bounded storage check.++Early scale fixture: 600 chapter identities, a 120-record directory, two accepted links per chapter. The pure fixture exercises one grouped inventory; it makes no database performance claim. The real SwiftData storage fixture adds another Work of equal size and verifies one selected Work fetch plus one batched all-physical-ID fetch, without authored-note reads. Selected endpoint read/mutation and unchanged original performance gates remain owed.++### Integration checkpoint (unverified draft)++The next checkpoint declares 45 tests: 12 repository association integration, 23 pure ledger, five physical storage, two V20 migration, three assembler mention eligibility tests. The initial integration RED reached the absent ChapterAssociationSnapshot API and executed zero tests. Two subsequent fresh resource boundaries found an unrelated Xcode UI build; no Asterism build was launched during that contention. Latest executed GREEN remains the 30-test foundation/storage slice.++Draft integrations use the existing review save, Entry note/delete/assignment, manual-entry, chapter capture/correction, reparse, re-share, record edit and Work merge transactions. The finite typed identity chain now persists historical cores and exact-text note rebinds for coherent final destinations even when literal support has disappeared; only a supported final pair receives a current receipt. Missing or torn destinations do not authorize retargeting. These drafts have not yet passed compiler or runtime checks.++Coverage eligibility remains separate from held proposal validity: whole source coverage includes matching-directory and decision changes; held proposal source guards include only current source state and source barriers. Thus deciding A does not implicitly decide or discard held B from the same unchanged chapter merely because coverage became stale. Rejections/acknowledgements conservatively leave coverage for a subsequent ordinary bounded dedup-empty pass; no immediate extra model call or eligibility rebasing is introduced. Source guards are batched values in the existing candidate read, not an additional schema or routing protocol.++### Safe checkpoint: validation pending on shared host++At the main agent's fresh 16:32:11 local resource boundary, an unrelated Meddy full UI Xcode build (PID 83332) still occupied the single-heavy-job slot; the host reported 87 running processes, 18.93% idle and load 104.65. Earlier fresh boundaries at 16:22:40, 16:27:14 and 16:29:06 also found unrelated Xcode jobs. The proposed 45-test checkpoint was **not executed**. This is a pending resource/coordination block, not an approval denial or an uncertain build outcome. No heavy process was launched by this implementation agent after the historical integration RED.++A bounded source-only follow-up adds three regressions for automatic late rejection retaining the unrelated other-kind proposal, manual old-target→new-target rejection-basis refresh, and source-barrier invalidation despite returned raw text. The next exact selection therefore declares **48** tests (12 repository + 23 pure ledger + five storage + two migration + six proposal). These three new tests and the current integration changes remain uncompiled/unexecuted. System note rebind now additionally requires exact originalContext equality; its negative-context runtime case remains owed in the note/API cohort.++Rune remains: completed utwj28a/utwj28b; in progress utwj28c; pending utwj28d–utwj28i. The current source is an unfinished implementation draft. No code commit, push, install or merge was made. Remaining work includes complete selected mutation/deletion parity and transaction regressions, authored-note/recovery APIs and publication, archive20 codec/export/import, editor/Settings wiring, synthetic rendered journeys, selected mutation scale evidence and every composed commit gate.++Resume only after a new main-agent clearance using a fresh host boundary. The next bounded command is recorded in /tmp/t2468-ledger-build/next-check.sh; raw status and changed/untracked path inventories are in checkpoint-status.txt and checkpoint-paths.txt in that directory. There are no note/archive code drafts in /tmp beyond the schema20payload scaffold already in the worktree; no later implementation is claimed.++The independent integration critic confirmed the bounded late-rejection/reroute refusal-loop source fix after the final edits. Both automatic suppression and explicit manual displayed acknowledgement semantics align with the reviewed contract; runtime validation remains pending. The checkpoint path inventories cover tracked modifications and untracked files; they include parent-owned specification edits, which this implementation agent did not overwrite.++### Resumed ownership and coordinated build queue++The owner explicitly resumed implementation and instructed this task to retain ownership through temporary resource waiting. The other build owner reserved the next heavy slot for the preserved 48-test checkpoint and confirmed that any follow-up run will wait until it finishes. Product source remains unchanged during the queue; note/archive API and regression drafts are private planning material only. A fresh host boundary is still required at handoff, followed by the 48-test compiler/runtime checkpoint and the remaining approved implementation/gates. Resource waiting is not completion or a terminal blocker.++Native dependency selection after Core integration: CharacterReviewModelTests has 42 existing unparameterized declarations, and CharacterExtractionCoordinatorTests has 41. Their 83 native app tests are outside the Core checkpoint and the Core fast cohort. Re-read source and add the new regression cases before the actual native selection; no native execution is claimed here.++### Resumed bounded compile++After the user resumed and the other project released its slot, main cleared the frozen 48-test command at the fresh 16:50:10 local boundary (71.63% idle, zero swap, pressure1, no matching heavy process). The exact script ran once and exited2 during package test compilation: AssociationIntegrationTests.swift118 omitted the existing required deleteEntry disclosedVariants argument. Production Core sources reached compilation without a concrete source diagnostic; no tests executed. The test call is corrected to disclosedVariants:nil, preserving its assertion and ordinary undisclosed-delete semantics. Raw log: /tmp/t2468-ledger-build/association-integration-green-1.log. The heavy slot was released immediately; any retry requires a new coordinated clearance and a fresh log. This is a compiler-fix iteration, not a GREEN or new RED claim.+++### Next bounded selection: 55 declarations, not yet executed++After the concrete compiler correction, the reviewed post48 counterexamples have source regressions and implementations: deterministic exact Unicode evidence ordering; known selected owner discovery even after orphan sync; global new-source/new-target coherence; full article-bearing evidence; Nova→NOVA remaining-alias continuity; failed acceptance-save atomicity; and active A+B combine→conversion with one final pair. Candidate source/target coherence uses batched endpoint reads and Work directories grouped once. Legacy fact/alias source semantics remain separate from feature mention eligibility. Runtime results are pending.++Expected suite counts: AssociationIntegrationTests18, AssociationLedgerTests24, AssociationStorageTests5, V20RecordedStoreTests2, AssociationProposalTests6 =55. Exact test names: /tmp/t2468-ledger-build/checkpoint55-test-names.json. Exact command: /bin/zsh /tmp/t2468-ledger-build/next-check55.sh (same five-suite private Make selection, new association-integration-green-2.log). Run only after a fresh main-agent resource/slot clearance. The source overlay was preserved as checkpoint55.tar, with base branch/HEAD and every changed-file SHA256 in checkpoint55-hashes.json. The overlay predates this evidence paragraph; compiler inputs are snapshotted. No55 execution or task3/4 completion is claimed.++The 55 selection was not run. Independent source review found that target coherence also belongs in the matching-directory eligibility signature: an invalid target covered by a dedup-empty pass must re-arm the unchanged source when sync removes its conflicting copy. Added a real repository regression, and both candidate eligibility and coverage writing now use the same globally coherent typed target-ID snapshot in that signature. The next selection is **56** (19+24+5+2+6); exact names/hashes/source overlay are checkpoint56-test-names.json, checkpoint56-hashes.json and checkpoint56.tar in the private build directory. Exact command next-check56.sh writes the still-fresh association-integration-green-2.log. No56 execution is claimed.++### Preserved56 runtime checkpoint++Main cleared the exact frozen56 attempt at fresh17:14:16 local (81.53% CPU idle, 3740MiB unused, 64% memory free, zero swap, pressure1; other build owners released their actual heavy work). Compiler input SHA256s matched checkpoint56. Exact next-check56.sh exited0; raw association-integration-green-2.log records **56 tests passed across five suites**: SwiftPM emitted a separate Intelligence runner summary of six tests/one suite (0.002s), followed by 50 Core tests/four suites (2.043s). No skips. This includes 19 repository integration, 24 pure ledger, five storage and two recordedV20 migration tests. Baseline NoEpisode/re-share/FoundationModels warnings remain; no new warning location is present in this bounded log. The process exited and the heavy slot was released immediately.++Task3/4 remain open for actual duplicate deletion/replay parity, additional mutation tests and native coordinator/review coverage. This checkpoint does not replace the composed checks or authorize an implementation commit. Note/archive private drafts remain outside package compilation; their API, lossless raw metadata/timestamp codec and one-lease exporter shapes are prepared for the next dependent phase.++### Post56 integration cohort and placement++The fixed fast-test manifest remains unchanged. Pure ledger/proposal suites run targeted and in fullCore; physical storage, migration, repository integration, note API and native suites remain outside fast. This is the explicit placement decision under docs/agent-notes/testing.md; no pilot expansion or unsolicited benchmark is introduced. Required fullCore and unchanged fast gates remain owed.++Independent source review identified that silent Work convergence moves Entries before deletion while record ownership had not followed. The existing explicit Work merge transfer helpers now serve the verified silent ownership transition too: characters and suppressions move by pointer, preselected places/suppressions move by Work UUID, existing citation/coverage handling is reused, and typed Work rebinds finish before that same chunk save. Selected table reads occur once per actual chunk; failed deletion chunks recapture their own current basis for per-plan replay. Coherent late children participate at the verified deletion boundary, stale plans do not route them, and no inactive root is stamped. This implements reviewed existing Work merge semantics, with no name-based record combine.++New source fixtures cover duplicate Entry deletion plus failed-chunk replay with exact authored head text; full observed Work convergence/settlement/deletion for both kinds and exact heads; coherent late children and stale-plan refusal; and repeated passes without feature-row growth. A selected real SwiftData mutation fixture declares two600-chapter Works with120records and two links per chapter; it asserts one captured grouped inventory (1200 selected events, two event fetches, three endpoint fetches), two active selected pairs, and untouched other-Work event count. Its elapsed measurement is diagnostic only, with no new budget or weakened original gates. Runtime pending.++Native review uses the current value-only coordinator ledger at final request preparation to withhold mention coverage for an unseen held sibling arriving after the sheet opens; no extra candidate read or model call. A native regression keeps window-A display fixed, adds B through the current-held seam, checks A leaves coverage unset, then checks B's own decision certifies completion. Native declarations now84 across the two affected existing suites, runtime pending.++The next source cohort additionally tests an actual failed Work deletion chunk with late active character/place children and suppressions: failure rolls back ownership transfer and exact note rebinds, then fresh replay must commit one rebind per root, correct both owner representations, preserve exact text/context and move both suppression tables. Known transaction record IDs are explicitly refetched after rollback before replay, supplementing the existing base-row refault. The grouped mutation fixture and Work suite make the next declaration count210 across ten suites (feature63 plus147 existing integration dependencies); earlier205/208/209 selections were not executed.++###210 compile correction++Main admitted the exact frozen210 no-simulator checkpoint at fresh17:27:51 local, with the other UI owner explicitly permitting this bounded coexistence and no compiler/Halo job active (50.53% CPU idle,62% memory free, zero swap, pressure1). Compiler input hashes matched checkpoint210. The Make command exited2 before test execution: AssociationDuplicateTests.swift67 passed Set<UUID> to an existing array-only ordering helper. The test assertion now passes Array(active), preserving its meaning. Production Core reached compilation; no runtime or GREEN claim is made. Raw association-integration-green-3.log remains preserved; a fresh coordinated retry/log is required.++###210 runtime result and stale-fixture correction++The corrected frozen210 retry ran under fresh main17:30:01 local admission (49.88%idle,62%memory free,1474MiBrawunused,zero swap,pressure1; the bounded no-simulator coexistence agreement remained active). Exit2: Intelligence97tests/four suites passed, Core113tests/six suites executed with two assertion issues in one new stale-plan test;209 of210 declarations passed. The stale fixture changed displayTitle on a parsed-title Work, which GroupOrdering intentionally does not count as reader-authored content (manualTitle(of:) requires manual provenance). The test now changes genericNotes, an actual authored workFingerprint component. Both existing refusal assertions remain unchanged. No production change was needed. Rawgreen-4.log retains the actual failure.++All original DuplicateReconciler56 passed, including legal boundaries and chunk/replay save assertions. Three other new Work cases passed, including both-kind/suppression ownership rollback plus exact head text/context and no repeated feature growth. The real selected mutation fixture passed and logged0.207548834s for captured update+finish+save,1200selectedevents/two event fetches/three endpoint fetches; this diagnostic is not a replacement performance budget. Native84 and remaining mutation parity remain owed.++### Note/archive RED and first GREEN source checkpoint++Focused stale-fixture retry passed4/4 tests (0.340s), raw association-duplicate-fixture-1.log. The next note/API17-declaration RED ran once under main's fresh17:36:45 bounded host admission, exited2 with zero executed tests and concrete absent note-basis/save/clear/recover/detached APIs. The compiler stopped at that primary file; V20 API absence was not independently emitted in this run. Raw association-note-archive-red-1.log is retained.++First coherent GREEN source now provides exact whole-head note basis checks, Save/Clear and explicitly selected same-pair recovery; Settings raw-variant identities frame every raw column and timestamp bits and withhold recovery for malformed scopes. Raw feature timestamps use decimal UInt64 IEEE754 bit-pattern strings for Date.timeIntervalSinceReferenceDate in format20, bypassing the released global date strategy; all raw textual metadata compares exact scalars. V20codec/snapshot/exporter retain all physical raw variants, sorted by application UUID plus framed raw-body digest. The V19 internal base projector retains its original graph/refusal checks; only the public old-format export doors reject all feature content, including barrier-only history. Current manual/background exporter factories useV20. Released older codecs/fixtures are unchanged.++Import preserves the LOCAL selected before-authority before staging incoming raw arrays; batch seed IDs extend the existing physical-copy/parent closure. Selected prospective endpoint values use shared existing newer-local/torn import predicates. Changed existing scopes that would revive known local before-inactive roots receive ordinary scoped barriers before the earliest base save; clean current incoming proof avoids artificial barriers. Complete winning fields precede final before-active carry, which filters invalid/retired/consumed roots and mutates only physical copies matching the decoded whole LOCAL before receipt. Stale variants are untouched; incoming raw variants are restored additively in the same final save if local carry changed a byte-identical preexisting copy. No per-pair history scans or new proof entities are used.++New archive controls cover clean alias/source restoration, known inactive root no-revival, later-chunk failure plus retry, full actual exporter→restore→reopen of malformed/contradictory notes and whole receipts, and before-active carry preserving incoming/stale variants without repeat growth. Additional existing API parity tests cover manual chapter update, explicit existing chapter capture and chapter→nonchapter retirement. These source changes are uncompiled pending the first feature86 checkpoint; native84, publication/UI, remaining parity, legacy current-flow test migration and composed gates remain owed. Rune3/4 remain open; task5 formal dependency remains pending.+++### Note/archive compiler iteration and next bounded cohort++The first note/archive GREEN attempt (`association-note-archive-green-1.log`, exact `next-note-green86.sh`) exited2 during test compilation, with0 executed tests. Production Core source compiled. Concrete fixture errors were two immutable comma-bound raw DTO variants and a recursively nested `#require`; those are corrected without changing assertions. The new unnecessary-try macro warning is addressed by separating the nested requires. This result is neither GREEN nor a product regression result.++The next source cohort adds exact typed authored timestamp IEEE754 equality (matching lossless raw DTO authority), an actual valid detached note from pairB refused against active pairA, and a normalization-sensitive import regression. The latter asserts actual final physical Entry notes/owners/coherence, includes an older-Work/no-write/no-barrier control, and an interrupted later chunk/reopen/retry control. Early uncertainty is limited to potentially winning, value-changing normalization inputs under the existing guards; each newly planned uncertain mutation always mints a fresh scoped barrier. The initial barrier-reuse draft was rejected before any run: an unseen receipt may already acknowledge an older barrier. The source shortcut is removed entirely, and normalization mode3 preserves the old barrier locally while withholding its old acceptance until after normalized import, then proves its late arrival remains inactive. Completed import plans naturally have no changed fields or normalization inputs, so repetition adds no metadata. No operation-provenance mechanism or per-pair history fetch is added. Source review and runtime are pending.++Next exact Make script: `/tmp/t2468-ledger-build/next-note-green89.sh`; raw log `/tmp/t2468-ledger-build/association-note-archive-green-2.log`. Selection `Association|V20RecordedStoreTests` contains89 declarations across10 suites (83Core +6Intelligence). Two parameterized declarations require inspecting every argument: existing source import `[false,true]` and normalization `[0,1,2,3]`; no skips are expected. Frozen compiler/source overlay and names use `checkpointnoteGREEN89c` in the private build directory. A fresh main-agent resource clearance is required before launch. Native84 and all later gates remain owed.+++### Core89 actual runtime and bounded corrections++`association-note-archive-green-2.log` compiled production and all package test targets, then executed Intelligence6/1suite successfully (0.002s) and Core83/9suites (6.115s), with13 issues. Both bool arguments and all four normalization modes executed; the summary counts declarations, not expanded cases. There were no skips. The failure groups were: five archive argument executions refused invalid direct-seed assignment tuples; manualChapterUpdate used the same invalid fixture; one older-Work control exposed artificial barriers during clean endpoint materialization; and the finite conversion fixture retained Ally as a supported matching key despite its claimed unsupported destination. Exact timestamp, cross-pair recovery, the other note API cases, migration, storage, pure ledger and proposal tests passed.++Direct fixtures now use the existing `applyManualAssignment` helper. The finite chain fixture starts with Alice-only source and B's Alice alias explicitly in its captured basis, then the conversion draft removes that alias; the retained Ally key genuinely lacks source support. Assertions are unchanged. The new unused injected-failure return warning is fixed with an explicit discard.++Production import correction: newly materialized absent Entry/record scopes are marked handled for the existing mutation finalizer, so it cannot add a late artificial barrier after clean incoming coherent content. Changed-existing and uncertain normalization scopes still receive their required early barriers. Incoming raw variants remain unchanged and no receipt is restamped by this exception.++Next bounded rerun is42 declarations: AssociationArchiveIntegrationTests5, AssociationNoteAPITests13, AssociationIntegrationTests24. Exact command `next-note-green42.sh`, fresh log `association-note-archive-green-3.log`; private caches/jobs2/serial Make unchanged. Core42 is expected; Intelligence0 is an intentional empty selection in this focused rerun. Full bool/mode arguments must execute, no skips. Source overlay/hashes/names: `checkpointnoteGREEN42fix` in the private build directory. Runtime remains pending, and native84/later gates remain owed.+++The focused42 correction was not run. Source review confirmed one further closure boundary: a valid unresolved pattern assignment may have a nil Work relationship while that referenced Work is absent; manual+nil+intentional is deliberate unattachment, and manual+nil+nonintentional is invalid/ambiguous. Projection now treats only the strict unresolved-pattern arm as missing metadata closure, preserving its cited assignment identity, requiring the supplied Work to have been physically absent and the exact nonowner feature fingerprint unchanged. Character closure uses absent supplied Work, nil owner, coherent exact names/retained keys/aliases and unchanged nonowner fingerprint. No incoming receipt is rewritten.++A new parameterized actual-export/import regression covers unresolved-pattern restoration for both kinds and exact note heads, deliberate manual unattachment, and invalid manual state. Positive restoration asserts original raw events/notes are unchanged; both negative controls retain detached text and inactive membership. Completed repetition must add no metadata. Next selection is **43Core declarations** (archive6 +notes13 +integration24; total feature declarations90). Script `next-note-green43.sh` writes fresh `association-note-archive-green-3.log`; snapshot `checkpointnoteGREEN43closure`. The 43 selection retains bool arguments, normalization modes0/1/2/3, and closure modes0/1/2. No execution yet.+++### Focused43 GREEN++Main ran the frozen `checkpointnoteGREEN43closure` inputs. Default sandbox attempt exited2 before compilation/runtime on SwiftPM manifest `sandbox_apply: Operation not permitted`; its diagnostics are preserved separately as `association-note-archive-green-3-sandbox-denied.log`. The approved escalated exact retry (`next-note-green43.sh`, session52991) exited0: build30.97s, **43 declarations/3Core suites passed in3.552s**. Both bool cases, normalization modes0–3 and missing-Work closure modes0–2 executed; no skips or failures. Only existing FoundationModels deprecation warning locations emitted. Raw runtime log: `association-note-archive-green-3.log`. This clears the bounded note/archive/manual-update runtime corrections, not final composed gates. Native84 remains next and unexecuted; compiler source stays frozen for it.+++### Native84 GREEN and extraction/mutation task closure++Main ran `next-native84.sh` against the frozen43closure compiler source, isolated task-owned simulatorE34807DE-B459-4DD0-807D-6E63D9BFD60D, seeded-m1 UUID temporary root before bootstrap, extraction unavailable and CloudKit/mirroring off. `native84-1.log` and `native84-1.xcresult` record TEST SUCCEEDED: **84 tests/2 suites passed in0.115s** (Coordinator41 in0.073s, ReviewModel43 in0.041s), no failures/skips/expected failures. Exact xcresult node identifiers reconciled expected84=actual84, none missing/unexpected; native build/test took approximately200s.++Task3/4 completion now combines the original valid integration API RED, foundation/storage/migration GREEN30, feature56 GREEN, expanded210 execution with the stale fixture corrected in focused4/4, newly covered manual/chapter capture/correction and note-chain boundaries in focused43 GREEN, and exact native84. Selected large-Work mutation inventory/query evidence and duplicate Work/Entry chunk/rollback/replay assertions remain preserved; original budgets/samples/assertions are unchanged. Source parity audit covers capture/manual/reparse/correction/re-share, record editing/conversion, explicit Work merge and duplicate convergence/deletion/replay hooks. Full original affected consumer suites and composed unfiltered/fast/Mac/quick/rendered/performance gates remain owed under task9; no final phase-green or commit claim is made. Rune IDs utwj28c and utwj28d are completed, utwj28e now in progress for remaining publication/provider/mock tests.++Private editor review corrections are prepared before source integration: field Clear stages an intent and only terminal toolbar Save writes; Cancel remains zero-write. Destination heads are exposed even when a single text/Clear head is about to be consumed during recovery or explicit latest-basis review. Initial async load gates editing; independently decodable raw original context remains visible despite unrelated malformed metadata. No private UI draft has compiled or executed yet.+++### Publication/editor RED source unit++Added test-only source and mock recorders after native84: Core AssociationPublicationTests2 expects the missing defaulted EntryTeachingDetail chapterAssociations value to contain both kinds independently of fact citations and to change on metadata-only contradiction while preserving chapter/facts/raw text. Native editor10 +detached-context1 +publication4 =15 declarations cover the reviewed Save-terminal/Clear/Cancel, exact Unicode, refusal/failure, load-disabled, single destination text/Clear head exposure, raw context, same-lock initial values, narrow draft-preserving refresh, canceled stale read and zero-effect arrival publication contracts. Both new model types and the DTO/model publication seams are intentionally absent at this RED boundary. No new shipping source is introduced in this unit.++Exact next serial commands: `next-publication-red2.sh` -> `association-publication-red-1.log`, then separately admitted `next-native-association-red15.sh` -> `native-association-red-1.log`/fresh xcresult and a fresh seeded UUID temporary root. Both expect concrete API absence compile RED with0 runtime tests; distinguish fixture errors and infrastructure from valid RED. Private caches/jobs2/Make remain unchanged. Test names and source overlay/hashes use `checkpointpublicationEditorRED` in /tmp/t2468-ledger-build. Broader production UI integration remains behind this meaningful RED boundary and a subsequent coherent GREEN source snapshot.+++### Publication/model/views coherent GREEN source unit++Core publication RED2 exited2 before runtime on the concrete missing EntryTeachingDetail.chapterAssociations property (`association-publication-red-1.log`). Native RED15 exited Make2/Xcode65 with0 tests, primary missing AssociationNoteEditorModel/DetachedAssociationNotesModel in the first new test file, with derived inference diagnostics. Compiler stopped there; this does not claim all15 bodies typechecked or native EntryDetail absence was independently emitted.++The GREEN source adds a defaulted EntryTeachingDetail chapterAssociations field built by the existing selected association reader in the SAME locked Entry detail context. EntryDetailModel publishes those initial values without a second read, and generation changes perform a narrow, cancellation-guarded association read that preserves chapter drafts. The view's generation task loads chapter data only initially; canceled old initial reads cannot overwrite the latest generation. The new regression makes native publication5 rather than4. Editor Clear stages intent, Cancel never writes, terminal Save writes once, exact Unicode dirty checks use ExactScalarString, loading disables edits, and single text/Clear destination heads are exposed during recovery/latest review. Detached Settings values refresh with snapshot generation, retain stable raw-variant identity and independent raw context, and offer recovery only for coherent eligible same-pair heads. Raw text/drafts have explicit exact clipboard actions. Existing fact citation sections remain separate.++Next serial, separately admitted commands: `next-publication-green2.sh` (Core2, fresh association-publication-green-1.log), then `next-native-association-green174.sh` (174 declarations/12 suites, fresh native-association-green-1.log/xcresult, fresh seeded UUID temp root and dedicated task simulator). Native selection includes new editor10/context1/publication5, EntryDetailModel40, DuplicateSurface32, all FIVE embedded WorkDetailCharacter consumers47, SettingsBackupModel23 and AppLibraryModelBackgroundExport16. Exact native names are checkpointpublicationEditorGREEN-native-test-names.json; every parameter case and no skipped/missing tests must be reconciled. Source overlay/hashes use checkpointpublicationEditorGREEN. No GREEN execution yet; rendered journeys/fixture integration and composed gates remain owed.+++### Publication/editor GREEN and rendered-fixture RED boundary++Main ran frozen checkpointpublicationEditorGREEN. Core publication2 passed0.149s (build40.23s), raw association-publication-green-1.log; only prior FoundationModels warnings. Native next-native-association-green174.sh exited0 TEST SUCCEEDED: **174 declarations/12 suites passed1.347s**, xcresult174 pass/0fail/0skip/0expected failures. Exact declaration ID reconciliation expected174=actual174, none missing/unexpected. All12 parameter Arguments nodes passed, including all3 refusal outcomes. Raw native-association-green-1.log/xcresult and summary/tests JSON retained. Warning locations match preexisting native84; new editor/publication/model/view files emitted none. Independent requirements peer reviewed actual source and confirmed staged Clear/terminal Save, loading gate, single destination head exposure, independent malformed raw context, same-lock publication and chapter-draft-preserving refresh; no bounded blocker.++Together with the valid note API RED, Core89 passing codec/pure/storage/migration cases, focused43 corrected archive/API/integration GREEN and native174 provider/manual-background export consumers, tasks5/6 are complete. Full unfiltered Core, Empty Library and remaining current-flow consumer suites and composed gates remain owed under task9. Native editor10 plus context1 and publication5 already run; task7 now adds rendered fixture/journey coverage.++Test-only renderedFixtureRED adds AssociationJourneyFixtureTests2 for both-kind membership, detached same-pair recovery, malformed raw copy-only text, exact edit preservation on relaunch and foreign-library refusal. UITestLaunchSupportTests adds the explicit seeded-association-notes UUID-contained/no-CloudKit scenario. The seeder/constants/scenario are intentionally absent: next focused Core2 expects absent API compile RED/0 runtime. Native scenario absence is source-only until its separately admitted run. Compiler overlay/hashes checkpoint renderedFixtureRED; exact script next-rendered-fixture-red2.sh writes association-rendered-fixture-red-1.log. No rendered or full phase acceptance is claimed.+++### Rendered fixture/harness GREEN source checkpoint++Fixture RED2 exited2/0runtime with concrete missing seedAssociationNotesFixture and associationFixtureChapterID diagnostics in the first test file (association-rendered-fixture-red-1.log). Native scenario absence was not independently executed.++The coherent source now adds a DEBUG-only URL-free fixture, with fixed synthetic application IDs inside the UUID-resolved temporary root. Only a completed marker plus known Work/chapters allows same-root relaunch; unrelated or partial nonempty libraries fail closed. Normal acceptance/Save/update APIs produce both kinds, an old detached same-pair note and a fresh active destination note. Direct debug-only raw setup adds two concurrent Place heads, one valid missing-endpoint note and an independently scoped malformed raw note with decodable context. The malformed note has a different missing Work UUID so its invalid scope cannot poison writable normal chapter bases. Fixture tests perform a real Save beside the raw variants and compare full raw/base snapshots across reseeding.++AssociationNotesUITests adds3 cross-platform methods: Save/Cancel/stagedClear/terminalSave/reopen/same-rootrelaunch/bothkinds+conflictresolution; explicit recovery with single current destination head visible before Save and Cancel preserving detached text; malformed/missing-endpoint text/context/copy-only versus one eligible recovery. Each XCUIApplication launch configures scenario+UUID+unavailable extraction beforehand; each eventual Make command will independently configure TEST_RUNNER root env before possible test-host bootstrap. CloudKit remains nil in the existing launch resolver. Bare example, launch screenshot and launch-performance iterations now use fresh synthetic UUIDs before EVERY launch; metrics/assertions/screenshots remain.++Native Mac harness uses an explicit macosx-only exclusion list of36 existing mobile journey/helper source files; simulator membership and all pre-push selections remain unchanged. It includes the new cross-platform journey, isolation helper and original bare launch suites; no product target is added. Selected fixture Core2 and native launch-validation15 are next, scripts next-rendered-fixture-green2.sh and next-native-association-launch15.sh. Compiler overlay/hashes checkpointrenderedFixtureGREEN; exact selected names in its selected-test-names.json. Rendered journeys and task7/8 acceptance remain pending actual runs.+++### Durable late-settlement counterexample and regression boundary++Fixture GREEN2 passed2/2 in0.196s (build155.12s), association-rendered-fixture-green-1.log. The new fixture test file now shares its helper's DEBUG guard so original release M4 test compilation does not reference absent debug APIs. Approved tooling adds build-only XCODE_BUILD_FLAGS to signed build-mac (its release alias reuses the recipe) and forwards existing SWIFT_TEST_FLAGS through test-performance-m4, preserving every filter/sample/assertion/threshold. No original benchmark fixture is changed.++Independent review found a concrete remaining integration race: currentHeld is sampled before awaiting commitDecision; B can settle afterward while A accepts an existing unchanged target, allowing A to persist source coverage while B exists only in RAM. A later manual pass over an already-covered unchanged source exposes the same durable gap without concurrency. Source serialization alone is insufficient. Rune3 is reopened in progress,4 pending,7 paused; exact IDs preserved. Earlier GREEN evidence remains historical, not final integration acceptance.++New native AssociationCoverageRaceTests2 uses actual UUID temporary Core repositories, normal record/chapter creation, a stub model and gated actual decision forwarding. The parameterized race covers both A-save/B-settlement orderings after A prepared completion, asserts A membership survives and B stays eligible in a fresh repository. The manual control first proves A genuinely covered the unchanged source, then discovers B, reopens, submits an empty model answer (which must not clear known pending B), reproduces B and explicitly accepts it to permit current-basis certification. No model call is live; original source/target matching is unchanged. This is an assertion RED against current source, not a missing new API. Script next-native-coverage-red2.sh, fresh native-association-coverage-red-1.log/xcresult, dedicated phone/privatecache/jobs2 and fresh TEST_RUNNER UUID. Two declarations/three argument executions expected; runtime pending.++Reviewed remedy is minimal source-scoped coverage-only pending key inventory and UUIDs in the existing event table, persisted before held publication, with explicit Keep/Skip acknowledgement in the same decision save. Pending bookkeeping is excluded from stable coverage BASE, membership receipts and sourceGuard; produced-none cannot acknowledge current-base pending. Genuine source/matching/base changes leave old rows retained but nonblocking. Rebase only completion metadata when original basis still matches; never evidence/sourceGuard. Detailed GREEN source remains pending meaningful race RED and final review of these boundaries.++### Coverage race RED and frozen pending-review GREEN checkpoint++Main executed native-association-coverage-red-1.log/xcresult: two declarations, three argument executions, seven expected runtime assertion issues in0.618s. Both A-save/B-settlement orderings failed current/reopened eligibility (four issues); already-covered manual discovery, reopen and restart→empty failed (three issues). Actual A acceptance, held B, unchanged source, saved membership and eventual explicit B certification controls passed. This is a reproduced durable gap, not an API/compiler failure.++The frozen coverageGREEN unit persists minimal original source guard/key/typed target selection/spelling keys before publishing held mentions, using the existing raw event table. Keep/Skip acknowledges only captured marker/key references in the decision save. Pending relevance is separate from coverage-directory eligibility: unrelated directory churn or harmless target rename cannot expire B; missing/torn endpoints remain review-needed. Positive coherent support loss or an actual guarded source revision can stale that original key. Produced-none never acknowledges pending keys. Completion rebasing changes only metadata when the captured original coverage BASE still matches. Membership, sourceGuard and legacy fact coverage exclude pending bookkeeping.++An exact Keep witness permits only redundant settlement: referenced immutable original guard/key/target selection/spelling set must match, the actual committed kind/ID must agree with a known original target (nil permits a newly created target), and a current active whole receipt must cover every original spelling. Skip supplies no witness; cross-kind satisfaction is conservatively excluded. Explicit captured-key acknowledgement still supports reclassification. The generic routing refusal now precedes association preflight and both precede the first mutation; Skip behavior is unchanged. The design critic confirmed these bounded source checks, including live Work endpoint visibility in the registration/coverage writer batches; no build by reviewer.++CheckpointcoverageGREEN compiler sources are frozen for parent-run sequential verification. next-coverage-core-green.sh selects126 declarations: pending10, repository integration24, pure ledger24, storage6, assembler33 and extraction ledger29. Pending parameters include all4 explicit decisions,6 relevance states,3 physical-conflict states and6 exact-witness states; independent raw known-target contradiction and removed-alias reroute/no-write controls remain. next-coverage-native-green102.sh selects race3, review43, coordinator41 and launch validation15. Exact selected names and compiler hashes are in checkpointcoverageGREEN-core/native-test-names.json and checkpointcoverageGREEN-hashes.json. All new native/rendered scripts use public -collect-test-diagnostics never while retaining xcresults, screenshots, assertions and selectors. Actual GREEN/runtime remains pending; Rune3/4 stay open and rendered7 paused.++Current production Settings export consumer IntegrationSafetyNetTests.everyGateUsesOneCapabilityValuePerEnvironment now decodes format20/schema21 while retaining its capability assertion. Historical direct-format compatibility controls remain unchanged; this native method is owed in composed test-quick. The fixed fast manifest remains unchanged; new pure suites run targeted/full Core, storage/API/native suites remain outside fast under the reviewed placement decision.++Parent-run Core126 attempt exited2 after build157.64s: Intelligence62/2 suites passed0.010s; Core64/4 suites executed4.922s with exactly one issue, differing-target witness mode2 expected an explicit decision but its two canonical Bryn names legitimately triggered existing rerouting. The other125 declarations and all other pending controls, removed-alias reroute and contradictory-known-target checks passed. Selected600-chapter storage diagnostic0.2019105s with unchanged query/count assertions. This is fixture ambiguity, not production witness failure. The correction changes only the different target's canonical name to Other with accepted alias Bryn, leaving original Bryn the stronger canonical route and preserving the intended supported-but-different-target pending assertion. Frozen checkpointcoverageGREENfixture2; next-coverage-core-pending10.sh reruns only pending10 (25 argument executions), fresh association-pending-green-2.log. Native102 remains owed.++Focused pending10 fixture retry passed10/1 suite in1.317s, all25 argument-expanded cases/no skips, association-pending-green-2.log. Parent then admitted native102 against the corrected frozen compiler unit; runtime remains pending. The sole126-run failure was corrected without assertion changes or production changes. Prepared only (not executed): next-composed-core.sh unfiltered serial CORE_TEST=; next-composed-fast.sh unchanged manifest; next-composed-quick.sh full native bundle retaining signed build-mac prerequisite and separate jobs2 build/test flags, dedicated phone/private caches, explicit synthetic TEST_RUNNER UUID before bootstrap. Exact original dependent M4 source inventory is original-m4-dependent-selection.json (Scale15, ToleratedScale10, DuplicateScale7); original budgets/samples/assertions and released exporter benchmark fixtures remain unchanged. All remaining gates require fresh parent resource admission.++Native102 completed0/TEST SUCCEEDED:102 declarations/4 suites passed0.661s, xcresult102 pass/0fail/0skip/0expected. Exact declaration reconciliation102/102, none missing/unexpected/nonpassed; all9 parameter Arguments nodes passed (108 expanded cases). Both race save orderings, already-covered manual→restart→empty→explicit decision, and failed durable marker publication controls passed. The current source therefore closes the reopened extraction/mutation coverage gap; Rune3 utwj28c and4 utwj28d are completed again with exact identifiers preserved. Task7/8 remain incomplete pending rendered phone/iPad/Mac results. Main proceeds selected rendered journeys on this frozen compiler unit before broad gates. No commit/push or device install occurred.++### First rendered phone attempt and bounded Form-scroll correction++Main ran phone3 against frozen coverageGREENfixture2: malformed/missing-context copy journey passed19.499s, recovery passed30.114s; Save/Cancel/Clear/relaunch journey failed24.886s at its FIRST chapter-link button, which existed but remained unhittable after ten app.swipeUp attempts. Raw association-ui-phone-1.log/xcresult retains all three executed methods; no compile failure. All attachments were exported to phone1-all-attachments (native metadata incorrectly marks failure associations false, so an only-failures filter was empty). Main retained the failed recording and UI Snapshot plists.++The actual repeated swipes plus UIJourneySupport.swift289–305 establish the existing nested TextEditor trap: screen-center app.swipeUp scrolls the editor, not EntryDetail's Form. The new mobile helper now uses the existing bounded below-editor drag from(0.5,0.85) to(0.5,0.25). Mac scroll branch and every journey assertion remain; an explicit kept screenshot is added before the same unreachable-control assertion on failure. No product change. Frozen checkpointrenderedPhone2; next-association-ui-phone3-retry.sh selects the same3 methods with fresh association-ui-phone-2 log/xcresult. iPad/Mac and broad gates remain owed.++Phone retry2 again executed all3: malformed/context19.328s and recovery31.184s passed; Save/Cancel journey40.263s failed the unchanged first-link isHittable assertion. Kept screenshot267F5263-101A-4481-A46D-A4E5F159182C.png shows Alice/Saved arrival note and Harbor rows fully visible without keyboard/overlay: the outer Form now scrolls, but hit-testing/query semantics remain unresolved. Button/Form source has no disabled gate for this row. No reachability assertion is bypassed.++Frozen checkpointrenderedPhoneDiagnostic adds failure-only target enabled/frame/debugDescription, all same-ID Button variants and full synthetic accessibility-tree text plus screenshot attachments. next-association-ui-phone1-diagnostic.sh selects ONLY the failing method with fresh host UUID/result paths, retaining the existing navigation and assertions; no additional drag attempts, coordinate tap or product change. Actual diagnostic execution remains pending parent admission. The two repeatedly passing journeys remain evidence, not a claim that rendered gates are complete.++The focused diagnostic failed1/1 in39.221s and supplied the missing hit-test evidence: one enabled Button, outer frame(16,546.7,370,68.7), no duplicate/overlay, narrow text-only children at x32 widths37.3/101.3. The outer accessibility-frame center x201 lay outside the VStack label's real content. The new label lacked both the full-width frame and rectangular content shape already paired in TodayView recent rows, WorksView unattached rows and WorkDetailView. The bounded product correction reuses only `.frame(maxWidth:.infinity,alignment:.leading).contentShape(Rectangle())` on the chapter-link label, aligning the actual hit region with its rendered/accessibility row. Button semantics, label, editor routing and all strict hittability/Save assertions remain. No coordinate bypass. Frozen checkpointrenderedPhoneHitShape; next-association-ui-phone1-hit-shape.sh reruns only the failing method with fresh UUID/log/xcresult association-ui-phone-4-hit-shape. Runtime pending.++Hit-shape focused attempt failed1/1 in41.218s, the same first-row predicate; widening the label was not a sufficient cause/fix. Parent invoked the current systematic-debugger skill (overview→inspection→root cause→verification); worker read the same skill and stopped product/style edits. Source inspection identified preexisting full-body DEBUG columnMarker (EntryDetailView105→ListDetailPane163–168→UITestMarker88–93), exposed as an accessibility element without hit-testing exclusion. intentEditSession only registers state; no source overlay there. Marker/AX interference remained a hypothesis.++Controlled5 retained the ORIGINAL wasHittable assertion, compared existing controls and attempted only ordinary element.tap. Actual1/1 failed54.245s as intended: Move/Delete and Alice StaticText all enabled=true but isHittable=false, while a normal tap opened the real link editor showing Saved arrival note, whose TextView is enabled/hittable=true. This disproves a solely local custom-label failure and distinguishes accessibility reporting from actual sheet routing. No coordinate action or assertion bypass. The shared DEBUG background marker is now a stronger but still unproven cause; WideRootView242 supplies a preexisting decorative-marker allowsHitTesting(false) precedent. No further product change until the parent-directed controlled experiment. All diagnostics/raw xcresults are retained.++Marker-only experiment also failed1/1 in54.367s with identical false predicates and successful normal editor opening, falsifying the proposed marker cause. Its only experimental modifier is removed (ListDetailPane has no diff). The systematic conclusion is narrower and proven: this new helper incorrectly required isHittable for normal element activation on this runtime, while unrelated existing visible enabled controls also report false. Existing EntryToWorkLink journeys use wait-for-existence followed by standard typed Button.tap.++Parent and independent critic approved correcting only that test oracle: wait for the control, assert enabled, use ordinary native tap/click and let it scroll its cell. No coordinate tap, ID allowlist or repeated gesture loop. Every meaningful editor-open/load, Save/Cancel/Clear, exact UTF8 text, relaunch, both-kind/conflict and recovery assertion remains. Failure-only screenshot/full-tree capture now covers missing/disabled controls and expected editor/load/close states rather than performing a diagnostic tap. Frozen checkpointrenderedPhoneNativeAction; next-association-ui-phone1-native-action.sh runs only the complete formerly blocked method, fresh association-ui-phone-7-native-action results. Actual behavior verdict remains pending.++Native-action complete journey progressed past navigation/load/Cancel/reopen, then failed1/1 in43.097s on exact reopened text: actual input was decomposed Café reader note followed by Saved arrival note. Normal tap had placed the caret at the start, so backward deletion removed nothing; the persistence path preserved the actual draft. The replacement helper now asserts exact UTF8 immediately before Save to distinguish input-driver failures from persistence failures.++A native Select All candidate checkpoint was preserved UNRUN. Parent chose the smaller established ChapterNotesUITests309–315 one-line driver: explicit caret placement at normalized(0.98,0.5), then backward replacement. This is deliberate text-caret placement, not forced activation of an unreachable control. No selection-menu fallback, clipboard injection or product mutation. Mac Command+A remains. Frozen checkpointrenderedPhoneCaret; next-association-ui-phone1-caret.sh runs the same complete method, fresh association-ui-phone-9-caret result. All later exact text, Cancel, staged/terminal Clear, relaunch, both-kind and conflict assertions remain.++Phone9-caret completed0/TEST SUCCEEDED: the full formerly blocked Save/Cancel/staged-and-terminal Clear/exact UTF8/relaunch/both-kind/conflict-resolution method passed111.550s, exact1/1/no skips. The immediate exact draft assertions passed before Save. Marker experiment diff remains empty; reviewed standard native-action oracle remains. Final composed rendered selections are now iPad5 (new3 plus original WideLayout rating-save and inspector-edit2), phone29 (all original26 plus new3 on one coherent source, no redundant separate phone3 run), and native Macnew3 after fresh no-unrelated-Development-app process check. Prepared only: next-association-ui-ipad5.sh and next-affected-ui-phone29.sh with exact selected identifier JSONs. Runtime/platform gates and tasks7/8 remain incomplete until their actual results.++First combined iPad5 executed exact5/5/no missing/unexpected/skips: malformed/context19.591s, recovery25.931s, existing inspector-edit16.698s and rating-only Save29.676s passed. New Save/Cancel journey failed29.655s waiting for the compact work-title route. Source confirms wide Today rows open an inspector (AppScreens99), whose Edit action calls showTodayEntry (WideRoot268); the original passing Wide913–918 follows that route. The new helper now waits for either actual destination, follows the observed inspector's normal Edit action when present, then retains the work-title assertion and adds actual chapter TextEditor presence. No product change. Frozen checkpointrenderedWideRoute; next-association-ui-ipad1-route.sh reruns only that method with fresh association-ui-ipad-2-route results. Four other passes remain explicit evidence, not a green initial5 claim.++Focused iPad wide-route retry completed0/TEST SUCCEEDED: exact1/1/no skips/missing/unexpected/nonpassed, full Save/Cancel/Clear/relaunch/both-kind/conflict journey118.282s. Together with the other4 passes from the initial iPad5 attempt this covers the selected5 across source-qualified runs; it is not a claim that the initial combined5 was green.++Before Mac admission, read-only source showed ContentView893–895 deliberately omits the mobile Settings row on Mac. The new test helper now uses the real native Command+, Settings action on Mac and keeps the mobile button unchanged, then retains the recovery-row/editor behavior assertions. No product change. Frozen checkpointrenderedMacSettings; next-association-ui-mac3.sh selects exact3 with fresh host UUID/private Mac DerivedData/diagnostics-never/result paths. Parent will freshly verify no unrelated Development app process before launch; Mac3 remains unexecuted at this boundary.++### Native Mac infrastructure boundary++Mac3 build/sign completed, but the runner initialized zero test methods: XCTest.XCTFuture Code1000, Timed out while enabling automation mode (association-ui-mac-1.log6309/6322,20:21:26 local). The requested3 journeys are therefore NOT executed or passed; this is a runner prerequisite outcome distinct from source/behavior results. Raw log/xcresult retained. Repository AGENTS/docs/scripts/Make search found no automation-mode prerequisite procedure. Read-only DevToolsSecurity -status in the default sandbox exited255 with Failed to get right definition for system.privilege.taskport.debug; the developer-mode status remains unknown, not inferred disabled. No OS setting, privacy rule, retry, personal app launch or device install was changed/performed. Parent can inspect minimized interactive-session/locked state and escalated read-only status before deciding any supported next attempt. Mac behavior gate remains blocked/pending while independent composed Core/fast/native/performance work proceeds.++### Composed Core consumer closure (source prepared; runtime pending)+The first unfiltered Core gate reported 3,410 declarations across 322 suites with 58 issues (55 opt-in performance declarations explicitly skipped); other package runners passed 42/304/235 declarations. Full evidence: `/tmp/t2468-ledger-build/composed-core-1.log` and `composed-core-1-failure-inventory.json`. Corrections retain V20 alongside live V21 in exact frozen schema/blob/membership inventories and five retained stages, update current store/marker and supported archive-pair expectations, and migrate only current chapter/empty-library/copy round trips to format20/schema21. Released codec/predecessor fixtures remain released. Empty/restore retains exhaustive base-record assertions and additionally compares current authored records, sources, raw events and notes. The deletion count explicitly expects its one source barrier, including zero-link deletion. Clipboard copying uses the existing RuntimePlatform seam; no platform allowlist expansion.+Legacy fact-only decision fixtures now explicitly assert the fact fingerprint saves atomically while chapter associations remain uncovered without a captured feature completion basis. The subsequent current bounded produced-none completion certifies both kinds together; no unseen post-create matching basis is certified by a legacy request. The per-revision produced-none fixture now submits the actual captured current completion value.+Next focused checkpoint: 16 affected files, 21 suites, 306 source declarations (parameter expansions verified at execution), `/tmp/t2468-ledger-build/next-composed-closure306.sh`; source names in `composed-failure-closure-selected.json`. This preparation does not claim a passing gate. Native Mac rendered runner remains an infrastructure zero-case failure (automation-mode timeout); no OS settings changed.++Focused compatibility closure runtime: `composed-core-closure-1.log` exited0, build108.50s, 306 declarations/21 suites passed27.988s, zero issues/skips. The exact source test-title/suite multiset reconciliation is `composed-closure306-reconciliation.json`: expected=started=passed306; 21/21 suites; no missing, unexpected or unpassed declarations. Parameter-case start lines are excluded from declaration counts. Warning locations match the previously recorded baseline. Parent launched a fresh unfiltered Core retry with XML output; its result is pending, with compiler inputs frozen.++Unfiltered composed Core retry `composed-core-2.log` exited0: Core reports3,410 declarations/322 suites in183.484s (55 opt-in performance declarations explicitly skipped), ConstellationKit42/8 in.048s, Presentation304/20 in.103s, Intelligence235/14 in15.096s; build.56s, no compiler warnings. Complete source/log multiset reconciliation across all package test targets:3,991 declared titles =3,936 started/passed +55 explicitly skipped;364 declared suites =353 started +11 explicitly skipped; no missing/unexpected/unpassed titles or suites. Evidence `/tmp/t2468-ledger-build/composed-core2-reconciliation.json` and reproducible `reconcile-full-core.py`. Both unnamed suites are included. SwiftPM accepted xunit-output but emitted no XML on this Swift Testing path; all reconciliation uses the retained raw log, with no XML claimed. Relevant original dependent M4 gates remain separate and owed. Fixed fast is now running under parent admission, source frozen.++Fixed fast gate `composed-fast-1.log` exited0 with its unchanged456-identifier manifest: Presentation304/20 passed.099s and Core152/12 passed.484s. No manifest additions or replacement tests. Full native quick, including signed Mac app/embedded-extension prerequisite, is active under parent admission; outcome pending. Correct package identities for the full Core gate are ConstellationKit42, Presentation304, Intelligence235, Core3,410 (the earlier parent label mismatch is corrected here; counts/outcomes unchanged).++Native quick prerequisite: signed Mac app and embedded Mac share extension compiled successfully on current source; full phone test bundle compilation/runtime remains in progress. Light warning audit captured17 unique Swift file/line/message locations in `native-quick-warning-provenance.json`; every location has the same file/message in retained earlier native logs and its exact emitting expression remains unchanged in baseline39696ad. Includes inherited NoEpisode unnecessary-try, FoundationModels deprecations, and existing test actor/capture/macro warnings; no inherited warning cleanup or threshold waiver. Final audit awaits complete native log.++Full native quick first attempt completed all1,784 declarations/128 suites in35.480s:1,782pass/2fail/0skip, with120 argument nodes. The only failures were current real-record/export and fill-into-empty flows in IntegrationSafetyNetTests still calling the released V18 exporter after their moves created required feature barriers. Only these two flows now use V20, preserving every real-record, relationship, exact-note and extension-readiness assertion. Remaining historical/released exporter controls are unchanged. The current-format fill test display title is corrected; its stable method ID remains unchanged. Next focused whole-suite selection has17 source declarations, `next-native-integration-current.sh`, followed by unfiltered `next-composed-quick2.sh`, both fresh result/log/UUID and diagnostics-never.+Source-inventory ownership correction only: AppNavigationTests.swift1646/1663 explicitly extend AppNavigationTests; diagnosedEntryClearsTheStack and diagnosedCaptureLeavesItsListing belong there, not the preceding AppNavigationTodayTests struct at1140. Both expected JSON inventories corrected without product/test mutation. Initial result reconciliation mismatch remains preserved for provenance.++Focused current-consumer native retry `native-integration-current-1.log` reports17 tests/1 suite passed3.333s and TEST SUCCEEDED. The two prior failing real-record and fill/readiness round trips now pass with all semantic assertions retained. Parent has started the fresh unfiltered quick2 invocation; compiler inputs remain frozen, no additional product or test changes.++Full unfiltered native quick retry `composed-native-quick-2.log` reports1,784 tests/128 suites passed38.396s and TEST SUCCEEDED, with the signed Mac build prerequisite preserved. Parent result-bundle exact identifier/argument and warning reconciliation follows separately; raw runtime diagnostic messages are not recast as test failures. The final combined phone29 run is now active; no source changes or independent heavy launch.++Quick2 parent xcresult reconciliation confirms1,784/1,784 passed,128 suites, all120 Arguments nodesPassed, zero skips/expected failures; no missing/unexpected/nonpassed source IDs after the documented extension ownership correction. Signed Mac/embedded appex succeeded again. Original M4 selection source audit (`original-m4-33-source-consistency.json`) confirms exact33 declarations: Scale15, Tolerated10, Duplicate7, Empty1; all four original source files byte-unchanged against baseline39696ad. Script retains release/no-parallel/performance define/RUNS1/default CONTROLLED semantics, all original median ceilings/assertions and sample counts, and reports p95; only supported private cache/jobs2 flags are forwarded. No performance run initiated by worker.++Phone selection ownership correction (active run unchanged): the initial29 claim was incorrect because CharacterExtractionUITests.swift813 declares a second XCTest class, CharacterExtractionOutcomeUITests; its two methods at841/858 were assigned to the preceding class. The active script therefore selects27 actual methods, not29. Preserve its raw script/result plus every initial JSON (`*-initial.json`); exact active manifest is `affected-ui-phone27-active-expected.json`. Corrected intended29 manifest assigns those methods to their real class, with focused whole Outcome2 script `next-affected-ui-phone-outcome2.sh` and fresh result/log/UUID prepared, not launched by worker. Full audit of all selected UI ownership found no other selected mismatch; iPad2/combined5 unchanged. The broader original-method inventory additionally misassigned three unselected wide-accessibility methods, now correctly owned by WideLayoutAccessibilityUITests (1552/1560/1590). Audit proof: `affected-ui-ownership-audit.json`, including source lines. No test/product source or assertion changes. Intended coverage will be reconciled honestly as27 plus2 across runs, without repeating unchanged27.++Final combined phone actual27 selection passed1,668.793s,27/27, zero failures/skips/missing/unexpected/nonpassed IDs; raw `affected-ui-phone29-1.log/.xcresult` retain their original misleading prefix, corrected summary/ID evidence is `affected-ui-phone27-1-*.json`. Outcome2 is separately active under parent fresh admission. Current host admission records65% memory free/5.4GB raw unused/pressure1, zero current swap rates; existing swap allocation766.88MiB remains and is not described as zero swap.+Light frozen diff inventory: `/tmp/t2468-ledger-build/final-frozen-diff-review-inventory.json` records117 modified tracked +41 new =158 paths, grouped by production/Core/Intelligence/app/test/harness/spec scope with SHA256 and line counts; `final-explicit-path-inventory.txt` provides explicit paths only. Parent-owned CHANGELOG/OVERVIEW/AGENTS/design/decision files are identified for coordination; worker has not staged/committed anything or touched CHANGELOG. Branch remains feature/T-2468-association-ledger, HEAD82d3f6df. diff --check clean. Rune utwj28a–utwj28f remain complete; utwj28g in progress, utwj28h/utwj28i pending because required rendered Mac gate is infrastructure blocked and original M4 gate is pending. No implementation commit until required gates are satisfied.++Focused Outcome2 `affected-ui-phone-outcome2-1.log/.xcresult` passed2/2 in63.612s, zero failures; parent combined source-qualified ID reconciliation confirms exact29/29 intended phone methods across27+2 runs, no missing/unexpected/nonpassed/skips. Original33 M4 selection is now active under parent admission on frozen source:61% memory free/pressure1,766.88MiB allocated swap with zero current rates. Default CONTROLLED empty preserves the original median gate and p95 reporting; this is not a controlled-p95 or quiet-host claim. Both owned simulators are Shutdown. No worker heavy launch, source edit, staging or commit.++Release compile warning provenance refreshed during M4 build:25 unique warning origins across six unchanged files; every emitting expression and entire containing file is byte-identical to baseline39696ad. The six files are ConstellationSelectionRecipesTests, LibraryRepository+NoEpisode, both FoundationModels clients and their test files. `m4-release-warning-provenance.json` records macro-origin real source paths and direct warning paths. No actual compiler error appeared at this boundary; a broad textual `error:` match was only a function parameter, and the audit now recognizes diagnostic prefixes. M4 runtime result remains pending.++Original M4 release build completed successfully in698.40s; runtime remains active/pending. Final compile warning audit now records43 unique origins across12 files; all43 exact emitting expressions are unchanged from baseline39696ad. Eleven entire files are byte-identical; NoEpisodeStorageTests differs only in its two live scratch-schema references V20→V21 (27/69), while warning expression162 is unchanged. `m4-release-warning-provenance.json` retains proof. No actual compiler errors and no source cleanup performed.+++### Final bounded verification blockers — no implementation commit+The original33 M4 gate has exited incomplete: Release build succeeded698.40s; parent interrupted only verified owned helper37071 with INT at22:36:33 local,60m14s after21:36:19 launch. Helper and parent34864 drained; Make session45724 exited2. Exact reconciliation:1 declaration started (duplicate settling),0 passed,32 unstarted,0 skips/known-issue lines,1 of4 suites started. No completed distribution or measurements file exists. This is an incomplete timeout, not a median/p95 assertion verdict or baseline waiver. `composed-m4-1.log`, `original-m4-33-reconciliation.json`, `m4-runtime-bound.json` and the retained three read-only samples preserve evidence. No performance fixture/threshold/sample or NoEpisode source was changed.+The bounded source audit (`m4-noepisode-dependency-audit.json`) finds unchanged NoEpisode Writer/Index/History and original performance fixture; reconciler4 transition sites/8 facts calls and exact transition argument multiset match39696ad. New selected association capture/after-read/barrier/fold and Work record-transfer work exists per chunk. Samples do not quantify that overhead or establish baseline-equivalent runtime; no causal/budget conclusion is claimed.+Mac3 remains a separate infrastructure block: signed target compilation succeeded, but UI runner initialization timed out enabling automation mode;0 of3 journeys executed. Read-only host status reported Developer mode disabled. No OS security/automation setting was changed or denied; the required test action remains blocked before initialization.+Completed Rune IDs remain utwj28a–utwj28f; utwj28g remains in progress, utwj28h/utwj28i pending. Statuses explicitly refreshed with Rune batch, preserving identifiers and dependencies. Functional gates are recorded above; required Mac rendering and original timing validation remain unresolved. No new product decision is pending. Concrete next step: unblock the Mac automation prerequisite and establish an executable bounded path to complete the unchanged original M4 timing gate; finish pending validation before any feature commit. Worker owns no active heavy job and performed no staging/implementation commit/push/merge/device install. Branch remains feature/T-2468-association-ledger at spec HEAD82d3f6df.++### Exact-baseline bounded component diagnosis (required gates remain open)+The parent materialized exact baseline39696ad851823a235749313df92f096e68735629 via git archive into the separate asterism-scale-baseline-diagnostic directory. An external public-API executable depended on that actual Core package: no copied model, association implementation, performance test harness or shipping edits. Core-only debug build passed67.35s; the bounded in-memory component probe exited0 in1.305670041s (runtime wrapper1.881s). For100/1000/5000 physical NoEpisodeAction rows, one warmup plus three measured unchanged single-fact transitions each all returnedfalse with exact row counts and no pending changes. Warmup-excluded medians were3.438875/31.554584/152.917625ms,44.46734x for50x history. Evidence: noepisode-exact-base-public-probe-result.json, noepisode-public-runtime-1.jsonl and noepisode-public-build-1.log under the private build directory. The result is a debug component observation, not an original M4 timing verdict, statistical band or feature-relative causal comparison.+Post-run verification separately records all554 immutable baseline files and all149 shipping compiler inputs unchanged, with an empty index: noepisode-exact-base-public-probe-postchecks.json. Writer/Index/History and the NoEpisodeAction model declaration body match baseline (only live schema namespace differs). The retained old noepisode-only control explicitly has pureBaseline:false and changed production files; its timings cannot establish baseline performance.+The original fixture's source-derived finite upper bounds (not measured final counts) are29,750 retained actions and8,800 nonempty global history reads across warmup plus10 generations; repeated decode visits can therefore be large without an infinite loop. The measured small probe establishes history-size sensitivity in the unchanged production component, but does not apportion the original60-minute timeout between that component, feature overhead, SwiftData and the full fixture.+Smallest next diagnostic, if separately admitted, is to split the same external exact-base probe into index construction, one anchor-Work history fold and allActions fold at the same bounded sizes/calls. This can discriminate fetch/group cost from unrelated-history decode without touching production. A repair candidate must first have focused TDD for physical contradictions, pending inserted stable/fresh clears, Work reassignment and rollback. Fresh affected-Work reads avoid cache invalidation but change refusal reach for unrelated malformed histories; transaction-local reuse retains global validation reach but must incorporate every insertion/repoint and discard state on rollback/save. Single-invocation decoded-history reuse has the smallest semantic surface but leaves the repeated global read per transition. No remedy or next run was applied; required Mac3 and original33 M4 gates remain open, Rune statuses unchanged, no implementation commit readiness.+Mac blocker evidence is now narrower than developer-mode status: retained host logs show an uncompleted XCTest LocalAuthentication policy2 request with reason “Enable UI Automation”, after runner/daemon authorization and before the60-second timeout. Files mac1-review-automation-auth.log and mac1-review-diagnostics preserve this proof. No prompt accepted, automation/security setting changed or retry performed; zero of3 journeys executed.++The separately admitted external phase2 probe also exited0: warm-cache Core-only build1.76s (wrapper4.058s), component runtime1.274026s (wrapper1.820s), all12 invariant check groups and36 timed phase observations passed. One warmup plus three diagnostic iterations per size used a fresh index, then the anchor-Work history fold, then allActions on that index. Postwarmup medians (100/1000/5000 rows) were index construction1.214958/11.847041/58.442667ms; anchor history0.024541/0.080417/0.086791ms; allActions1.717291/17.950791/87.207083ms. Raw phase observations: noepisode-phase-runtime-1.jsonl; build: noepisode-phase-build-1.log; parent summary: noepisode-exact-base-phase-probe-result.json. The narrow measured finding is that BOTH global fetch/group and global decode/sort grow with unrelated history; decoding reuse alone would leave global fetch amplification. The single-Work fold stays small on this fixture. This does not establish full M4 attribution, a feature-relative regression, an approved scoped-refusal change or a budget verdict. V1 source/plan/results remain preserved; no writer rerun or production repair occurred.+Separate phase2 postchecks again confirm554 baseline files and149 shipping compiler inputs unchanged, empty index (noepisode-exact-base-phase-probe-postchecks.json). Rune completion remains a–f complete/g in progress/h–i pending. Mac authentication and original M4 completion remain required blockers; no code commit is ready.++### Parent-authorized narrow history reuse repair — RED preparation+The parent authorized an independent Implementation/stream1 repair task utwj28j after the exact-base phase measurements. Existing a–f completion and g/h/i blockers remain untouched. NoEpisodeHistorySessionTests adds10 runtime SwiftData declarations,12 parameter executions: lazy empty/nonempty global validation; stable-present/absent pending clears; two new Entries same Work/day retain two fresh clears and same-call snapshot semantics; absent observed-clear rows; identical copies and unrelated physical conflict; moved pending history; coalesced conflict deferred to next nonempty transition; failed save/rollback/fresh replay; explicit external invalidation/post-save freshness; cold/warm raw malformed Work moves.+Proposed internal HistorySession is explicitly bound to ONE existing save chunk/context, lazily globally validates all physical rows, reuses whole decoded histories/key lookup, and records its own inserted stable and random clears between calls. The public one-call writer creates a fresh session. Reconciler convergence chunks, deletion chunks and every failed-chunk per-plan replay create independent sessions; no cross-save/rollback/refault state. Raw Work moves must remain non-decoding, retain raw rows, and invalidate decoded state; the next nonempty call regroups by current row.workID and globally validates. External invalidation drops raw inventory too. Empty calls and teardown/save never add validation. No scoped-refusal change, persistent entity/schema/index or generic context cache. The original budgets/tests are untouched; new suite stays outside the fixed fast manifest. Production GREEN awaits meaningful parent-run API-absence RED plus critic review.++Parent-run RED noepisode-session-red-1.log exited2 with concrete missing HistorySession API and0 runtime. Independent critic reviewed private GREEN drafts and found no concrete production blocker; its raw-move test lifecycle correction is incorporated. Integrated changes are limited to NoEpisodeWriter and the existing four DuplicateReconciler transition sites/chunk lifetimes; all other callers retain fresh one-call semantics. Added actual two-set deletion-chunk failure/rollback/refault/per-plan replay regression requiring exactly one committed random clear per Work, no phantom stable keys, both collapsed sets and fixed-point no-growth. New runtime suite now11 declarations/13 argument executions. Next frozen focused selection: 138 declarations/8 suites, next-noepisode-session-green138.sh; exact source methods in noepisode-session-green-expected.json. Original budgets unchanged; no build launched by worker. Mac retry separately executed3 methods with2passes and1new route assertion failure, so authentication no longer prevents that attempt; Mac behavior completion remains open.++Parent focused GREEN138 exited0: build38.62s,138 declarations across9 reported suites passed4.094s, including actual deletion-chunk failure/replay. Eight explicit selected suites plus a nested suite account for the report; exact title reconciliation remains parent-owned. One new unnecessary-try warning in the new replay assertion was removed without changing its expression/expectation; warning-only focused11 retry prepared as next-noepisode-session-warningfix11.sh, production unchanged. Original inherited warning provenance remains separate.++Warning-only focused session suite passed11 declarations/13 parameter executions in0.121s, build17.17s, no warnings. The parent then ran the identical external single-generation driver against exact baseline39696ad: build58.24s, setup17.900s, measured pre-observation counts10,000 NoEpisodeAction rows/6,000 Entries/1,100 Works/1 Site. Observation hit its declared120-second alarm; no completed observation or settling duration exists (runtime wrapper138.782s). A retained1-second sample locates the unchanged global writer/index/history decode path. Setup also emitted CoreData external-data .interim clone errors, retained and not waived as harmless. The diagnostic is incomplete for baseline and does not replace any original budget. Current-arm run remains pending; shipping production inputs frozen.+The separately authorized Mac retry actually executed3:2 passed and Save/Cancel failed its Inspector Edit→chapter-editor assertion. Native action was synthesized and inspector disappeared, but no editor controls appeared; retained private app tree/window is disabled. No SwiftUI navigation/presentation warning was found in the raw test log or narrow retained PID window. Existing state-only navigation tests prove the bound route values but cannot reproduce a SwiftUI remount failure. No speculative UI edit or further UI retry performed. Initial zero-case authentication failure remains distinct historical evidence; current Mac behavior remains incomplete.++The current-arm identical initial-generation diagnostic exited0: Core-only debug build75.95s, setup14.4247s, observation3.434260166s (0 collapsed/300 settling sets/250 Entries moved), settling6.599527125s (all300 seeded sets collapsed). Actual counts were10,000 actions/6,000 Entries/1,100 Works before observation,12,250/6,000/1,100 afterward,12,250/5,750/1,050 after settling. Both resolved dependency/binary provenance retained; exact baseline554 files remain unchanged. The current semantic comparison completes; exact baseline observation remains incomplete at120s, so no precise speed ratio, median/p95 or original-gate verdict is claimed. Debug timings do not establish Release budgets. No original performance assertion/sample/selection changed.+Task utwj28j has runtime correctness138 plus warning-clean11 and a completed current diagnostic; composed validation remains pending, so it stays in progress until the parent accepts the required verification. Proposed unchanged original33 Release run has an explicit10-minute bound to the first distribution and30-minute total runtime bound after build, informed by the documented32-test1,120.6-second run and the current initial-generation debug work (3.434+6.600s, before repeated reseeding). This is a timeout policy, not a predicted passing band or threshold waiver. Preserve incomplete output if either bound is reached. The original 60-minute incomplete run remains evidence. Production source frozen; root owns unfiltered Core3 and any further heavy admission.++Post-repair unfiltered Core3 exited0, warm build0.69s/no compiler warnings. Exact source/log reconciliation:4,002 declarations =3,947 started/passed plus55 explicit opt-in performance skips;365 suites =354 started plus11 skipped, no missing/unexpected/nonpassed. Core3,421/323 passed184.982s; supporting ConstellationKit42, Presentation304 and Intelligence235 passed. Original33 is separately owed. Current single-generation setup emitted0 external-data clone errors while exact baseline emitted200; this is an additional diagnostic confound retained with the original logs, not a sole-cause finding or basis for an exact ratio.+Parent-reviewed bounded-original33 wrapper preserves all source filters/samples/assertions, uses only its newly created process group, and records build/startup15min/first-distribution10min/runtime30min bounds; next-composed-m4-33-bounded.sh remains unlaunched by worker. Fast2/full native quick3 follow under parent admission. No further source edits or Mac retry/diagnostic approval.++Post-repair full native quick3 passed exact1,784 declarations plus all120 argument nodes in31.881s; signed Mac app/embedded-extension prerequisite passed. Seven native warning origins are inherited, with entire emitting files byte-identical to baseline and matching prior logs. Parent has started unchanged original33 Release selection through the corrected bounded wrapper (critic source rereview CLEAR), session9806/owned Make-group58195,12:32:42.862Z; outcome pending. All898 compiler paths remain frozen, owned simulators Shutdown. No Mac diagnostic approval or source edit/UI retry.++History-reuse impact/selection rationale: only DuplicateReconciler's four transition sites opt into explicit per-save-chunk reuse. Public recordNoteTransition and reader-confirmed Work merge/resolution/import/mark paths retain fresh one-call semantics; no new UI state, route, evidence or persistence format. Global physical-copy refusal reach, same-call snapshot, pending stable/random clears, raw Work moves and save/rollback/replay remain exercised by the focused138 and full Core3; full current native quick3 covers publication/model/runtime consumers. Earlier exact phone29 and selected iPad5 editor journeys remain source-qualified evidence for unchanged app/editor code, not a claim of newly composed rendered or Mac green. Original Release timing selection33 is active, not complete. Rune snapshot history-repair-rune-status.json confirms10 tasks: a–f complete, g/j in progress, h/i pending. Task10 is independent of Mac but remains open for its final timing verification. No additional test, UI run, source edit, staging or commit.++Post-repair fast2 retained the exact456-identifier manifest and passed Presentation304/20 in0.096s plus Core152/12 in0.472s (composed-fast-2-history.log). No manifest expansion or assertion change.++The first bounded post-repair Release attempt was stopped before tests: actual SwiftPM frontend/plugin descendants used PGID59221 while Make58195/swift-test58201 used58195, retaining original fresh SID58195. The fresh-group-only guard was insufficient. Parent sent verified swift-test INT, Make exited2 after320.656s, then identity/session-verified orphan group59221 was drained. No test/distribution began; no timing or code failure verdict. Logs/cache and m4-2-live-owned-groups-build.json/m4-2-session-drain-check.json retained.+A separate run3 guard now tracks PID/executable/lstart identities through fresh-session membership and observed parent ancestry, retaining reparented descendants and child-created sessions. It signals only freshly reverified owned groups, preserves uncertainty and bounds cleanup waits. A harmless Python-only fixture passed3.5376s: root exited, nested-group orphan and detached-session child remained tracked, only their verified groups received INT, original SID drained, unrelated fresh control survived, no tracking errors. Evidence m4-run3-ownership-fixture.json. The earlier default-sandbox ps-denied fixture is separately retained; pre-identity failure meant its exact old PID/SID receipt was absent, so no identity-verified old drain is claimed (sleepers had a finite30-second source limit and elapsed before corrected retry). Corrected fixture children were all limited10s/overall15s. No Swift/app/user process was launched or signalled by the worker. next-composed-m4-33-bounded-run3.sh preserves original33 filters/samples/budgets with the same time bounds; critic rereview and parent admission pending. Production/compiler source unchanged.++Corrected run3 is active under parent ownership: session50667, fresh Make/SID60300,12:43:34.696Z. Parent verified compiler61300 uses its own PGID61300 while remaining in fresh SID60300; the new guard tracks it. At12:53:03Z build was still active with no guard errors/test helper/distribution; build deadline12:58:34Z. This is pending compilation, not a test result. All898 compiler inputs remain frozen; no further worker build/source/UI action.++Run3 actual first Release distribution completed and FAILED unchanged budgets: duplicate settlingmedian7.630516s/p9511.433368s/n10, observationmedian3.982454s/p959.225410s/n10, both original2s medians asserted and failed (first test190.520s/2issues). Gated arrival passed0.027760s. Original33 continues unchanged; this is an actual budget failure distinct from earlier incomplete attempts. Build600.98s; verified helper63867 birth23:53:39local/PGID63867/SID60300, first completed distribution observed201.72s runtime, demonstrating corrected cross-group guard tracking. No threshold/sample/assertion changes or waiver.+The retained current sample lands at outer prewrite LibraryRepository517→NoEpisodeWriter.reconcileCurrentNotes35→facts14 and SwiftData/CoreData SQL while reading Work relationships. facts function body and entire NoEpisode checkpoint file match exact baseline (noepisode-remaining-gap-source-audit.json). A sample is not whole-distribution attribution or measured query count; feature overhead remains unquantified. Proposed discriminator is normal-vs-Work-prefetch full fetch+facts, rather than skipping scans/checkpoints. External read-only diagnostic is prepared only (next-noepisode-facts-prefetch.sh/noepisode-facts-prefetch-plan.json): copied205-file retained synthetic input, fresh contexts/same calendar, six counterbalanced calls, exact5,750 full NoteFacts and rows, no changes/saves, strict call/runtime caps; original input/compiler pre/post hashes. No existing shipping prefetch pattern found; SDK public FetchDescriptor property confirmed. No diagnostic launched or product edit while original33 runs. Taskj remains in progress because current correctness passes do not clear the actual timing breach.+++### Bounded original33 outcome and completed read-only diagnostics+Parent confirms original33 Release run3 ended at its30-minute helper runtime bound, with the full owned session drained. Seven declarations started: five passed (including the retained known-memory export issue), the duplicate settling test failed its two unchanged2s median assertions, and backup import was interrupted;26 declarations were unstarted. Actual failed medians remain settling7.630516s and observation3.982454s, each n10. This is a real partial budget failure plus an incomplete overall gate, not a full33 result or a waiver. Original sources, filters, samples and thresholds remain unchanged.++The separate copied-store facts-prefetch diagnostic completed six exact5,750-row/full-NoteFact comparisons, with no pending changes or saves. Parent reports measured total normal about0.4510s versus Work-prefetched about0.2804s (about0.171s difference); facts time0.2631s versus0.0285s was partly offset by higher fetch cost. All205 retained input-store files and898 shipping compiler inputs remained unchanged. This is a small current Debug path diagnostic, not a Release distribution or an explanation of the entire failed budget. Evidence remains private in noepisode-facts-prefetch-plan.json, its build/runtime logs and postchecks. No shipping prefetch optimization was made.++The read-only import audit is noepisode-import-readonly-scope-audit.json. Current ConfirmImport raw-action union203 precedes Site/rule save; Entry transitions438/449 use fresh public writer calls, with save455 per actual500-record chunk. Baseline39696ad equivalents are185,429/440 and446; transition argument blocks match ignoring whitespace. No raw Action repoint occurs inside that Entry loop. EntrySources and record/association saves are separate later phases; prospective BackupImport materialization is a separate graph. Any future import reuse would require separate scope authorization and focused chunk-failure/retry/global-conflict tests; none is implemented.++Rune remains utwj28a–f complete, g/j in progress, h/i pending. Mac retry remains3 actual journeys/2 passes/1 Inspector-to-editor failure; additional Mac diagnostic permission and import-reuse scope are pending. There is no implementation commit readiness, no worker heavy process, no staging/commit/push, and no further source optimization or build is authorized at this checkpoint.+++### Authorized importer chunk reuse — focused TDD in progress+Parent explicitly authorized narrow live-import reuse after the original33 import phase was interrupted at the runtime bound. The new NoEpisodeImportHistorySessionTests exercises actual internal upsert at batchSize2, preserving production default500. Compile RED noepisode-import-red-1.log exited2 solely for the absent internal noteHistorySessionFactory argument (zero runtime). A seam-only intermediate retained one fresh session per Entry transition; runtime RED noepisode-import-runtime-red-1.log executed6 tests/1 suite in0.147s with10 expected session/fetch-count issues and no semantic failures. Five Entry calls read5 times rather than the expected3 chunk reads; retry and corruption cases similarly expose per-call reads. Exact action counts, imported mark/fresh clears, unchanged-fact overlap clearing, empty-chunk laziness, unrelated global conflicts, first-chunk durability and fresh retry assertions all passed.+The proposed GREEN places a lazy context-bound session in a nested scope per actual Entry chunk and ends that scope before the existing save. Upfront imported-action union, per-record applicability guards, save positions, EntrySources/later-record/prospective-materialization phases and public single-call semantics remain unchanged. Source review and focused GREEN are pending; no broader gate verdict or implementation commit is claimed.++Focused importer GREEN noepisode-import-green-1.log exited0: build11.28s,6/1 passed0.141s with all exact declared titles, no skips/issues/warnings. Critic confirmed defaulted internal factory and chunk-local nested scope end before unchanged save, both Entry arms share it; upfront union/default500/all other phases remain unchanged. Actual runtime batching RED→GREEN counts are preserved without weakening semantic assertions. Wider dependency-backed correctness selection is prepared separately for parent admission; no broad gate or task10 completion is claimed.++Parent-admitted broader importer/history correctness noepisode-import-broader-green-1.log exited0: warm build0.59s,80 declarations/eight suites passed2.512s. Exact source-title reconciliation80expected=80started=80passed, no missing/unexpected/unpassed titles/skips/issues/warnings. All seven parameter-case starts appeared (three incoherence arms and two bool arms in each of two history tests), yielding84 expanded executions; parameterized declarations passed. Evidence noepisode-import-broader80-reconciliation.json. No original timing-gate completion or Mac behavior pass follows from this correctness result. Production remains frozen; no additional heavy process, staging or commit.++Parent-owned bounded public import ABC diagnostic completed with exact semantic checks: A actual39696ad baseline confirmation30.233s; B explicitly modified common-repair counterfactual0.717s; C current0.741s. B is not a pure baseline: it contains the same reviewed history-reuse repairs for a matched component comparison, preserving original guard-driven save boundaries. Private provenance/build/runtime receipts live under /tmp/t2468-ledger-build/import-public-comparison/receipts/. Separate initial-generation B/C observations were2.838s/3.277s and settling4.842s/7.965s; the3.124s settling increment remains unresolved pending read-only attribution. These bounded Debug diagnostics establish neither the original Release2s budget nor full33 completion, and authorize no further shipping optimization. The importer80-declaration/84-expanded correctness pass remains current; Mac and performance gates remain open. Shipping production stays frozen and no worker build/staging/commit is active.+++### Reviewed lazy raw-row Work inventory closure+Contained sampling identified repeated raw-row owner traversal in the common B/C NoEpisode HistorySession.repointActions path; it does not apportion feature-relative overhead. Parent authorized the smallest chunk-local per-Work physical-row inventory, with no schema/save/query-scope/budget changes. Critic cleared exact private Writer fb3c0d5c59ab7e89ef76d315f6ebc4a8c8b46acd9b0361284d2a44377f72d247 and tests e12c3cef4544580e6b36f1d81cffb0ac15395c53f30e702a1bdea0abd9f654ae before application. Buckets are built only on first raw repoint; record-only sessions do not traverse owners for this inventory. Every physical reference/copy remains in the original rawRows used by unchanged global validation. Own insertions update buckets only once built; own moves drain selected sources, external invalidation drops both raw inventories, and decoded invalidation/deferred validation/chunk lifetime remain unchanged.+Compile RED noepisode-raw-bucket-red-1.log failed only absent rawWorkID constructor seam (zero runtime). Seam-only old traversal runtime RED built29.30s, executed5decl/6expanded in0.033s, and failed exactly two traversal counters (72vs24 and46vs22); every semantic assertion passed. Reviewed lazy GREEN built32.94s and passed5decl/6expanded in0.036s. These counters measure repoint inventory owner traversal only, not unchanged global decoding work.+Focused broader noepisode-bucket-broader-green-1.log passed85decl/nine suites/90expanded in2.571s; exact85expected=85started=85passed, no missing/unexpected/unpassed IDs/skips/issues/warnings. All reviewed600s ownership guards ended naturally, reasonnull/uncertainfalse, with no remaining owned processes. Frozen source postchecks raw-bucket-postchecks.json and reconciliation noepisode-bucket-broader85-reconciliation.json retained. No timing-budget or full-gate verdict is implied; the next bounded retained-driver comparison requires parent admission. No staging/commit/push or additional worker heavy process.+++### Selected original Release timing result — both budgets still fail+The parent-admitted single original M4DuplicateScalePerformanceTests/settlingPassOverSeededDuplicates completed naturally with exit2, no signals/tracking errors and no remaining owned processes. Build561.97s; exact one declaration/one suite ran153.168s. Both original median assertions failed: settling6.648267s (p957.660916s,n10) and observation3.932553s (p954.604596s,n10), each against2s. No semantic/count assertion failed and no declaration was skipped; original performance source is byte-identical to39696ad. Evidence selected-release-duplicate-reconciliation.json, selected-duplicate-release-1.log and measurements retained. This is a real unchanged-budget failure; the full33 gate remains open, with no waiver or further optimization selected.+The guard was configured for900s build/startup and600s runtime/first distribution, but its final receipt remained in building status with no helper/runtimeClock/firstDistribution fields, likely due buffered output. Total718.353s was below the active900s bound; the native153.168s result independently lies below600s. Do not claim the separate runtime clock activated or retrofit the receipt. All898 source paths matched before and after; guardExit2/integrityOKtrue retained.+Final warning provenance selected-release-warning-provenance.json records26 actual-source origins across11files, all inherited or source-qualified against39696ad and prior receipts; no unqualified/new origin. Macro expansions map to their real source notes. The two production NoEpisode73/93 warnings are exact baseline-file matches; no unrelated cleanup was made. Worker source/task states remain incomplete: taskj open, required performance/Mac gates unresolved, no staging/commit/push or further heavy run.+++### Private current-note Work-prefetch trial preparation and baseline parity+Contained Release sampling motivated a parent-admitted PRIVATE descriptor-only trial: retain the ordinary allphysical Entry fetch and default pending inclusion, adding only Entry.work relationship prefetch in reconcileCurrentNotes. No shipping production trial is applied. Critic reviewed three appended tests with actual decoded stable-key equality, physical sameUUID splitowners/latestdates/resolved+unresolved redirects/ownerless rows, unsaved owner/date changes+insert/delete without incidental Entry writes, fresh externally saved owner/Entry, unchanged no-write and acknowledging-mark overlap outcomes. Prior copied-store Debug0.171s difference is corroboration only; the original Release medians6.648267/3.932553 versus2s remain failed.+The first baseline-only attempt failed compilation (zero runtime) because six test Work initializers omitted required timestamps; log noepisode-prefetch-baseline-parity-1.log retained, complete899 source restored before release. Only six deterministic epoch timestamps were corrected privately and critic hash-confirmed no assertion delta. The separately admitted corrected baseline-only retry noepisode-prefetch-baseline-parity-2.log built17.61s and passed exact3 declarations/one suite in0.059s. All three semantic titles matched, no issues/skips; six warning locations were inherited existing NoEpisodeRepositoryTests249/326/348–351, none in appended tests. Reviewed600s ownership guard ended naturally in22.795s, reasonnull/uncertainfalse/no remaining owned processes.+Before the retry, authoritative source-state.py verify green passed900 comprehensive inputs. Only the corrected test file was temporarily appended; production Writer remained exactfb3c0d5c. After exit, all900 candidate hashes matched, exact original test4ef7640704cac2f0dfa79f09ae7e7ba1fc26c59c797ead1eb351fe3cf0200ff2 was restored, all900 baseline hashes matched and authoritative verify green900 passed before slot release. Proof prefetch-parity3-retry-restoration-reconciliation.json. Private descriptor trial correctness/performance admission remains pending; no automatic production advance, no commit readiness.++After baseline parity3 and independent review, parent admitted only the descriptor trial plus one complete affected cohort (no redundant parity3 repeat). Manifest-bound source-state helper verified baseline900, applied exactly Writer0362d62d and corrected RepoTests4c0f4a34, and verified candidate900 before/after. noepisode-prefetch-trial-broader-1.log built26.11s and passed exact88 declarations/10 suites/93 expanded executions in2.594s; no missing/unexpected/unpassed identifiers, skips or issues. Only six inherited RepoTests249/326/348–351 macro warning origins appeared, matching retained baseline expression hashes. Reviewed600s guard ended naturally in33.988s, reasonnull/uncertainfalse/no owned remainder. Candidate remains frozen pending explicit root performance disposition; correctness does not authorize automatic retention, a Release run or a completed performance gate.++The separately admitted one-shot descriptor-prefetch original Release test completed naturally with exit2: build567.74s, exact one declaration/one suite146.912s. Both unchanged2s medians still failed: settling6.281479s (p957.430748s,n10) and observation3.682579s (p954.440666s,n10). Exactly two budget issues occurred; no semantic/count assertion or skip. Single-cohort numerical movement versus prior6.648267/3.932553 is not controlled repeatability or sole-attribution proof and does not authorize automatic retention. Full33 remains open. Raw prefetch-trial-selected-release-1.log/measurements and execution/release-reconciliation.json preserve actual values.+The clock-only guard adjustment activated runtime from the birth-verified owned helper independently of buffered output (build/startup570.958s; total717.985s). It conservatively includes discovery/startup; no exact method-start claim. firstDistribution stayed absent in the guard receipt because native output arrived at exit, although both actual n10 distributions are retained. No receipt retrofit. Native/guardexit2, reasonnull, no signals/tracking errors/remaining owned identities; candidate900 source integrity passed before/after. Final warning audit20origins/seven files is entirely inherited/source-qualified, with no new source cleanup. Candidate remains frozen pending explicit root disposition; no subsequent run, automatic keep/restore or commit readiness.++Root disposition explicitly declined retention of descriptor prefetch: both original medians still fail and modest single-cohort directional movement does not establish repeatable benefit sufficient to retain the shipping delta. After natural exit/drain, the reviewed helper restored ONLY the original Writerfb3c0d5c and base RepoTests4ef764. Exact full900 baseline verification and authoritative binding verify green900 both passed. Separate execution/root-disposition-restoration.json retains this restoration, leaving candidate post-run integrity and all trial raw logs/manifests/distributions/clock fields unchanged. Read-only host boundary03:49:13 local showed no matching heavy/compiler/test process,74.3% CPU idle,pressure1,current swaprates0 (allocated702.88MiB). No further job or optimization was advanced.+++### Private mutation-only barrier warming alternative prepared+The never-shipping global roots-only warming probe preserved semantic parity but regressed combined eight-iteration pure work776.480→874.807ms (construction78.56→9.86ms, queries694.02→860.80ms), so root rejected it. A critic-cleared safer PRIVATE alternative preserves public/default ledger construction and default Storage.read all-observed warming, opting in internally only from AssociationMutation.capture and its finish fold. No maps, physical closure, validation, fallback, fresh barriers or save boundary changes are proposed. Capture still calls sourceGuard once per request mention, potentially repeating an Entry/off-root fallback digest; not all mutation consumers are receipt-only and benefit remains unproved.+Private mutation-warming-private-v1/execution pack records actual baseline900 and expected candidate901 (three existing source files plus one new three-case parity suite), exact source/apply/restore guards and backups, manifest-bound root admission, and a source-owned complete329-declaration/31-suite correctness cohort with41 parameterized declarations. Existing original N10 failures are the meaningful performance RED; no artificial warming counters were added. No shipping patch, build or test was applied/run for this alternative at this checkpoint. Any later original Release trial requires separate root admission; full timing gates remain open.++Root separately admitted the exact mutation-only trial and one whole correctness gate. Manifest-bound helper verified baseline900, applied only three reviewed source files and one new three-test file, and verified candidate901 before/after. association-mutation-warming-correctness-1.log built34.03s and passed329 declarations/31 suites in19.455s. Final source-owned reconciliation confirms all41 parameterized methods'154 values against exact attributes/enum cases/ten deterministic seeds, plus288 ordinary executions=442. No declaration/suite/argument mismatch, issue or skip. Initial private parser greedily split two titles at later "to" words; its script/receipt are preserved separately and corrected v2 correctness-reconciliation-final.json changes no source/test execution.+Eight compiler warning origins are inherited/source-qualified: NoEpisodeRepositoryTests249/326/348–351 macro expressions and Intelligence Character35/Rule40 deprecations; correctness-warning-provenance.json retains exact proof. Reviewed600s guard ended naturally59.802s, exit0/reasonnull/uncertainfalse/no owned remainder. Candidate901 remains frozen pending explicit performance disposition; no Release was launched or automatically admitted. Public/default warming remains unchanged, and per-request-mention capture sourceGuard fallback cost remains a stated risk.++The separately root-admitted mutation-only original Release N10 trial completed naturally with native/guardexit2. Build567.02s; exact one declaration/one suite149.095s. Both unchanged2s median assertions failed: settling6.309745s (p957.237939s,n10) and observation3.796133s (p954.512053s,n10), with no semantic/count issue or skip. Evidence mutation-warming-selected-release-1.log/measurements and execution/release-reconciliation.json. No full33 verdict, repeatability/causal claim or automatic retention follows.+Birth-based runtime clock activated from verified owned helper independently of output buffering (build/startup569.927s; total719.412s). Guard firstDistribution remained absent, although both actual native distributions are retained; no receipt retrofit. No signals/tracking errors/uncertainty/owned remainder, candidate901 pre/post source integrity true. Final26 warning origins/11files all inherited/source-qualified; completed warning metadata is separate from preserved generic-template initial receipt. Candidate remains frozen pending explicit root disposition; no retry, restore, commit or further heavy job was advanced.++Root rejected mutation-only warming after independent native/guard/warning review: both original2s budgets remain failed and modest one-cohort movement is insufficient repeatable benefit/closure. The separately authorized reviewed restore verified candidate901, restored ONLY the three exact source backups and removed ONLY the owned new trial test. Full baseline900 and authoritative binding verify green900 passed. Separate execution/root-disposition-restoration.json retains restoration; private draft test/patch and all native/log/clock/distribution/post-integrity evidence remain untouched. No further optimization/Release/build admission exists; final composed gates remain owed on selected restored900 source. Index remains empty, no commit/push or worker heavy job.+++### Final restored900 correctness checkpoint — root accepted, overall verification incomplete+The selected restored900 shipping inputs remained unchanged through the final composed gates. Unfiltered serial Core completed naturally with 4,017 declarations: 3,962 passed and 55 existing opt-in performance declarations skipped; 367 suites comprise 356 started and 11 skipped. Exact final-v2 reconciliation includes 231 executed parameterized declarations and 2,573 argument executions, yielding 6,304 expanded executions. All sixteen root checks passed, no test issues; twenty warning origins were source-qualified as inherited. The initial reconciliation with twenty-two multiline/control argument records missed is preserved separately; accepted evidence is `composed-gates-restored900-v3/core-reconciliation-final-v2.json` plus `core-root-review.json`. No rerun or source change repaired that parser.++The unchanged fixed fast manifest verified and passed exactly 456 identifiers / 32 suites, with all seventeen parameterized declarations and 113 argument values matching accepted current Core: 439 ordinary plus 113 argument executions = 552 expanded executions. No skips, issues or warnings. The reviewed 600-second guard exited naturally0 in 6.557s, with no signals, tracking errors, uncertainty or remaining owned processes. Source900 postcheck passed. Evidence: `composed-gates-restored900-v3/fast456/fast-reconciliation.json`, `fast-bound.json` and root acceptance `fast-root-review.json`. V1 preparation and the subsequent accepted final-Core reference pin are both retained.++Signed Mac application and embedded extension compilation passed as the retained prerequisite to full native quick. Native testing passed exactly 1,791 declarations, forty parameterized declarations / 120 passed argument nodes, 1,871 expanded cases, with zero issues, skips or expected failures. Native Make exited0 / TEST SUCCEEDED. The wrapper124 is recorded distinctly: only a birth/ancestry-verified post-Xcode ibtoold helper received SIGINT; final drain was empty, with no other signals, errors or uncertainty. Root explicitly accepted that infrastructure disposition in `composed-gates-restored900-v3/native-execution-v1/native-root-review.json`. Three tool warnings are inherited; no compiler/structured runtime warning was emitted. Fresh UUID fixture isolation, mirroring-off before bootstrap and the dedicated simulator's already-Shutdown state were verified; no shared library/device installation occurred.++These are correctness/compile acceptances only. The previously accepted Mac5 rendering does not erase historical failed attempts; the inherited same-geometry iPad scroll contract remains pending without a tolerance waiver. Original Release duplicate N10 still fails both unchanged2s median budgets, and the complete original33 performance gate remains incomplete. Full unfiltered phone/iPad UI remains owed before any push. Rune a–f remain complete, g and j in progress, h and i pending; no overall GREEN or code-commit readiness is claimed. All heavy jobs drained. Concrete next step is parent disposition of the retained performance and iPad contract failures, followed by the remaining required validation; no new product decision or further optimization is admitted. No staging, commit or push was performed.+++### Matched Release attribution completed — no safe two-second fix demonstrated+The parent admitted an exact-baseline39696ad Core-only Release executable build with the same retained9f1 clock-bracket public driver used by current C. A build passed122.30s; baseline runtime completed naturally: setup11.729156542s, observation96.16345725s and settling170.459821792s. Current C reused the hash-proven retained Release executable457d5127…62e33 without rebuilding: all216 Core/package inputs exactly match selected900. C setup11.709512666s, observation2.932166834s and settling5.230809292s completed naturally. Each arm passed all six exact semantic/count/multiplicity checks:6000Entries/1100Works/10000actions→6000/1100/12250→5750/1050/12250, one Site throughout, observation0collapsed/300settlingSets/250moves and settling300collapsed. No clone diagnostics occurred. A/C guards exited0 and drained, all source900/baseline554/driver inputs stayed unchanged. Evidence: `matched-release-attribution-v2/receipts/87144424-32f4-4e35-bbde-27dfff469124` (A) and `…/05481b22-3b76-417b-937a-549fa9909119` (C). These are one initial-generation Release diagnostics with the same untimed count warming, not original warmup+N10 budget verdicts. The old driver output word “debug” is retained but actual build/binary provenance is Release. C includes approved common NoEpisode repairs; A/C difference is not association-only overhead.++Read-only postshutdown metadata checks on that exact C synthetic store confirmed750entry invalidation events,750distinct typed scopes each multiplicity1, zero acceptances/PairNoteVersions/malformed payloads/lookup mismatches/validation blobs. SQLite mode=ro/query_only was used; DB/WAL before/after hashes match. No row IDs or authored text were exported. `postshutdown-association-oracle-v2.json` is the reference. This verifies required zero-root persisted invalidation work rather than authorizing its removal.++A separately reviewed private timing-only C copy retained all physical validation, queries, ordering, barriers, writes, saves and rollback/refault boundaries. Immutable Work/Entry/deletion/replay origins carry sixteen coarse inclusive stages; no per-row recorder/model cache or shipping code change. Three cumulative snapshots are taken outside original timers; all metrics output follows original final counts and shutdown. An initial private build failed before compilation because the external product package identity did not match its core-copy dependency; v1 inputs/failure are preserved. The new v2 changes only that identity/private path; instrumented library and driver Swift bytes are identical to reviewed v1. Corrected build passed142.57s, only the two inherited NoEpisode73/93 warning origins; private runtime passed all nine original semantic and nine postdrain read-only oracle checks, natural0 guard21.494s, no signals/tracking errors/remnants/uncertainty/clone errors. Source900, baseline554 and original/candidate216 inventories stayed exact. Runtime evidence is `coarse-association-spans-v2/execution-v1/receipts/24797612-81cf-4c83-bc94-6b8aa8a25cf7`, including `phase-reconciliation.json` and `inclusive-stage-summary.json`. Instrumented elapsed is excluded from budgets.++Directly measured same-stage sums across sequential origins were: observation endpoint source snapshot/fingerprint209.064ms, storage.total1.757ms, finish.finalLedger17.675ms, finish.rawRedecode0.000667ms; settling fingerprint454.735ms, storage.total78.823ms, finalLedger44.374ms and rawRedecode5.583ms. Endpoint.total is inclusive285.426/603.700ms for observation/settling; capture.total169.431/426.784ms and finish.total148.658/332.077ms. Shared actual saves267.446/671.246ms are not association-exclusive. Work and Entry capture/finish each ran once per phase; one deletion chunk ran additionally during settling; no replay/refault/throws occurred. All counter invariants and six reconciliation checks passed. Do not add nested spans, infer exclusive rawdecode by subtracting fetch closure, subtract cumulative maxima, or subtract these initial-generation values from original N10 medians.++Attribution is complete for this bounded phase. Duplicate raw re-decoding is only5.583ms in measured settling and does not justify another shipping trial. Fingerprint work is the largest measured association child, but no safe change or demonstrated route to the unchanged2s budgets follows. The selected original N10 result remains settling6.648267s/observation3.932553s against2s; complete original33 remains open. No further build, probe, Hex/fingerprint optimization or persistence-policy change is selected. Reliable scope barriers/global validation remain intact.++The minimal remaining decision is validation/delivery policy: either hold T-2468 on the unchanged2s gates while wider duplicate-pass performance work proceeds, or explicitly accept a documented performance exception with separate wider duplicate-pass work, retaining failed assertions/results and unchanged thresholds. No exception is inferred or applied. The inherited iPad defect remains separate from T-2468, without assertion waiver or a feature contract decision. Rune a–f remain complete, g/j in progress, h/i pending; attribution complete does not complete task j or make a commit ready. All jobs drained; no shipping source/test change, staging, commit or push occurred in this diagnostic phase.
diff --git a/specs/character-chapter-associations/investigation.md b/specs/character-chapter-associations/investigation.mdnew file mode 100644index 00000000..0ecbbe3b--- /dev/null+++ b/specs/character-chapter-associations/investigation.md@@ -0,0 +1,14 @@+# T-2468 — Saved association evidence before this feature++This is a baseline investigation, scoped to commit `39696ad851823a235749313df92f096e68735629` (live V20). The implementation now in this branch is described separately in design.md and checkpoint.md. Display design remains deferred.++| Evidence already saved | Source and limits |+| --- | --- |+| Accepted fact citations | `RecordFacts.swift` stores a `RecordFact` with statement, immutable quote, retained name key and `SourceRef.entry(UUID)` or `.genericNotes`. An Entry citation survives URL/title changes by identity, but identifies a fact's source rather than every character mention or story presence. `CharacterFactsTests.swift` verifies canonical encoding and identity. |+| Names and aliases | The live record models in `Models.swift` retain names, name keys, aliases, record-wide notes and encoded facts. `CharacterExtractionAssembler` resolves current name, retained key, then accepted aliases; proposed aliases do not route to another existing target. Matching establishes record identity, not a saved chapter occurrence. `matchingTiers`, `proposedAliasesDoNotMatch` and `factsAreKeyedToTheResolvedCharacter` pin this behavior. |+| Saved manual and linkless notes | `LibraryRepository+RecordExtraction.extractionCandidate` gathers nonempty Entry notes by Entry UUID, plus generic Work notes. It does not require a source URL. `ManualEntryRepositoryTests` covers authored chapter identity and URL-optional manual saves. Generic notes remain a distinct source rather than a chapter. |+| Reference chips | `ShareCharacterChipsView.chip` toggles `openID` to expand reference content. That action neither inserts a name nor accepts a chapter association. The record-wide note and aliases shown by the chip have no per-chapter meaning. |++The principal gap is completeness. The V20 model list has no independent chapter–record association entity. A known-record extraction bundle with no new fact or alias is discarded (`emptyBundleIsNotShown`); a name-only new record can be shown (`nameOnlyCandidateIsShown`), but that does not create an independent chapter link. Fact citations therefore cannot answer which chapters mentioned a record when no fact was added, when all proposed facts were unticked, or after citation-bearing facts are deleted. Statement edits preserve the immutable quote and source citation. Alias storage does not itself record where an alias was mentioned.++The extraction sources are saved notes, not chapter bodies. No baseline structured signal distinguishes inferred story presence from an explicit saved-note mention. The approved feature consequently saves accepted, grounded **note mentions**, preserving existing facts independently. It supports authored linkless chapters while excluding generic Work notes and non-chapter notes from chapter membership; it does not infer presence or manufacture links during migration. Current implementation and validation gaps are tracked in checkpoint.md.
diff --git a/specs/character-chapter-associations/note-first-redesign/decision_log.md b/specs/character-chapter-associations/note-first-redesign/decision_log.mdnew file mode 100644index 00000000..0e94187e--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/decision_log.md@@ -0,0 +1,61 @@+# Note-first redesign decisions++Status: Approved implementation in progress. The pre-implementation installed checkpoint and all existing work are preserved in evidence/t2468-note-first-implementation.++## Quick Decisions++| ID | Decision | Authority |+| --- | --- | --- |+| Q1 | Each suggestion shows entity/kind, chapter/source and supporting saved note. | Owner-approved direction, Sentinel_5968828cb2a881b47fd004d86a2e03. |+| Q2 | Character/place history is a compact chapter list with expandable authored notes; primary Facts becomes chapter-linked notes. | Same owner approval. |+| Q3 | Stop new fact generation, retain existing facts in a secondary area; no deletion or generated prose. | Same owner approval. |+| Q4 | Reuse extraction/grounding/matching/association persistence, with automatic recognised-character writes and creation/place Keep-Skip; no second pipeline. | Parent's current scope and existing approved T-2468 groundwork. |+| Q5 | Draft under note-first-redesign without changing the installed requirements/design or application source. | Specification-only request; preserve existing checkpoint. |+| Q6 | Proposed local window 20 and generation-bound selected reads; source and annotation stay separately labelled. | Technical proposal for review, not owner approval of exact layout/API. |+| Q7 | Generic/standalone evidence can retain an entity under existing name policy but never gains a chapter row; no new persisted general-source relation. | Proposed application of existing source semantics; requires review with this draft. |+| Q8 | Confidently recognised existing characters gain chapter links automatically in the background; approval is only for creating new characters. Places retain existing review semantics. | Explicit owner correction, Sentinel_d1c16c14741c81919c46276d02754dca. |+| Q9 | Confidence requires one coherent identity at the existing matcher’s winning tier before UUID tie-breaking; ambiguous evidence stays unresolved without gating unrelated known links. Automatic commits never install novel aliases or clear rejection. | Safety-preserving application of the owner correction, grounded in RecordMatching and current suppression/mutation code. |+| Q10 | Implement the revised redesign and deploy verified Development Devsterism to the phone for testing, without a further task-approval gate. No merge or performance waiver. | Explicit owner approval, “Approved for now. Implement this and when done deploy it to my phone for testing”, Sentinel_0088877bc64c8191a462ca16fe729750, 2026-10-19. |+| Q11 | Retain immutable display bodies in the one selected-record snapshot; render bodies on expansion and obtain a fresh editor basis only for editing. Measure 600-chapter size/read cost. | Technical implementation decision with design-critic review, 2026-10-19; no product/storage change. |+| Q12 | Hide legacy facts from all visible record/review interfaces while retaining data; remove saved-note ordinals, put dates beside titles and make Chapters (#) a native initially collapsed disclosure. Verify reopen/edit flows and update Development phone build. | Explicit owner-tested follow-up via parent, 2026-10-19; see ui-refinements.md. |+| Q13 | Correct both character/place suggestion sources and matching history rows: no Saved source # ordinal or separate Chapter # heading for titled chapters; compact date trailing right in title row; preserve untitled fallback/evidence/disclosure/data and update Development phone build. | Explicit owner-tested follow-up via parent, 2026-10-19; source-row-refinements.md. |++## Decision 1 — Follow-up full-spec draft++Context: Installed requirements deliberately deferred character/place history display and retained fact generation. The owner has now approved a different primary reading/review experience and stopping generated facts. This changes the model response contract and decision/view consumers; it is not merely adding a disclosure to a missing list.++Decision: Prepare a focused full-spec review draft with explicit evidence/legacy-data contracts and a sequenced implementation outline. Existing approved persisted schema and installed artifacts remain authoritative until implementation is separately authorized. Parent's explicit request to draft for review authorizes preparation of these documents; it does not approve their technical details or implementation.++Alternatives: A UI-only tweak cannot supply missing source-note values or record-to-chapter queries. A new knowledge/extraction engine adds unapproved scope. Automatically converting facts into notes would invent reader-authored content and violate the owner's no-deletion/no-generated-prose direction.++Consequences: The draft proposes transient evidence DTOs and selected read projections, with no new persistent models or archive version. Any discovered need for a durable policy/version change must return for review. Historical performance failures and the separate iPad defect remain unchanged.++## Decision 2 — Automatic recognised-character associations++Date: 2026-10-19. Status: Owner-approved product routing; implementation authorised in Q10.++Context: Existing assembly sends known character proposals to held review, while RecordMatching deterministically chooses a lowest UUID within a matching tier. The owner explicitly rejects repeated approval for already recognised characters.++Decision: Route unique coherent existing character matches to guarded background link persistence, with approval only for new-character creation. Keep current place review. Resolve identity confidence at the same matcher tiers before its tie-break, leave ambiguity unresolved, preserve suppression/removal/authored-note semantics and reuse current source/mutation/pending/publication lanes.++Rationale: Recognition of a saved character does not need another acceptance decision. A deterministic UUID winner alone cannot justify unattended identity selection. Background writes need narrower authority than human Keep, which may create records, install aliases or reconsider rejection.++Alternatives considered: Approval for every known character contradicts the owner; automatic place acceptance exceeds the explicit decision; auto-linking the lowest UUID can misattribute evidence; a second extraction or retry engine adds unnecessary architecture.++Consequences: Replace the actual old manual-known-review reconsideration route with optional per-link Restore link, outside ordinary approval and without an extra confirmation sheet, so historical rejections remain explicitly reversible. Tests must prove zero known-character approval rows, unique-tier identity, suppression-safe background commits, mixed-key coverage and existing note continuity. No task-approval ceremony is added. Ambiguity can wait for ordinary directory/source correction without a required identity dialog. No new schema/event kind is proposed.++## Review status++Prior note-first review identified four contract gaps, retained here: preserve original decision-key granularity; capture display evidence before actionability filtering; require strict transient source guards for redesigned no-mention Keep without changing legacy citation tolerance; recover with all captured destination heads plus selected detached heads. That earlier review does not certify the new automatic-character routing. Focused design-critic review of the revised routing resolved three gaps: explicit optional per-link Restore replaces the removed known-character review reconsideration; unresolved source/key outcomes and chapter markers prevent empty-result coverage; dual-kind split/reclassification retains place decisions. Sequential independent internal Codex peer review found no remaining material routing blocker after these corrections; no additional owner product question was required for the character correction. Its additional scope check narrowed durable unresolved-key retention to chapter evidence; non-chapter sources retain their existing fingerprint policy without a new general-source relation. The review checked source/decision authority, original keys, recovery, incomplete sources and bounded 600-row history. External Kiro review was unavailable in this environment and is not claimed. The subsequent Q10 approval authorises implementation of Q6/Q7 within the reviewed requirements/design; rendered behavior and performance still require evidence. Q5 records the earlier specification-only phase and is superseded for implementation/deployment by Q10. External ticket publishing remains blocked by the prior automatic approval rejection; no Transit mutation is attempted in this specification pass. No requirements/design/implementation approval is inferred from review comments.++## Decision 3 — One captured history snapshot++Date: 2026-10-19. Status: Technical implementation decision, reviewed by design critic.++Context: The approved display contract requires one selected-record fold with local windows. Existing associationNoteBasis reads refold the Work; using that for every expanded row repeats the inventory, while a new raw-signature freshness protocol would duplicate physical-copy and barrier correctness rules.++Decision: Capture immutable full source-note and annotation-head display values with the count and ordered descriptors in one generation. Render at most 20 collapsed rows initially; expansion reveals captured bodies without another read. Opening an editor alone obtains the existing fresh associationNoteBasis; repository writes still revalidate. Relevant owner publication replaces the captured display snapshot. No cross-save authority cache, schema or archive change is introduced.++Alternatives: Per-expansion full Work folds retain existing correctness but repeat work. New signature validation requires an additional correctness contract. Captured display values are simpler because membership, source text and annotation heads all describe the same read.++Consequences: This narrowly changes design wording from on-demand body loading to on-demand rendering and editor basis. Product behavior, saved-data authority, local windows and editing rules stay the same. Measure source/head UTF-8 bytes and elapsed cost for the real 600-chapter fixture; a large result remains a risk to report, never grounds for a budget waiver.
diff --git a/specs/character-chapter-associations/note-first-redesign/design.md b/specs/character-chapter-associations/note-first-redesign/design.mdnew file mode 100644index 00000000..1db2ce5b--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/design.md@@ -0,0 +1,123 @@+# Note-first record history — design draft++Status: Approved for implementation and Development phone testing, 2026-10-19 (Sentinel_0088877bc64c8191a462ca16fe729750). Requirements are in requirements.md. No merge or performance waiver is included.++## Pre-implementation baseline and exact navigation++The following observations describe the code at design drafting, before this redesign was implemented. Present implementation and remaining publication qualifications are recorded in `implementation.md` and `../save-time-known-links/implementation.md`; later save-time matching for both known kinds is specified by `../save-time-known-links/smolspec.md`.++| Symptom at drafting | Code-grounded cause at drafting | Existing route at drafting |+| --- | --- | --- |+| Suggestions omit chapters/full supporting note | CharacterReviewView:100–177 renders entity/kind, aliases, fact statement/quote and name-only text. CharacterReviewFact stores SourceRef, but its view does not draw a chapter/source label. CharacterReviewRow has no source-evidence presentation array. | Work reading view → Characters → Look for characters and places → Review suggestions → Keep/Skip. |+| Mention-only suggestions have little support text | AssociationMentionDecision carries Entry UUID, fingerprint and spelling keys, not note body/title. ExtractionProposal.citedRevisions retains source identities/revisions; only GroundedFact carries a quote. | Same review sheet; no hidden chapter-evidence disclosure exists. |+| Character chapter list cannot be found | WorkDetailView.recordDetailCard:2447 displays record-wide note and facts. WorkRecordPresentation has facts but no chapter collection; recordPill:2429–2441 shows a fact count and labels it as facts. LibraryRepository.chapterAssociations(entryID:) is Entry-scoped; no record-to-chapters API/view exists. | Work → tap a character/place pill expands its fact card. A fact's citation gutter can open its own cited note, but is not a membership list. |+| Saved annotation exists but is elsewhere | EntryDetailView.chapterAssociationsSection:459 renders accepted active pairs; AssociationNoteEditorView edits reader-authored text. | Open chapter editor (wide layouts may first show inspector → Edit) → Chapter links → entity → Chapter link note. Settings → Detached link notes exposes detached text. |+| Facts keep appearing | FoundationCharacterExtractionModelClient.instructions/prompt explicitly request facts; @Generable ExtractionResult character/place types include fact arrays. Grounding → assembler → bridge → decision commit writes them. | Existing extraction and record editors; not a failed chapter-list toggle. |++These symptoms match the installed groundwork's explicit non-goal of record-history layouts. The follow-up changes that scope; it does not prove saved associations are absent.++## Character routing: automatic known links, approval only for creation++The existing matcher is `RecordMatching.match` in CharacterExtractionTypes.swift:178–195: current name, then retained key, then accepted alias, with lowest UUID breaking ties within a tier. CharacterExtractionAssembler.resolve uses that rule; coordinator processing currently assembles everything into held proposals and preserves pending mentions before publication (CharacterExtractionCoordinator.swift:484–496). Known chapter links therefore currently wait for review. The owner requires direct background persistence for recognised characters instead.++Reuse the existing source extraction/grounding/assembler/coordinator and repository mutation pipeline. Classify character evidence before held-review publication: **unique coherent existing target → guarded background association commit; no match → new-character creation review; ambiguous/incoherent identity → unresolved, no arbitrary link and no new-record creation**. Scope is `.character` only. Place proposals, including known places, retain the agreed explicit Keep/Skip route. Same spelling across kinds keeps kind separation and the existing dual-kind/new-candidate suppression rules; an automatic character result cannot settle or suppress a place proposal.++Recognition uses the same normalised key and current-name → retained-key → accepted-alias precedence. Enumerate distinct logical record IDs at the first nonempty tier before the existing minimum-UUID selection; a single coherent ID is recognised, multiple IDs are ambiguous. Physical duplicate copies must pass the existing coherent-endpoint checks before becoming one logical identity. Lower-tier matches do not override a unique higher-tier match. Proposed aliases, fuzzy similarity and model confidence cannot establish an existing target. A torn/incoherent winning target is not permission to choose another tier or create a new character. Expose this confidence classification alongside the existing matcher tiers rather than introducing a competing matcher or changing place resolution.++On recognition, carry the existing original ProposalKey, exact source revisions/guards and supported accepted spellings directly to a repository operation under the exclusive lock. Re-derive the unique winning character target and source authority there; do not silently reroute if identity changed since classification. Reuse AssociationMutation, literal RecordMentionGrounding, associationAcceptanceRefusal-equivalent endpoint/rejection checks, idempotent AssociationPair event construction, pending settlement, save strategy and publication. Do not implement this by blindly invoking an unrestricted human Keep: existing applyAcceptance can install aliases and clear suppressions, while manual assembly permits rejected mention reconsideration. The automatic path has an explicit transient origin/policy and cannot create records, modify name/aliases/facts, write PairNoteVersion, clear rejection, or emit reconsidered-rejection IDs. It persists only supported unsuppressed chapter associations and its own settlement/coverage events. Existing live pairs are no-ops unless supported eligibility genuinely changes; changed evidence may update the pair basis without adding another history row. No new persisted event kind, schema or archive format is proposed.++Keep standing candidate suppression in its established new-candidate Work/kind/name-key scope, and existing-record rejection in its chapter/kind/record/spelling scope. Candidate rejection is not silently cleared; it remains effective for new candidates under current semantics rather than becoming a global ban on an already saved record. Both automatic extraction and a manually requested sweep use the no-reconsideration known-character policy. Only the optional explicit Restore link action described below may lift a rejected character association; requesting extraction alone cannot do so. Never make reconsideration a prerequisite for unrelated unsuppressed recognised links. Ignore novel proposed aliases for known-character auto-linking; accepted names/aliases still provide literal support, and existing explicit record editing remains available.++Do not put successful known-character outcomes in CharacterReviewModel/held review or durable undecided review queues. Existing held/durable known-character items encountered on restart are revalidated and settled by the same background path, one original key at a time; stale/ambiguous/suppressed items cannot be auto-acknowledged as accepted. Retry/refusal remains recoverable through existing source eligibility and publication; no persistent retry service, confirmation sheet or approval gate for known characters is introduced. A genuinely ambiguous item remains unresolved until ordinary directory/source changes or existing manual record editing disambiguates it, without blocking unrelated known characters. Model failure/unavailability/cancellation does not certify unprocessed sources. Publish saved known links immediately while preserving unresolved creation/place keys; whole-source coverage must not advance over their outstanding obligations. New-character creation Keep strictly rechecks matching: if it now uniquely matches an existing character, create nothing and let fresh recognised processing handle it, rather than requiring another known-character approval.++Provide optional **Skipped character links → Restore link** in the chapter editor’s Chapter links area, outside suggestion approval. This replaces the old manual-pass → known-row Keep reconsideration path: current code has no separate restore affordance (assembler manual mention selection, CharacterReviewModel refreshed(reconsider:), associationDecisionEvents reconsideredRejectionIDs). Present only supported known-character rejected spellings with clear chapter/record context. Restore is one explicit action, with no additional confirmation or approval sheet; it is never required for unsuppressed recognised characters. Its captured basis includes pair, supported spelling keys, observed rejection IDs and source/target guards; revalidate all under the lock and reuse the existing explicit reconsidered-rejection acceptance semantics, refusing stale or ambiguous identities without side effects. It restores only selected supported spellings and never attaches detached annotations automatically. If support is absent, do not fabricate a restorable link. New-candidate explicit manual reconsideration and place review retain their existing policies; the background known-character path never inherits their suppression bypass.++Reconcile routed results as explicit per-key outcomes before the coordinator’s producedNone/coverage decision: guarded known commit or validated already-active/no-chapter no-op, creation/place review, and unresolved ambiguity/stale/guard/save failure are distinct. Current process:373 infers producedNone coverage from absence of held rows, and preservePendingMentions:527 sees only actionable proposal.mentions; neither absence may certify an unresolved result. Capture unresolved grounded chapter keys before actionability filtering and preserve them using existing recordPendingMentionReviews/AssociationPendingReviewItem with original kind/name key, source guard and literal spelling keys. For ambiguity use targetID nil, never the matcher’s lowest UUID; the marker records coverage eligibility, not a new-candidate classification or UI approval request. Its state is reclassified against the current directory before any held row or write. Stale sources retain only valid guarded markers; leave their newer revision uncovered rather than writing stale metadata. Generic/non-chapter sources use the existing uncovered source fingerprint eligibility, since chapter pending markers cannot represent them. This slice guarantees durable unresolved-key retention for chapter-link evidence only; it does not add per-key non-chapter ambiguity history. A generic/non-chapter ambiguity is not covered in its unresolved attempt; a later genuinely successful empty attempt may settle that source under its existing fingerprint policy. It still never creates a chapter link, general-source relation or arbitrary character attachment. Retry remains within current scheduling/budgets; no new service or blanket backfill is introduced. A later empty model response cannot certify a still-relevant unresolved chapter marker; tests must prove ambiguous-only restart, empty-response retry, and successful-known plus ambiguous plus new/place mixtures. No accepted acknowledgement is invented for a suppressed or unresolved key.++At the dual-kind boundary, classify known characters before the assembler folds unmatched kinds. Background settlement applies only to `.character`; any surviving `.place` evidence retains or reconstructs its own reviewed proposal and pending obligation. Current applyDualKindRule folds two unmatched results into one displayed character proposal with both returnedKinds. If that held/folded proposal becomes known before Keep or after restart, split/reroute from captured per-kind provenance: retain the original character-key reference for automatic settlement and preserve/reconstruct the surviving place key, source guards and rejection basis before completing coverage. Do not auto-acknowledge a place via a folded character key or discard the place because a character was saved. Where both remain new, preserve the existing single creation/reclassification review and cross-kind candidate Skip scope. Reclassifying a reviewed place into an already recognised character exits ordinary Keep into guarded background routing (it requires no known-character confirmation); reclassifying into a place retains place review. Test folded-dual → directory becomes known → restart, as well as both reclassification directions. If necessary per-kind provenance is absent after restart, rederive from the existing uncovered source rather than inventing metadata or marking it covered.++For Work generic notes and standalone non-chapter Entries, known-character recognition requires no approval but creates no chapter pair or general-source relation; validate and settle the source outcome as a no-op. New characters from those sources still require creation approval. No source-free record note is used as extraction provenance. Existing chapter-link removal and detached annotation rules apply equally to automatically saved links.++## Evidence presentation and decision basis++Extend value DTOs in the existing candidate → extractor → assembler → routed background-commit or held-review path with `ProposalSourceEvidence`: SourceRef, exact source text/fingerprint, captured chapter eligibility and a display descriptor (chapter identity/designation/title/date or generic/standalone label), supported spellings and stable source order. Metadata is local input, never model-generated. Keep the model request to the existing Work title plus one saved note; do not send authored annotations or old facts back as source text.++Capture display provenance before the assembler actionability filter, which currently drops already-active sources with no novel alias/fact/mention. Carry that provenance through GroundedCandidate, grouped ExtractionProposal, ledger merge/reclassification and CharacterReviewRow; attach it only to an independently actionable result under its original decision key; retain review display evidence only for new-character/place rows and use exact guarded provenance for background character writes. Informational evidence cannot create a proposal or additional writes by itself. Display every contributing source, including sources with no novel fact/alias and sources whose pair is already active when that source contributes to a multi-source review. Do not derive source display only from the filtered actionable `mentions` array. Keep the current mentions/source guards/review acknowledgements as write authority, separate from presentation provenance.++For rows that require review, preserve a stable captured evidence snapshot. Opening a live source uses its stable Entry identity. A current read may label it changed/missing but cannot replace the captured text/fingerprint or acceptance basis; commit-time guards remain authoritative. Redesigned Keep and background character persistence must strictly revalidate existence, coherent typed ownership and exact revision for every contributing decision-basis source, including generic, standalone and alias-only/no-mention decisions; an empty mentions array cannot bypass this check. Preserve existing authority checks rather than treating informational display evidence as new association writes. Keep this transient source guard distinct from currentlyHolds legacy fact-citation tolerance, which permits a missing Entry, and retain underlying legacy fact editing/dangling-citation policy while hiding its UI under Q12. Additional displayed context outside the original decision basis is labelled informational and cannot settle pending work or authorize a write. A missing captured body is shown as unavailable, never rebuilt from a generated fact quote. Source disclosure starts with compact labels/counts; all contributing sources and exact full text remain reachable through Show more/expansion without another model call. Use the same proposed 20-row window for large evidence groups.++Deduplication keys:++- Decision unit: preserve the original ProposalKey (kind, normalized name key), reviewedKey, returnedKinds, mentions, rejection basis and pending acknowledgement obligations. Distinct original keys retain independent settlement/rejection obligations. Known-character keys settle through successful guarded background writes; new-character/place keys retain Keep/Skip. Do not merge keys or acknowledge a sibling key without validating and settling its own result. Typed resolved identity labels the target and deduplicates active history, not original decisions. Preserve matching precedence and cross-kind separation.+- Evidence block: source identity plus exact fingerprint within one original decision unit; union distinct supported spellings. Do not merge distinct Entry UUIDs because text, URL or display title match.+- Active history: AssociationPair (Work, Entry, kind, record). Physical copies, repeated occurrences, multiple acceptances and annotation heads do not add chapter rows or inflate counts.+- Conflicting source revisions/physical variants do not become a fabricated common source; retain stale/review-needed distinctions. No UUID-dedup shortcuts before existing physical validation.++## Record history and navigation++Retain the Work's existing character/place pills and kind-specific identity. Expanding one opens a shared record-history component under the existing record-wide note. The primary section is **Chapters (N)**, replacing the fact-body area in reading view. Remove the pill's fact-count badge/accessibility claim rather than relabelling it as chapters; show the exact chapter count once the selected history is loaded, without forcing an eager read for every unopened record. Legacy fact reading/editor controls are hidden under Q12; draft facts and repository fact edit/delete APIs remain intact without a visible entry point.++A chapter row has the Work's existing chapter key/title/date fallback and a compact exact saved-note preview (not a generated summary). Expansion exposes separately labelled **Saved chapter note** and **Your link note**. Optional annotations remain useful but are not required for a chapter row; an empty annotation is not filled from the source note. Opening the chapter uses the current onSelectEntry route. Editing an annotation uses the existing AssociationNoteEditorModel/View and captured current head basis from either entry point. Distinct conflicting heads remain visible until explicit resolution. Empty/error/review-needed states must differ from a loaded empty list.++Use the existing chapter spine/order derivation, then capture order and stable Entry UUID tie-breaks; do not lexically sort chapter titles or invent numbers. An unnumbered live chapter uses its available title or “Unnumbered chapter · noted <date>”; date/capture-position context disambiguates identical titles, while stable UUID is internal identity. Missing/incoherent endpoints do not become current active rows merely to show annotations; show a review-needed notice and offer existing Detached link notes. Existing facts with dangling sources retain their exact stored values and are hidden under Q12.++Proposed bounded UI: 20 rows initially, then **Show 20 more (N remaining)**; annotation/source bodies collapsed except the reader's chosen rows. With 600 chapters, 30 windows (the initial window plus 29 Show more actions) reach all rows. Disclosure state keys are typed pair IDs, never list indices. Changing selected record cancels/ignores stale reads. Publication refresh recomputes the visible window against stable IDs and preserves the chosen record; deleted rows leave focus predictably. This is a reviewable local presentation choice, not a new global search/filter product.++## Reads and publication++Add a typed record-history value read to the existing LibraryProviding.swift/repository/MockLibraryProvider seam. Do not add a silent default empty result to satisfy adapters; unsupported/failing reads must remain an explicit error, not “0 chapters”. Inputs are Work ID, RecordKind and record UUID. Reuse AssociationStorageInventory/ledger/note fold and AssociationEndpointInventory under one locked read, filtering selected pairs and batch-validating all encountered physical endpoints. Never call chapterAssociations once per chapter, nor rebuild the entire ledger for every rendered row.++Return one immutable value snapshot for the selected record: count, ordered compact row descriptors/previews, annotation-presence/conflict indicators, unavailable/review-needed status and publication generation. UI displays a 20-row prefix and expands that window locally; Show more does not reread/refold the ledger. The captured snapshot retains immutable source-note and annotation-head display values from that same fold. Full bodies are rendered only when a row expands; expanding and Show more do not refetch or refold. Opening the annotation editor obtains a fresh basis through the existing associationNoteBasis read, and every write rederives authority. Count, descriptors and displayed bodies belong to the same captured generation; publication replaces that snapshot rather than mixing newer text into old membership. Measure the real 600-chapter snapshot’s retained UTF-8 bytes and read cost before UI integration (Decision 3). No ModelContext or @Model escapes to views, no new repository pagination/cache service is introduced, and no write occurs on expansion/refresh/navigation. The value projection is display-only; writes always rederive current authority, and publication invalidates it on relevant saves/rollback/reconcile. Never skip barriers for an empty acceptance set.++Integrate lazy loads in WorkDetailModel record expansion and existing publication generation. Annotation Save refreshes record history and Entry detail through the same owner publication path; source save/removal, record edits, import and reconcile invalidate the affected history generation. Keep existing live active-pair validation and detached recovery as the truth; a fact citation cannot fill a missing pair.++## Stop new fact generation; retain saved facts++Use one names-only constrained result for the existing model call, with separate character/place arrays. Remove fact-generation instructions and generated-fact fields from that response contract. Keep the current client seam, availability handling, attempt timeout, source batching/caps, canonical grounding and matcher tier precedence, routing recognised characters automatically and retaining creation/place review. Do not introduce a second pass or ask the model to author notes.++Keep legacy GroundedFact/RecordFact/archive readers where compatibility and explicit editing require them. New extraction adapters/assembler/background character commits/review decisions submit empty `facts` and `untickedFacts`; held-row merge/reclassification cannot resurrect generated facts from an obsolete shape. Test the live request/prompt contract as well as the commit boundary. Existing fact bytes, suppressions, ranking/chip consumers and source citations remain untouched; do not rewrite facts as annotations or silently convert them into accepted associations.++Held proposal DTOs are in-memory, not the durable pending-review format. Preserve durable source guards, original keys, acknowledgements and composite coverage, routing known-character obligations to background settlement; no blanket coverage invalidation/backfill solely to remove fact generation. Restart must recover undecided source eligibility through the current pending metadata. Coverage still certifies a successfully settled source, not the existence of a generated fact. Cancellation/failure/unavailability cannot certify it. If implementation uncovers a necessary persisted policy/version change, stop and return it for review rather than altering V21/archive20 in this slice.++## Source categories and removal++| Category | Review evidence | Saved record history |+| --- | --- | --- |+| Live chapter, including URL-free/no designation | Exact note, chapter fallback, kind/entity/spellings | One current accepted typed pair; source/annotation separately labelled. |+| Work generic note | “Work note — no chapter” and full original text | New-character creation or place Keep may retain record/name/alias under existing policy; known characters require no review and no data enrichment here; no chapter row and no invented general-source association. Work notes remain accessible from their existing Work area. |+| Standalone non-chapter Entry | Its note title/date plus “Standalone note — no chapter link” | Same no-chapter rule; cannot inflate chapter count. |+| Missing/torn chapter or stale evidence | Captured context and unavailable/changed status | No fabricated live link or wrong destination; preserve raw annotations and existing review-needed rules. |+| Source-free record-wide note | Not extraction provenance or an auto-linked chapter | Keep its separate record-note field. |+| Existing fact with missing/unknown source | No new suggestion derived from it | Preserve stored statement/quote/citation unchanged; render no legacy fact view (Q12). |++Final literal support loss removes the active pair immediately in the existing save, not after another model call. Detached annotation text/context survives and never counts as historic/current membership. New accepted support does not attach old text automatically; existing same-pair explicit recovery parents all captured current destination heads plus explicitly selected detached heads. Unselected detached groups remain untouched; incomplete or stale destination/selected-head bases still refuse recovery. Preserve per-chapter/per-kind/per-spelling existing-record rejection; candidate-name suppression retains its existing Work/kind scope. Only explicit Restore link may lift a known-character rejection; a manual extraction request uses the same suppression-respecting automatic known-character lane; merely expanding history never does.++## Integration parity and validation++| Seam | Required change/retained contract |+| --- | --- |+| Core candidate read/CharacterExtractionSource; Foundation client/result; CharacterGrounding | Source metadata/value provenance, names-only output, unchanged literal grounding and bounds. |+| CharacterExtractionAssembler/Bridge/Ledger/Coordinator | All-source evidence preservation through grouping, merge, retarget/reclassify; no fact writes; guarded background character routing, per-key pending settlement/coverage/rejection semantics; place review retained. |+| CharacterReviewModel/View | Source blocks for new-character and place rows; recognised characters absent from approval queues; explicit target and atomic stale refusal. |+| LibraryProviding, repository, AppLibraryModel/provider/mocks, WorkDetailModel | Selected batched record-history read and generation-bound value snapshots/local windows; shared publication refresh. |+| WorkDetailView/CharacterEditorView/EntryDetailView | Native collapsible Chapters view and hidden legacy fact sections/counts; same annotation editor and existing chapter navigation on phone/iPad/Mac (Q12). |+| Settings/DetachedAssociationNotesModel/View | Preserve copy/recovery reachability and exact authored text; no new auto-recovery. |+| Backup/import/migration/RecordCopy/ranking/chips | No new schema/format, no data conversion or membership invented from old facts/copies; maintain existing behavior. |++Acceptance tests must exercise the actual coordinator → repository → publication path: one known current-name match, retained-key match and accepted-alias match each produces a saved chapter link with zero review rows/confirmation, on automatic and manual extraction. Verify a unique higher-tier match beats lower-tier candidates, same-tier logical-ID ties remain unresolved despite the existing lowest-UUID matcher, torn/physical-conflict/missing/wrong-Work targets never auto-link, and independent recognised characters still commit. No match requires new-character approval and creates no record before Keep; a candidate that becomes known before Keep creates no duplicate and returns to fresh automatic routing. Known places still wait for Keep; character/place dual-return cases preserve kind-specific keys and suppressions.++Assert automatic known processing never creates a character, installs a proposed alias, clears candidate or mention rejection, writes facts/annotations, or resurrects detached text. Cover automatic/manual sweeps respecting historical chapter spelling rejection, skipped new candidate suppression, supported unblocked spellings, final mention removal, later support restoration with detached heads unchanged, replay/restart idempotence, old held known-character keys, optional scoped Restore link without a blanket review/confirmation gate, source-save/rename/rejection races under the write lock, save failure/rollback and partial mixed known/new/place settlement without premature coverage. Ambiguity has no confirmation gate for all known characters and no fallback new-character creation. Generic/standalone recognised sources settle without review or chapter membership.++Tests should cover source evidence with no facts, same record via accepted aliases across multiple notes with independent original-key background settlement/restart, already-active source A plus newly actionable source B with A retained as review context where review applies and as source provenance for automatic character processing, same-text distinct Entries, non-chapter/generic/missing/torn sources, kind switches, stale source/target and Keep/Skip atomicity, including source deletion/change for generic/standalone/alias-only decisions with no mentions. Assert zero generated facts for new automatic/manual/reclassified paths while old fact/note/archive bytes round-trip exactly. Re-run existing final-mention removal, detached-head/Clear/recovery, rejection/manual reconsideration and pending restart/order cases without weakened assertions.++Use deterministic permutations for idempotent evidence grouping and typed pair counts, with existing Swift Testing; no new PBT library. Add a real SwiftData 600-chapter fixture: initial 20, all 30 windows, stable refresh and captured-generation invalidation, one shared fold/batched endpoint validation per generation, and no per-row fetch loop. Render actual review/history/edit routes at accessibility sizes on phone/iPad/Mac with isolated fixtures. Implementation validation follows AGENTS phase selection; the owner authorised implementation and Development phone deployment for testing in Q10. Existing failing 2 s N10 gates and incomplete full 33/pre-push acceptance remain recorded, never treated as a waiver.++Risk: selected ledger validation over a real 600-chapter history may exceed existing read budgets | Verify: early isolated fixture and call-count/elapsed measurements before UI integration | If wrong: report measured costs and revise the selected read; do not add cross-save caches or relax gates.++## Q12 reading presentation amendment++The owner-tested UI refinements in [ui-refinements.md](ui-refinements.md) are authoritative for presentation: legacy facts remain in storage and drafts but their reading/editor/review views are hidden; saved-note ordinals are removed; dates sit beside chapter titles using the existing spine as reference. The native initially collapsed Chapters (#) disclosure owns the actual rows, expanded bodies and pagination controls while counts stay visible. Collapsing/reopening and note Save retain the selected snapshot/window and existing editor authority. No persistence, extraction, matching or schema changes follow from this amendment.++## Q13 source-row correction++[Source-row refinements](source-row-refinements.md) supersede Q12's intrinsic-width/vertical-fallback date layout and redundant designation labels. Both character/place suggestion sources and matching history rows use actual chapter title with a trailing-right compact date in one full-width row. The leading title may wrap; the date remains in that row. No visible source ordinal or separate chapter-number heading appears for titled chapters; truly untitled chapters retain one title fallback. Internal Entry/source identities, order, exact evidence and chapter keys remain intact, including distinct rows with identical visible titles. Rendered verification must include both suggestion kinds, not merely entity history.
diff --git a/specs/character-chapter-associations/note-first-redesign/implementation.md b/specs/character-chapter-associations/note-first-redesign/implementation.mdnew file mode 100644index 00000000..f142b599--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/implementation.md@@ -0,0 +1,91 @@+# Approved note-first implementation++## Phase 1: extraction and automatic character links++Domain implementation and bounded static review completed 2026-10-19. Unique coherent existing characters use guarded association persistence without a review row. New characters retain approval; places retain Keep/Skip. Ambiguous chapter keys remain unresolved. Names-only model output and saved source evidence replace new generated facts; existing fact bytes remain. Cancellation publishes completed writes without starting another key or prematurely recording coverage.++Focused native verification: 13 declarations, 22 expanded executions, zero failures/skips; 916 extended source inputs unchanged across the run. Package checkpoints passed 177 declarations/314 executions and 83 declarations/112 executions; these cohorts overlap and must not be summed. An earlier native checkpoint passed 84 ordinary coordinator/legacy review declarations before the final pending-state and cancellation fixes. The final composed selection must refresh their qualification.++Raw failures and successful results are retained. Local durable receipt: `../evidence/t2468-note-first-implementation/phase1/receipt.json` relative to the worktree. Final read-only critic found no material phase-1 blocker, including the cancellation boundary.++Tasks 1–2 are complete for the domain layer. Rendered source evidence, the optional Skipped character links/Restore link route, and reader history remain explicitly assigned to task 5; final composed validation and Development phone deployment remain task 6. No code commit, push, merge, new installation or performance waiver follows from this checkpoint.++## Phase 2: selected history++Tasks 3–4 are complete: a selected-record read with compact value snapshots, exact availability/count semantics, shared chapter ordering and local 20-row windows. A real SwiftData fixture must link one selected record to all 600 chapters and establish bounded Work-scoped inventory reads.++### Phase 2 Core checkpoint++The focused five-suite Core run passed 44 declarations/46 expanded executions with no failures/errors/skips in 190.92 seconds including dependent-product compilation. Package source hashes were unchanged. The six new history declarations expanded to eight executions, covering both typed 600-chapter histories.++In the retained-context synthetic fixture, character baseline inventory plus endpoint batch took 0.2084 seconds and the full projection 0.4516 seconds; place timings were 0.2072 and 0.4474 seconds. Each captured display payload held 324,490 UTF-8 bytes of source and annotation text. These are UTF-8 payload sizes, not allocator peaks or original performance-gate acceptance. Tests asserted one fold, two event queries, two note queries and three endpoint queries, plus exact whole-backup equality including saved facts.++Evidence: `/tmp/t2468-ledger-build/note-first-history-core/`. Native selected-model and shared-order verification subsequently passed 67 declarations/75 expanded executions, no failures/skips or reported runtime warnings, including the four new model tests and all seven original ordering tests. Its 910 actual-start/end inputs were unchanged; localization and nine nonshipping spec prototypes separately matched the prior phase baseline, during-run and after-run hashes. The actual-start manifest was not rewritten. Evidence: `/tmp/t2468-ledger-build/note-first-history-native/`. Final bounded static review is clear for tasks 3–4; task 5 UI implementation is active. No material read/model blocker remains. The comprehensive post-gate handoff manifest contains 950 current nonignored product/test/tool/resource inputs; it does not retroactively replace the native start manifest.++## Phase 3: review and history UI++Production UI is implemented; composed targeted validation is in progress. Separate child views render captured suggestion sources, typed selected chapter history and optional skipped-link restoration. Both Work-detail entry points observe the owner publication generation. Existing facts stay in a secondary labelled area, and the existing annotation editor retains fresh Save/Cancel authority.++Precompile review identified and resolved three material issues: absent visible chapter designations made duplicate-title chapters indistinguishable; overlapping skipped-link reads could reinsert a row after Restore; and the Entry-detail intent guard omitted its annotation child. The final bounded precompile review is clear. The controlled overlapping-read regression uses a mock provider; real repository authority is covered separately, and rendered Restore remains pending. No runtime or final UI acceptance is inferred from static review.++### Rendered checkpoints and refresh correction++The first Task-5 native cohort passed all 15 declarations with zero failures/skips. The first four rendered journeys passed automatic recognised-character linking and the independent Restore action, including preserved unsaved parent fields and detached annotation bytes. Two failures identified a pill hit-target problem in the new test driver and an accessibility identifier inherited by the source disclosure container; both were corrected without removing assertions.++The subsequent seven-journey cohort executed all expected cases: six passed, one failed. Exact saved-source presentation, names-only review, sweep, place/history, reclassification, cross-kind hints and alias handling are qualified by their individual receipts. The remaining history failure occurred after annotation Save: replacing the whole selected-history snapshot with a loading placeholder clamped the scroll viewport. Native hierarchy evidence confirmed that the Work remained open while the history subtree had left the viewport.++The narrow correction retains the same-selection captured snapshot during refresh, displays an Updating indicator and blocks editor creation until fresh data arrives. Selection changes, cancellation and errors still clear the capture; request and generation guards remain. A controlled suspended-refresh regression asserts retained rows, window and expanded source, then fresh annotation/editor authority. Read-only critic review found no material blocker. Its native and rendered verification remains pending; no green result is inferred from review.++The final composed package cohort passed exactly 225 expected JUnit declarations, with zero failures/errors/skips or missing/unexpected declarations. Package source is unchanged by the subsequent app-only refresh correction. Parameter-expanded execution counts were not independently emitted by this aggregate run and are not claimed. Local evidence: `../evidence/t2468-note-first-implementation/final-composition/core/receipt.json` and `phase3/ui-seven/`.++### Composed source and host checks++The final composed read-only critic review found no blocker, critical or major correctness issue in the note-first paths. The fixed fast cohort then passed all 456 expected unique JUnit declarations, with zero missing/unexpected identifiers, failures, errors or skips, in 11.52 seconds including discovery/build. All 956 captured inputs stayed unchanged. Neither aggregate JUnit receipt independently emits a parameter-expanded execution count.++Xcode MCP built the Development Mac app and test harness successfully. A subsequent app-only build passed on the settled localisation catalogue in 19.38 seconds with all 956 inputs unchanged; the app and embedded Mac extension passed strict signature verification with their Development identities and original team. The Mac app was not launched for this compile check. Evidence: `../evidence/t2468-note-first-implementation/deployment-preparation/mac-final-receipt.json`.++The corrected phone history journey has passed annotation Save visibility and chapter navigation with all original assertions retained. Its enclosing native/rendered cohort is still running; remaining platform checks and the authorised Development phone deployment are pending.++### Final phone composition++The history/editor cohort passed all 10 expected declarations: five native selected-history tests and five rendered journeys, zero failures/skips, with all 956 source inputs unchanged. The full history journey retained annotation visibility after Save and completed chapter navigation. The next composition passed exactly 108 declarations/117 independently observed expanded executions: 97 native routing/review declarations expanded to 106 executions, plus 11 rendered journeys. No expected identifier was missing or unexpected, and all 956 inputs remained unchanged.++The source-qualified phone UI union is 24 unique methods: 17 extraction, two outcome and five association-note journeys. Earlier failed attempts remain retained; corrected successful runs replace their runtime proof. The earlier recognised-character/Restore successes are qualified by unchanged relevant implementation blobs rather than being presented as a final whole-app rerun. Native phase-3 union is 16 declarations (Skipped 5, Entry publication 6, history 5); do not add the earlier 15 and later history 5. The refreshed routing/review 97 is a separate cohort.++Evidence: `../evidence/t2468-note-first-implementation/phase3/history-editor-green/`, `final-composition/native-and-rendered/` and `phase3/phone-ui-union.json`. Mac and iPad rendered checks and authorised phone deployment remain pending. This is targeted Development qualification; unfiltered pre-commit/pre-push and original performance gates are not claimed.++### Long-note acceptance and Mac host limitation++A review found that the rendered fixtures were short, despite the task's explicit long-note acceptance requirement. A test-only method now appends 1,543 ASCII/multiline bytes through the real saved Entry editor, asserts the original NFD/whitespace prefix and complete draft bytes, explicitly Updates, verifies the complete refreshed history source byte-for-byte and opens/cancels annotation editing. It uses the proven history-row → Open chapter route, so it does not query an unrealized chapter-spine row. Narrow critic review is clear. The phone method passed in 87.04 seconds (127.22 seconds including build/startup); all 956 captured inputs stayed unchanged. This extends the qualified phone union to 25 unique methods.++Only `AssociationNotesUITests.swift` changed after the previous frozen composition. All shipping, package and native-test blobs remain identical; previous Core225, fast456 and native receipts retain their covered source qualification. No production or fixture change was made for this additional test.++The first selected Mac UI command compiled and signed successfully but its runner timed out while enabling automation mode before any of seven expected methods executed. It exited 2; the synthetic runner failure is not an application test-case failure or a pass. The console was unlocked, and `DevToolsSecurity -status` reported developer tooling disabled. No host permissions or security settings were changed. Evidence: `../evidence/t2468-note-first-implementation/phase3/mac-ui-initialization-failed/`. Xcode's supported test-list action returned all eight current method identifiers; its own selected-test action may be checked separately using existing authorization after the independent iPad run.++### Cancelled refresh replacement++The retained-ready snapshot exposed one additional cancellation edge: an in-flight refresh had already recorded its publication generation, so a replacement request for the same generation could incorrectly deduplicate before the cancelled read finished. The completed-read deduplication now also requires that no refresh is in flight. Request and typed-selection guards still reject stale responses. A controlled noncooperative-read regression verifies replacement completion, retained window/expansion/editor authority, stale-response rejection and subsequent completed-generation deduplication. The final narrow critic review is clear.++On the current 956-input source manifest `6e7d00fe12df8cbedb583b22b5db3318a9142bacd8fcdf3c27ddbd2a4c9ebad1`, all six selected-history model declarations plus the phone history journey passed (7 expected identifiers, no failures/skips/missing/unexpected tests; 138.66 seconds including build). All inputs stayed unchanged. The current iPad long-note journey, refreshed Mac compile and Development deployment are still pending. Core/fast package blobs and the routing/review native cohort are unchanged by this app-model/test-only correction, so their earlier composed receipts remain source-qualified rather than being presented as reruns. Evidence: `../evidence/t2468-note-first-implementation/phase3/history-cancellation-green/` and `final-composition/cancellation-change-qualification.json`.++The current iPad long-note journey subsequently passed (1/1 expected, no failures/skips, 125.79 seconds including build), with all 956 inputs unchanged. The current signed Development Mac app and embedded Mac extension then compiled through Xcode MCP in 48.25 seconds, with strict signatures verified and the same source manifest unchanged. This build did not launch the app. The eight observed Mac UI identifiers are now being exercised once through Xcode's supported selected-test action using existing authorization; no host developer/security setting is changed. Evidence: `phase3/ipad-long-note-current-guard-green/`, `deployment-preparation/mac-cancellation-receipt.json`, and `phase3/mac-gui-validation/` under the local evidence root.++### Mac UI qualification remains blocked++The one supported Xcode GUI-context attempt also ended before test execution. Xcode MCP reported all eight exact selected methods **not run**, with zero passed/failed/skipped selected methods; the native result separately records one runner-initialisation failure: “Timed out while enabling automation mode.” This is a host automation startup blocker, not a passing application test or eight application failures. The current app/test harness compiled; all 956 inputs remained unchanged. Developer-tooling status remained disabled, and no host permission/security settings were changed. No further retry is queued. Durable receipt and native bundle: `../evidence/t2468-note-first-implementation/phase3/mac-gui-validation/`.++The approved Development phone deployment proceeds independently. Task 5's Mac runtime qualification remains open; the existing original performance budgets and unfiltered pre-push phone/iPad acceptance also remain open. No commit/push/merge or performance waiver is inferred from the testing deployment.++### Development deployment completed — 2026-10-19++Xcode MCP installed and launched **Devsterism** on the current Makefile-selected paired phone using `Asterism Development`, with no debugger. The preceding signed phone build passed in 42.35 seconds; the warm RunProject action returned “The app was launched successfully.” Both signed products retained their verified Development bundle/team/App Group identities, with the app's separate Development CloudKit container. All 956 product/test/tool/resource inputs remained unchanged at source manifest `6e7d00fe12df8cbedb583b22b5db3318a9142bacd8fcdf3c27ddbd2a4c9ebad1`; the complete source ZIP and binary hashes are retained. No fixture launch arguments or environment were enabled.++Released Asterism's before/after metadata was identical, and the Development shared library App Group container path was unchanged. iOS reported a changed private app-container path; only metadata was inspected, so no claim about private-container contents or normal launch writes is made. No uninstall, reset or migration command was issued. Both owned simulators are shut down and owned build/test jobs have drained. No code was staged, committed, pushed or merged.++Testing deployment is complete under Q10. Selected current native/phone/iPad checks and source-qualified package/routing/UI receipts are retained without summing overlapping cohorts. The Mac UI startup blocker, original performance gates and future unfiltered commit/pre-push gates remain explicitly open. No further product decision is needed to try this Development build. Local installation receipt: `../evidence/t2468-note-first-implementation/phone-deployment/installation-receipt.json`.++Transit publication was not retried: automatic approval review previously denied publishing nonpublic source/device/performance details. All new findings and deployment evidence remain local; the existing ticket is T-2468.++### Owner-tested presentation follow-up++Q12 refinements are implemented and deployed as Development Devsterism 0.7.0 (1), installed source 701c2799. Hidden legacy data, native chapter disclosure, date/title layout and note editing passed focused native/phone/iPad verification; current signed Mac/phone builds passed. Exact outcomes, the retained test-driver failure/retry, localization-only source qualification and installation receipt are in [ui-refinements-implementation.md](ui-refinements-implementation.md). Existing Mac UI/performance/future publication qualifications remain open.
diff --git a/specs/character-chapter-associations/note-first-redesign/requirements.md b/specs/character-chapter-associations/note-first-redesign/requirements.mdnew file mode 100644index 00000000..bcb29870--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/requirements.md@@ -0,0 +1,82 @@+# T-2468 — Note-first character and place history++Status: **Approved for implementation, 2026-10-19.** The owner approved the note-first direction in Sentinel_5968828cb2a881b47fd004d86a2e03 and automatic links for already recognised characters in Sentinel_d1c16c14741c81919c46276d02754dca. The owner authorised implementation and Development phone deployment for testing in Sentinel_0088877bc64c8191a462ca16fe729750. No merge or performance waiver is included.++## Introduction++Readers need to see which saved note supports a suggested character or place, then find that record's accepted chapters without reading a wall of facts. This follow-up presents the existing chapter associations and reader-written notes as the main record history. Existing confidently recognised characters gain note-derived chapter links automatically in the background. Only creating a new character requires approval; known characters have no approval queue or mandatory confirmation. New extraction identifies named entities without generating fact statements; existing facts remain stored while hidden from the interface (Q12). Place proposals retain their existing Keep/Skip semantics; the character automation decision does not authorise automatic place acceptance.++## Non-goals++- Merge or performance acceptance as part of the implementation/testing deployment. Development installation for testing is authorised by Q10.+- Deleting, rewriting, synthesizing or automatically migrating existing facts or authored prose.+- Reading chapter bodies, inferred story presence, automatic creation of new characters, automatic acceptance of places or an automatic link-note author.+- New sync, association-ledger, archive or note-conflict architecture; cross-record search or ranking redesign.+- Treating fact citations, generic Work notes or standalone non-chapter notes as chapter membership.+- Repairing the inherited iPad scroll defect or changing existing performance assertions.++## Definitions++A **source note** is the exact saved chapter/Entry note or Work generic note used for an extraction attempt, identified by SourceRef and text fingerprint. An **annotation** is optional reader-authored PairNoteVersion text for one typed chapter–record pair. A **record note** is the existing source-free character/place-wide note. A **legacy fact** is existing stored fact text and citation, irrespective of whether its source still exists. A chapter row denotes a currently supported persisted association, whether automatically saved for a known character or explicitly accepted through a creation/place decision, not every place a name could occur in the story. A confidently recognised character is one coherent same-Work character identity uniquely matched at the winning current-name, retained-key or accepted-alias tier; UUID tie-breaking alone is not confidence.++## 0. Known characters link automatically++**User story:** As a reader, I want recognised characters to gain their chapter links without repeatedly approving characters I already have.++1. <a name="0.1"></a>WHEN grounded saved chapter-note evidence uniquely matches a coherent existing character at the winning established matcher tier, the system SHALL create or update its supported chapter link in the background without a review row, approval queue or mandatory confirmation, for automatic and manually requested extraction alike.+2. <a name="0.2"></a>WHEN no existing character matches and the candidate is not suppressed, the system SHALL request approval before creating a new character; WHEN the winning tier contains multiple character identities or the target/source is incoherent, the system SHALL neither choose an arbitrary identity nor treat it as a new character, and SHALL leave only that evidence unresolved without blocking independent recognised links.+3. <a name="0.3"></a>BEFORE a background write, the system SHALL revalidate the exact saved source, unique typed identity, literal support and standing rejections under the repository write lock; stale, suppressed or changed-target evidence SHALL cause no mutation or suppression clear and retain its appropriate retry or suppression state.+4. <a name="0.4"></a>WHEN background character processing succeeds, the system SHALL publish the saved link and settle only its own durable original-key obligations; repeated runs, restart or replay SHALL not duplicate links, create character records, install proposed aliases, change authored notes or clear unrelated pending decisions.+5. <a name="0.5"></a>The system SHALL retain existing approval/Keep-Skip behaviour for both new and existing place proposals; matching a place SHALL NOT become automatic because a character was recognised.+6. <a name="0.6"></a>WHEN a source contains unresolved or mixed character/place outcomes, the system SHALL save independent recognised links without certifying unresolved keys as processed; unresolved grounded chapter keys SHALL survive restart without an approval queue, and a dual-kind result SHALL retain the place decision when its character becomes recognised.++## 1. Reviewable suggestion evidence++**User story:** As a reader, I want to see the source behind each suggestion so that approving a new character or deciding a place proposal is informed.++1. <a name="1.1"></a>WHEN reviewing a new-character or place suggestion, the system SHALL identify the entity, character/place kind, existing-record target when present, and every contributing source note represented by that decision.+2. <a name="1.2"></a>FOR EACH source, the system SHALL show its chapter designation/title or an explicit non-chapter/missing-source label, the exact saved note text with a path to read it fully, and the supported entity spelling; mention-only suggestions SHALL have the same source visibility as other suggestions.+3. <a name="1.3"></a>WITHIN one suggestion and its original decision key, repeated occurrences or accepted aliases in one source revision SHALL share one source block retaining distinct supporting spellings; separate original decision keys SHALL retain independent settlement and rejection scope (Keep/Skip where review applies), and distinct chapters SHALL remain distinct even when URL or text is identical.+4. <a name="1.4"></a>WHEN a decision-basis saved source or typed target changes during review, the system SHALL distinguish captured evidence from current content, refuse stale Keep atomically, retain review input and allow stale Skip under the existing policy; it SHALL NOT silently substitute newer text beneath an older acceptance basis.++## 2. Record-to-chapter navigation++**User story:** As a reader, I want a compact history for a character or place so that I can find its chapters and my notes.++1. <a name="2.1"></a>WHEN opening a character/place from its Work, the system SHALL present its accepted chapter-linked notes as the primary history, with exact active-chapter count and stable chapter navigation; unannotated accepted links SHALL still appear.+2. <a name="2.2"></a>EACH chapter row SHALL distinguish the saved source chapter note from its optional authored annotation; expanding the row SHALL expose the full available source note and annotation heads without generating prose or combining conflicting heads into one note.+3. <a name="2.3"></a>WHEN editing or clearing an annotation from either record history or Chapter links, the system SHALL use the same explicit Save/Cancel behavior and conflict/recovery rules; annotation edits SHALL NOT change membership, source-note text or extraction eligibility.+4. <a name="2.4"></a>FOR a record linked to 600 chapters, the system SHALL initially collapse the native Chapters (#) disclosure; expanding it SHALL render no more than the current 20-row window with the remaining count and Show more action, permitting every row to be reached without expanding all note bodies. Collapse/reopen and relevant refresh SHALL preserve the selected record, stable row identities, local pagination and editing access (Q12).+5. <a name="2.5"></a>The system SHALL use the Work's existing chapter ordering, retain distinct stable Entry row identities even when titles match, omit saved-note/source ordinals and separate Chapter # headings for titled chapters, and place the date at the trailing right of the same full-width title row. The title MAY wrap; the date SHALL NOT become a separate content-list line. Truly untitled chapters SHALL use one sensible title fallback. This applies to character/place suggestion sources and matching history rows on phone, iPad and Mac (Q13).++## 3. Existing facts and new extraction++**User story:** As a reader, I want chapter-linked notes to replace generated facts in the main view without losing what I already saved.++1. <a name="3.1"></a>WHEN the new automatic or manual extraction runs, the system SHALL propose named characters/places and grounded source evidence without asking the model to generate fact statements, paraphrases, chapter summaries or annotations.+2. <a name="3.2"></a>WHEN a new proposal is kept or skipped, the system SHALL preserve existing facts and fact suppressions and SHALL NOT append a generated fact or copy source text into an annotation; new-character creation and place choices SHALL remain reviewable; confidently recognised character links SHALL follow Section 0 without review. Automatic known-character linking SHALL not install proposed aliases or rewrite names.+3. <a name="3.3"></a>The system SHALL preserve existing facts, quotes, citations and suppressions in stored records and draft Save payloads, while hiding their statements and controls from record reading, record editing and suggestion review interfaces (Q12). Unrelated Save/Cancel, combine and kind-conversion operations SHALL NOT discard this hidden data.+4. <a name="3.4"></a>The system SHALL retain record-wide notes as separately labelled reader-authored content, without presenting them as a chapter-specific source or annotation.++## 4. Removal, rejection and incomplete sources++**User story:** As a reader, I want chapter history to stay truthful while my annotations and decisions survive changes.++1. <a name="4.1"></a>WHEN the final supported mention is removed from the saved source note, the system SHALL remove the active chapter row without deleting its authored annotation; removing only one of several supporting occurrences SHALL retain the row.+2. <a name="4.2"></a>WHEN an annotation becomes detached through source/endpoint removal, the system SHALL retain exact text and original context under Detached link notes, excluding it from active chapter counts; restored support SHALL NOT auto-attach old text, and recovery SHALL remain explicit.+3. <a name="4.3"></a>WHEN a prior existing-record rejection or a place Skip applies, the system SHALL continue to suppress equivalent spelling evidence only in that chapter and kind under the existing policy, retaining unrelated chapters/new spellings and an optional explicit restoration action; a background pass or merely requesting extraction SHALL NOT clear or bypass standing character-link rejection. Previously rejected new candidates SHALL retain their existing Work/kind/key suppression scope, without resurrection by the new automatic lane.+4. <a name="4.4"></a>WHERE a real chapter lacks designation, title or URL, the system SHALL preserve its identity and navigation using an unnumbered/date fallback; a missing/torn chapter SHALL show unavailable/review-needed context without inventing membership, deleting annotations or navigating to a different chapter.+5. <a name="4.5"></a>WHEN a proposal comes from Work generic notes or a standalone non-chapter note, the system SHALL label that source explicitly and SHALL NOT add a chapter row or invent an Unknown chapter; a source-free record note SHALL remain accessible, while a dangling legacy fact and its quote/citation SHALL remain stored unchanged and hidden under Q12.+6. <a name="4.6"></a>WHEN the reader explicitly restores a previously skipped known-character link, the system SHALL revalidate its current identity, source support and selected rejection basis, restore only that supported chapter/kind/record/spelling scope, and preserve authored annotations without automatic reattachment; this optional action SHALL NOT be a confirmation gate for ordinary recognised characters.++## 5. Processing and saved-data continuity++**User story:** As a reader, I want the redesigned views to use the data and processing I already have.++1. <a name="5.1"></a>The system SHALL preserve existing extraction availability, automatic/manual scheduling, bounds, matcher tier precedence, atomic writes and durable original-key/pending-review/coverage behaviour, with Section 0 routing known characters directly to guarded persistence and only new characters to creation approval without an additional model call for source display.+2. <a name="5.2"></a>WHEN replaying equivalent accepted evidence, the system SHALL retain one active chapter row per typed pair without duplicate annotations, decisions or fact writes; sync/import ambiguity SHALL keep the established inactive/review-needed outcome.+3. <a name="5.3"></a>The system SHALL preserve all existing association/note/fact bytes and archive round trips without automatic deletion/backfill or a storage-format change solely to render this redesign.++## Save-time known links amendment — owner approved 2026-10-19++Successful chapter-note saves automatically persist complete-name links to coherent known characters **and known places** within that work, subject to the existing recognition tiers, explicit spelling rejections and safe source identity. This is the bounded exception to the AI place-review requirement: newly discovered places and characters still require review. App, extension and queued replay share one transaction; no AI or new entity creation is added to the extension. Complete-name source maintenance, exact pending-key settlement and final saved-content conflict choices are specified in [save-time known links](../save-time-known-links/smolspec.md). This approval also resumes pr-pilot after implementation and required gate assessment; it does not waive the recorded performance or Mac runtime qualifications.
diff --git a/specs/character-chapter-associations/note-first-redesign/source-row-implementation.md b/specs/character-chapter-associations/note-first-redesign/source-row-implementation.mdnew file mode 100644index 00000000..518c334a--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/source-row-implementation.md@@ -0,0 +1,75 @@+# Q13 suggestion-source and chapter-row verification++Status: implemented, focused verification complete, and corrected Development app installed and launched. The owner-tested 701c2799 Development build is preserved in the preceding UI-refinement evidence. No merge, staging or commit is part of this correction.++## Scope++The previous cleanup missed ProposalSourceEvidenceView, shared by character and place suggestions. It still renders Saved source ordinals and a stacked full timestamp. RecordHistoryView also renders a separate chapter designation and an intrinsic-width title/date row. Q13 corrects both components with actual title, compact date trailing right in the same full-width row and a single fallback title for genuinely untitled chapters. Internal source IDs/order/keys, exact notes, data and native Chapters disclosure/More/editor remain intact.++## Verification requirements++Actual character suggestion, actual place suggestion and matching history rows must be exercised and visually inspected from retained rendered screenshots. Do not infer review coverage from history or a shared component alone. Record exact platform/surface, assertions and source hashes for each proof. Preserve prior failure/retry history without claiming old snapshots are new runs.++## Existing qualifications++Mac UI remains unqualified after earlier automation initialization failures; no blind retry or host setting changes. Original performance and future full commit/pre-push gates remain open. No Transit publication of nonpublic details is attempted after the prior automatic approval denial; new evidence remains local.++## Frozen source review++The narrow design critic reviewed the seven-file correction against the installed source archive and found no blocker, major or critical issue. All 959 product, test and tooling inputs match source manifest `1a596b90b886be59ccddd189ae38110b802dc4e5329726ef95ea7fe60e37215a`. Two files are new: the shared row and native presentation tests. No package, schema, signing or project input changed.++Both actual suggestion kinds call `ProposalSourceEvidenceView`; it and `RecordHistoryView` now use the same full-width row. The leading title wraps and the compact date retains the trailing edge without a vertical fallback. Native fallback tests cover exact authored titles, designation fallback, unnumbered chapters and generic/standalone distinctions. The review establishes source correctness; rendered verification and deployment remain pending.++Evidence is retained under `evidence/t2468-source-row-refinements/` in the parent task directory, including the exact follow-up diff, source manifest, archive and review proof. Actual runtime manifests must remain as captured, even if Xcode later synchronizes localization resources.++## Verification selection and ownership++Phone checkpoint A selects three native presentation declarations and four rendered journeys: character suggestion, place suggestion, character history with 24 rows and editing, and place history with two chapters. iPad checkpoint B repeats the four rendered journeys. Each checkpoint has a 600-second bound, serial destinations, two compiler jobs and the task-owned native cache. The phone and iPad use the dedicated T2468 simulator identities; no physical library is involved in fixtures.++The fixed fast cohort is selected by the repository's unchanged 456-identifier manifest. It will run once after the focused checkpoints release their actual processes. Signed Mac compilation then uses Xcode MCP, followed by a separate signed Development phone build and the owner-authorized normal install and launch. Mac UI startup, original performance attribution and future full publication gates remain separate qualifications.++## First phone attempt and bounded driver correction++Checkpoint A exited 2 after 375.084 seconds. All seven selected identifiers ran with no skips or missing tests. The three native presentation tests and both rendered history journeys passed. Both suggestion journeys failed when their test driver used XCTest's string subscript with an identifier longer than its 128-character limit. The semantic disclosure button aggregates descendant identifiers; it is not a raw source identity. The retained accessibility tree contains the actual title/date leaf identifiers and correct title/date geometry.++The authorized correction is limited to the test driver: locate the title leaf with an identifier predicate, derive its raw base from that leaf, and query date and exact-source leaves with predicates. Keep all title, geometry, byte equality, heading absence and sibling decision assertions. Repeat only the two failed phone journeys, then run the four planned iPad journeys. The first attempt, screenshots and accessibility trees remain retained; no product change is needed for this query limitation.++The main agent inspected both first-attempt phone history screenshots. The place view shows Harbor, Chapters (2), Arrival with Today at the right, and the exact expanded saved note. The character view shows Alice, Chapters (24), title-only Arrival/Return/Shared title rows with trailing dates, and the expanded exact chapter 6 note. These images establish those rendered surfaces only; suggestion verification still awaits the corrected driver.++## Predicate-query retry and visual evidence qualification++The two suggestion journeys passed on the predicate-query test source `e0efdc41b16de27ab973e389eae2c678b8dffa050c4bb8ada65ff01f01a0700b`; the process exited 0 after 190.835 seconds. Production and the passing native/history tests were unchanged. The main agent inspected both retained suggestion images. They show the correct kind context and title/date layout, but part of the chapter row and expanded chapter body is below the viewport, especially for the place case. A passed accessibility byte assertion is not a full visual proof of offscreen content.++Retain these context images and add one further capture per kind after scrolling the actual chapter title/date and expanded source body fully into view. This is another test-driver evidence correction only; preserve the existing assertions and product source. Repeat the two phone review journeys and then the four iPad journeys after the capture correction. Do not claim the current images show the full chapter source.++## Full-viewport capture qualification++The two viewport-proof journeys passed, exit 0 after 227.951 seconds, on source `14e8d539215d9a116d00f68c33e9c59c725d2be5a03b59ba3c0cb3b01e0a7cce`. All 959 inputs remained unchanged. The main agent inspected both second images. Place review clearly shows the entire wrapped chapter title, Today at the trailing right, supported spelling Kestrel Head, selected Place kind, and the full expanded chapter note. The character image has its title partly occluded by the sticky navigation bar despite accessibility hittability and list/window containment. It does not qualify as a full unobscured row image.++The final capture-only driver correction excludes the navigation bar from the usable viewport and uses bounded small coordinate drags instead of page-sized swipes. Repeat only the character journey on phone; the already verified place image remains valid, and all four iPad journeys exercise the shared capture driver. Product inputs remain unchanged throughout these driver refinements. No runtime assertion or evidence from prior attempts is discarded.++## Accepted phone visual proof++The final character-only proof exited 0 after 132.685 seconds on source `a36c3f7f937d7c72f6c74b810456c0e11f7796fdad4e4eaccf366670358423c1`, with its exact identifier passed, no skips and all 959 inputs unchanged. The narrow design critic confirmed that only the test driver changed from the production-cleared source and that every existing oracle remains intact.++The main agent independently viewed the final character image: the full three-line chapter title is below the navigation bar, Today sits at its trailing right beside the first line, supported spelling Brede and the selected Character kind identify the surface, and the full expanded saved source is visible. Together with the accepted place image and both history images, all four required phone surfaces now have direct visual proof. The iPad checkpoint will exercise the four corresponding surfaces on the final driver source.++## iPad, fast and signed compile outcomes++The four iPad journeys exited 0 after 374.174 seconds with exactly four expected identifiers, no failures, skips, missing or unexpected tests, and all 959 source inputs unchanged. The main agent viewed both full suggestion-source captures and both history captures directly. Both review kinds show the full wrapped actual title, compact date at the trailing right and exact expanded chapter body. Character history shows Chapters (24), title-only rows and the exact expanded note; place history shows Harbor, Chapters (2), title-only Arrival/Return rows, trailing dates and the expanded exact note. Both owned simulators were verified shut down after their actual processes exited.++The fixed fast gate passed exactly 456 unique expected declarations in 9.497 seconds with no failure, error or skip entries and no source changes. The current Development Mac app and embedded Mac extension compiled through Xcode MCP in 18.993 seconds; both strict signatures and team/bundle identities passed. The app was not launched and no Mac UI test is claimed.++Xcode synchronized only Localizable.xcstrings during the Mac build: it retired the unused `Chapter %@` and `Saved source %lld` keys. No retained translation entry, Swift source, test, package or configuration changed. Original runtime manifests remain intact; settled build source is 959 inputs, SHA `d397256441d53ca86165159e15f4c1e1f147dcf2594274759229d9aa3a8fc95b`.++The separate Development phone preflight build passed through Xcode MCP in 18.116 seconds. The actual product path was derived from that successful build log, then app/extension strict signatures, isolated Development bundle IDs, team, App Group and CloudKit entitlements were verified. Source remained unchanged across the phone build. The owner-authorized normal install and launch subsequently completed successfully, as recorded below.++## Deployment outcome++Xcode MCP confirmed `The app was launched successfully.` with no build errors. Devsterism 0.7.0 (1), bundle `me.nore.ig.Asterism.dev`, team `V24684SCZN`, is installed and launched on the current Makefile-selected paired iPhone. Source remained exactly 959 inputs at `d397256441d53ca86165159e15f4c1e1f147dcf2594274759229d9aa3a8fc95b` across the signed phone build and launch; strict signed app and embedded extension products were identical before and after RunProject. No fixture launch arguments or environment were enabled.++The pending request was left running rather than duplicated. A read-only lock-state diagnostic reported a required passcode and an unlock was requested; the same Xcode request then completed successfully. No host or device permissions/settings were changed. Released Asterism app metadata and the Development library App Group path remained identical before and after. iOS reported a different private app-container path during the in-place update; no container contents were inspected and no claim of byte-level contents identity is made. No uninstall, reset or migration command was issued.++The final receipt, signed identity proofs, source archive and per-run evidence are retained locally in the parent task's `evidence/t2468-source-row-refinements/`. See `phone-deployment/installation-receipt.json`, `verification-summary.json`, `visual-verification.json` and `source-archive.json`. All eight accepted screenshots are listed by exact surface in the visual proof. Rune reports the Q13 correction task complete with no pending stream. All task-owned test/build commands exited and both owned simulators are shut down; the physical app is left launched for owner testing.++No staging, commit, push or merge occurred. The branch and HEAD remain `feature/T-2468-association-ledger` at `82d3f6df6032152525e7476827fc90de94a5ee97`, with existing work preserved. Mac UI automation startup remains unqualified; original performance and future unfiltered commit/pre-push gates remain open. No Transit update was attempted after the earlier automatic approval rejection of nonpublic disclosure; the new evidence stays local.
diff --git a/specs/character-chapter-associations/note-first-redesign/source-row-refinements-tasks.md b/specs/character-chapter-associations/note-first-redesign/source-row-refinements-tasks.mdnew file mode 100644index 00000000..a0ae0f94--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/source-row-refinements-tasks.md@@ -0,0 +1,15 @@+---+references:+ - specs/character-chapter-associations/note-first-redesign/source-row-refinements.md+ - specs/character-chapter-associations/note-first-redesign/requirements.md+ - specs/character-chapter-associations/note-first-redesign/design.md+ - specs/character-chapter-associations/note-first-redesign/decision_log.md+---+# T-2468 source-row correction++## Suggestion and history row presentation++- [x] 1. Both suggestion kinds and history rows show title with trailing date and no source ordinal or redundant chapter heading+ - Implement Q13 source-row-refinements.md and verify actual rendered character/place review plus matching history, exact source text, untitled fallback, collapsed disclosure/pagination and editing after reopen. Preserve data and capture actual screenshots for both suggestion kinds and history.+ - Stream: 1+ - References: specs/character-chapter-associations/note-first-redesign/source-row-refinements.md
diff --git a/specs/character-chapter-associations/note-first-redesign/source-row-refinements.md b/specs/character-chapter-associations/note-first-redesign/source-row-refinements.mdnew file mode 100644index 00000000..8f9fee6d--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/source-row-refinements.md@@ -0,0 +1,16 @@+# T-2468 suggestion-source and chapter-row correction++Authorised owner feedback after testing the installed 701c2799 Development build, 2026-10-19 (Q13). The shared suggestion-source component still shows source ordinals and a stacked date; both character and place suggestions must be corrected, together with matching history rows.++## Required behavior++- Character AND place suggestion source rows MUST omit visible Saved source # ordinals. Internal stable source identities/order remain unchanged.+- Every titled chapter source/history row MUST show its actual chapter title without a separate Chapter # or redundant chapter-heading line. Truly untitled chapters MUST retain a sensible single-title fallback (existing designation when available, otherwise Unnamed/Unnumbered chapter). Generic and standalone source distinctions remain clear.+- The date MUST occupy the trailing right side of the same full-width title row. It MUST NOT become a separate list/content line. Allow the leading title to wrap without clipping at accessibility sizes; use existing compact date conventions. Preserve captured date data and full exact source-note evidence.+- Preserve native initially collapsed Chapters disclosure, exact/incomplete counts, pagination, source expansion, note editing, legacy-data retention and all persistence/extraction/signing behavior. No merge or storage changes.++## Scope and checks++Inspect ProposalSourceEvidenceView.swift for both CharacterReviewView paths, RecordHistoryView.swift for character/place history, and any matching chapter-list presentation that repeats the redundant designation. Keep changes focused. Add actual rendered character and place review journeys, including expanded exact source notes, explicit absence of Saved source ordinals and redundant chapter headings, and date/title placement. Verify title-only and untitled fallback source/history cases with meaningful native/value or rendered tests. Retain history disclosure/reopen/edit/SaveCancel and pagination coverage. Inspect retained screenshots of BOTH suggestion kinds and matching history rows; report exactly which surfaces/platforms were visually verified.++Use bounded focused Makefile checks/private caches/dedicated simulators and fresh actual resource boundaries. Run fixed fast once on final source. Refresh current signed Mac app/embedded extension compile via Xcode MCP; known Mac UI automation startup qualification remains open without blind retries or host-permission changes. Install/launch the corrected verified Development Devsterism build through the established Xcode MCP route, current Makefile phone selection, strict signed identity and before/after app metadata checks. Preserve the existing library App Group; do not inspect real library contents.
diff --git a/specs/character-chapter-associations/note-first-redesign/tasks.md b/specs/character-chapter-associations/note-first-redesign/tasks.mdnew file mode 100644index 00000000..30d226ea--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/tasks.md@@ -0,0 +1,48 @@+---+references:+ - specs/character-chapter-associations/note-first-redesign/requirements.md+ - specs/character-chapter-associations/note-first-redesign/design.md+ - specs/character-chapter-associations/note-first-redesign/decision_log.md+---+# T-2468 note-first approved implementation++## Extraction and automatic character links++- [x] 1. RED: character routing, evidence and names-only contract <!-- id:8xhrose -->+ - Test known current-name/retained-key/accepted-alias matches saving links with no review row/confirmation on automatic and manual extraction, unique winning-tier confidence before UUID tie-breaking, ambiguity/torn targets remaining unresolved while unrelated recognised links succeed, new-character creation requiring approval, and known places retaining Keep/Skip. Cover historical rejection preservation and optional guarded per-link restoration outside approval, no alias installation, mixed pending/coverage, ambiguous-only restart/empty-model retry and folded dual-kind→known-character split/place preservation, old known held-key restart and guarded commit races/rollback. Add tests for no-fact suggestions with all source labels/text, within-key alias/repeated evidence dedup, independent original-key settlement/restart, active source A plus+ - actionable source B provenance, distinct same-text Entries, kind reclassification/target identity, generic/standalone/missing/stale sources and strict no-mention Keep guards. Assert client prompt/result and automatic/manual/bridge commits produce no new facts; legacy fact/note bytes untouched. Refs:0.*,1.*,3.*,4.5,5.1.+ - Stream: 1+ - References: specs/character-chapter-associations/note-first-redesign/requirements.md, specs/character-chapter-associations/note-first-redesign/design.md, specs/character-chapter-associations/note-first-redesign/decision_log.md++- [x] 2. GREEN: reuse the extraction lane and guarded automatic character commit <!-- id:8xhrosf -->+ - Classify existing character identity at matcher winning tiers, route only unique coherent recognised characters to repository association persistence before held-review publication, and reserve character approval for creation. Reuse mutation/save/publication/key settlement; explicitly prevent automatic alias/record creation or rejection clears and retain existing place review; move explicit known-link reconsideration to optional Skipped character links → Restore link with no confirmation sheet. Extend source presentation provenance through candidate/extractor/grounding/assembler/held merge/review; implement names-only model output and empty generated-fact decisions. Preserve cancellation/bounds, matching, suppressions and durable pending-review/coverage. Refs:0.*,1.*,3.*,4.3,5.*.+ - Stream: 1+ - References: specs/character-chapter-associations/note-first-redesign/requirements.md, specs/character-chapter-associations/note-first-redesign/design.md, specs/character-chapter-associations/note-first-redesign/decision_log.md++## Selected record-history projection++- [x] 3. RED: selected record history at scale <!-- id:8xhrosg -->+ - Build 600-chapter real SwiftData and typed duplicate/conflict fixtures; verify exact counts, 20-row windows/all rows, generation refresh, batching/no per-row ledger fetch, source/annotation distinction, final support loss, detached recovery/Clear/replay and old fact/archive preservation. Measure before choosing read optimizations. Refs:2.*,4.*,5.2–5.3.+ - Stream: 1+ - References: specs/character-chapter-associations/note-first-redesign/requirements.md, specs/character-chapter-associations/note-first-redesign/design.md, specs/character-chapter-associations/note-first-redesign/decision_log.md++- [x] 4. GREEN: repository projection/publication <!-- id:8xhrosh -->+ - Add selected record-history read and provider/mock parity, generation-bound value snapshots/local windows and shared refresh. Reuse validated ledger/endpoints/note heads; add no persistent schema/format or cross-save authority cache. Refs:2.*,4.*,5.*.+ - Stream: 1+ - References: specs/character-chapter-associations/note-first-redesign/requirements.md, specs/character-chapter-associations/note-first-redesign/design.md, specs/character-chapter-associations/note-first-redesign/decision_log.md++## Review and history UI++- [-] 5. RED then GREEN: actual UI routes <!-- id:8xhrosi -->+ - Current qualification: phone/iPad journeys pass with source-qualified receipts; Mac rendered runtime is blocked before test execution by automation-mode startup. Signed current Mac app and harness compile. No host permissions changed.+ - Assert recognised character links appear in history without entering review; render source blocks in new-character/place suggestions, primary chapter-note history under character/place pills, hidden legacy facts with preserved stored/draft values in reading/edit surfaces (Q12), expanded source/annotation views and the existing Save/Cancel/recovery editor. Cover phone/iPad/Mac navigation, accessibility sizes, stale selected record/generation and long notes without altering inherited scroll assertions. Refs:0.*,1.*,2.*,3.3–3.4,4.*.+ - Stream: 1+ - References: specs/character-chapter-associations/note-first-redesign/requirements.md, specs/character-chapter-associations/note-first-redesign/design.md, specs/character-chapter-associations/note-first-redesign/decision_log.md++## Composed validation and Development deployment++- [x] 6. Composed validation and review <!-- id:8xhrosj -->+ - Outcome: implemented and installed/launched as Devsterism for owner testing on 2026-10-19 under Q10. Local receipt and open Mac/performance/future commit/pre-push qualifications are in implementation.md. No commit or push made.+ - Run AGENTS-appropriate affected Core/native/rendered suites and fixed fast on final composed source; retain exact failures/warnings/counts. Run the separate required code-commit gates before any code commit. Full unfiltered phone/iPad UI belongs to pre-push. Reassess performance against unchanged gates and review documentation. Q10 authorises Development phone deployment for testing after implementation and validation; follow the repository Xcode MCP installation route. Merge and Personal device runs require their own applicable authorisation.+ - Stream: 1+ - References: specs/character-chapter-associations/note-first-redesign/requirements.md, specs/character-chapter-associations/note-first-redesign/design.md, specs/character-chapter-associations/note-first-redesign/decision_log.md
diff --git a/specs/character-chapter-associations/note-first-redesign/ui-refinements-implementation.md b/specs/character-chapter-associations/note-first-redesign/ui-refinements-implementation.mdnew file mode 100644index 00000000..785dd030--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/ui-refinements-implementation.md@@ -0,0 +1,57 @@+# T-2468 owner-tested UI refinement evidence++Status: implemented, verified with focused checks and installed/launched as Development Devsterism for owner testing on 2026-10-19. Owner authorisation is recorded as Q12 in decision_log.md; the prior testing installation remains preserved.++## Scope++Hide legacy fact prose, counts and edit controls from record reading/editing/review and chapter-editor fact-count labels, retaining underlying models, draft payloads and archive data. Remove saved-note ordinals, align date/title using the Work spine, and make the actual selected chapter history a native initially collapsed disclosure. Preserve count/incomplete states, source bodies, pagination and editing after reopening.++## Baseline++The installed source checkpoint contained 956 inputs, manifest SHA `6e7d00fe12df8cbedb583b22b5db3318a9142bacd8fcdf3c27ddbd2a4c9ebad1`. It is retained in `../evidence/t2468-note-first-ui-refinements/source-before.json` and the existing `../evidence/t2468-note-first-implementation/final-composition/verified-source-6e7d00fe.zip`. Existing uncommitted work stays on feature/T-2468-association-ledger, HEAD 82d3f6df6032152525e7476827fc90de94a5ee97. No staging, commits or merge are part of this follow-up.++## Remaining qualification++The prior Mac UI attempts stopped before selected tests executed because automation mode did not initialise. Host permissions were unchanged; no new blind retry is planned. The original performance and future unfiltered commit/pre-push gates remain open. Transit publication of nonpublic details remains blocked by prior automatic approval review; all new evidence is local.++## Frozen implementation review++The narrow production review found no material correctness or scope issue in the 957-input source snapshot. Two test-oracle hardenings then made chapter-count lookup independent of the native accessibility element type and required actual conversion/combine completion and destination identity before checking hidden fact data. The critic qualified this test-only delta; no production input changed after its source clearance. Final pre-runtime manifest: `7eae83eadd77a89a5104dc48d0969359d321b724bf9e3fe14a9342d05a97f66c`, 957 inputs, retained under `../evidence/t2468-note-first-ui-refinements/`.++The bounded serial runtime plan is: native selected-history7 declarations + real legacy-preservation1 declaration/3 arguments + phone disclosure/edit journey1; six affected phone UI methods; then two iPad history/long-note methods. These represent seven unique UI methods across nine platform invocations. No passing runtime result is inferred from static review. A standard-text compact-row screenshot is not added as an independent gate; only actual available attachments and accessibility-size journeys will be described as observed.++## Native preservation and phone disclosure gate++The first serial gate exited0 in 188.66 seconds including compilation: all 9 expected declarations/11 independently observed expanded executions passed, with no failures/skips/missing/unexpected identifiers. Native history7 and hidden-legacy1/3 arguments cover typed disclosure state and real repository data preservation; the phone history journey verifies collapsed content absence,20→24 pagination, collapse/reopen retaining row/source state, and fresh annotation Cancel/Save after reopening. All 957 inputs stayed unchanged at 7eae83ea. Inherited actor-isolation warnings in unrelated test files are retained; no new changed-file warning was observed. Evidence: `../evidence/t2468-note-first-ui-refinements/native-history-green/`. The six affected phone methods and two iPad invocations remain pending.++## Six-method phone gate and retained failure++The phone batch exited2 after 433.48 seconds. All6 expected methods executed,5 passed and the long-note method failed; no skips/missing identifiers, and all 957 inputs remained unchanged at 7eae83ea. The passing methods cover hidden facts with aliases/chapter navigation, combine, cited-place names with fact counts hidden, exact-source/names-only review and editor kind conversion.++The long-note failure was a test-driver destination race: immediately after Update it queried whether the Work title existed and selected the wide Open Work fallback before phone navigation settled. The retained failure tree shows the Work title, count24 and full explicitly saved source body already present, with the old Entry-detail fallback control gone. No production navigation change is indicated. A bounded test-only wait correction and one-method phone retry are required before iPad validation and deployment; all exact source bytes/count/edit assertions remain. Raw failed evidence is retained locally rather than reported as a green batch.++The final test-only correction waits for the actual Work destination before considering the wide-column Open Work fallback. A short-lived OR-predicate candidate was rejected in review and was never run. The accepted929a4270 source differs from7eae83ea only in AssociationNotesUITests.swift; shipping production inputs and the five passing B methods/native cohort are unchanged. The critic found no remaining issue in that narrow delta. The isolated phone long-note retry and subsequent iPad run retain every exact-byte/count/editor assertion.++The isolated phone retry passed 1/1 with no skips in 133.17 seconds, all 957 inputs unchanged at 929a4270. Its full source-byte and link-note editor assertions passed after the corrected Work-first wait. The five passing methods from the initial phone batch are qualified by unchanged covered code/methods; the earlier phone disclosure journey is likewise unchanged. Current follow-up phone coverage is7 unique selected journeys across those receipts, not a claim that the initial six-method batch passed. Evidence: `phone-first/` and `phone-long-green/` under the local refinement evidence root. The two iPad invocations are now active.++## Final iPad and fast checks++Both selected iPad methods passed 2/2 with no failures/skips/missing identifiers in 238.24 seconds; all 957 inputs remained929a4270. The long-note case passed111.21 seconds including the deliberate bounded wide return wait. The retained phone and iPad screenshots show adjacent title/date rows at accessibility size, no saved-note ordinal, and separate full source/annotation/actions without visible horizontal clipping. They are observations of the retained screenshots, not an unrun normal-size or Mac claim. Both owned simulators are Shutdown and implementation test jobs drained.++The final fixed fast cohort then exited0 in 9.55 seconds: all 456 expected unique JUnit declarations matched the fixed manifest, with zero missing/unexpected/failures/errors/skips and unchanged957 inputs. The empty legacy tests.xml contains no tests; the actual declarations come from tests-swift-testing.xml. Parameter-expanded counts are not independently emitted and are not claimed. Evidence: `../evidence/t2468-note-first-ui-refinements/fast/`. Current signed Mac compilation is active; physical Development deployment remains pending.++## Signed build qualification++Xcode MCP compiled the current Development Mac app and embedded Mac extension successfully in 27.79 seconds; both strict signatures, bundle IDs and team were verified without launching the Mac app/tests. During this build Xcode synchronized3 new and6 retired literal UI localization keys, changing only Localizable.xcstrings. Existing translations on retained keys were unchanged; these interface resources are distinct from stored fact data. All validated Swift production/test, package and configuration inputs are unchanged. The actual runtime manifests remain intact; `localization-qualification.json` records this narrow resource delta. Settled957-input source manifest:701c27991d3c35f1265d3cfc6c6931f1206b6658d4be8a5dd301d0eea0bc6d88.++The signed Development phone build then passed in 18.07 seconds with that settled source unchanged. Strict verification confirmed Devsterism app and embedded extension, Development bundle/team/App Group identities and the app's separate Development CloudKit container. The source scheme has no enabled fixture arguments/environment. The authorised Xcode MCP in-place installation/normal launch is active; completion is not inferred from the successful build.++## Installation completed++Xcode MCP confirmed successful installation/launch on the current Makefile-selected paired phone, with no debugger: **Devsterism 0.7.0 (1)**, bundle `me.nore.ig.Asterism.dev`, team V24684SCZN. Installed source: 957 inputs, SHA `701c27991d3c35f1265d3cfc6c6931f1206b6658d4be8a5dd301d0eea0bc6d88`; the complete source ZIP and signed app/extension binary hashes are preserved. Source and signed products stayed unchanged across the phone build/run. No fixture arguments/environment were enabled.++Before/after released-Asterism metadata was identical, and the Development library App Group container path was unchanged. iOS reported a different private app-container path; contents were not inspected, and no byte-identity claim is made about normal launch writes. No uninstall/reset/migration command, staging, commit, push or merge occurred. Both owned test simulators are Shutdown and owned heavy jobs drained.++The requested refinements and Development testing deployment are complete. Remaining qualification is explicit: no new Mac UI attempt after the known host automation startup failures, original performance gates remain open, and future unfiltered commit/pre-push checks are not waived. The initial five-pass/one-driver-failure phone batch and its successful isolated retry are retained honestly. No new product decision is required.++Local receipt: `../evidence/t2468-note-first-ui-refinements/phone-deployment/installation-receipt.json`; final check summary: `../evidence/t2468-note-first-ui-refinements/verification-summary.json`. Transit publication was not retried because the prior automatic approval review denied nonpublic implementation/device/performance disclosure; evidence remains local.
diff --git a/specs/character-chapter-associations/note-first-redesign/ui-refinements-tasks.md b/specs/character-chapter-associations/note-first-redesign/ui-refinements-tasks.mdnew file mode 100644index 00000000..3d0c3ee4--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/ui-refinements-tasks.md@@ -0,0 +1,15 @@+---+references:+ - specs/character-chapter-associations/note-first-redesign/ui-refinements.md+ - specs/character-chapter-associations/note-first-redesign/requirements.md+ - specs/character-chapter-associations/note-first-redesign/design.md+ - specs/character-chapter-associations/note-first-redesign/decision_log.md+---+# T-2468 owner-tested UI refinements++## Reading presentation++- [x] 1. Hidden legacy facts and compact collapsible chapter history retain data and editing+ - Implement the authorised ui-refinements.md behavior, retain source evidence and exact/incomplete counts, remove saved-note ordinals and use spine-inspired title/date layout. Verify native fact preservation and phone/iPad disclosure, pagination, reopen/edit/save/cancel journeys; retain inherited substantive checks and report exact IDs/outcomes.+ - Stream: 1+ - References: specs/character-chapter-associations/note-first-redesign/ui-refinements.md
diff --git a/specs/character-chapter-associations/note-first-redesign/ui-refinements.md b/specs/character-chapter-associations/note-first-redesign/ui-refinements.mdnew file mode 100644index 00000000..2bdaba9d--- /dev/null+++ b/specs/character-chapter-associations/note-first-redesign/ui-refinements.md@@ -0,0 +1,20 @@+# T-2468 reading presentation refinements++Owner request after testing the installed Development build, 2026-10-19. This is an authorised presentation-only amendment to the existing approved note-first design; no new product decision or storage/API change is needed.++## Requirements++- The interface MUST hide legacy fact statements, quotes, citations and fact-edit controls on record reading, record editing and suggestion review surfaces. Every underlying fact, quote, citation, suppression and draft value MUST be preserved under the existing operation semantics. Unrelated Save/Cancel MUST leave hidden values unchanged; explicit kind conversion and combine MUST retain their data using the existing destination/rebinding rules, without a new deletion caused by hiding the controls. Source-note evidence, record notes and chapter-link annotations remain visible through their existing routes.+- Chapter rows MUST omit the “Saved note #” ordinal. The chapter title and its existing date MUST share the compact title line using the Work spine presentation as a reference, adapting without clipping at accessibility sizes. Chapter designation, exact source text and distinct annotation labelling remain available.+- The “Chapters (#)” heading MUST be a native disclosure which controls the actual row list, expanded source bodies and Show more action. It SHOULD initially be collapsed for a newly selected record. Exact/incomplete counts remain visible in the header. Relevant refresh and note Save MUST preserve the selected section's expansion, local pagination and per-row expansion; switching typed record selection MUST not expose the previous record's rows.+- Expanding, collapsing and reopening MUST preserve access to note editing and its fresh Save/Cancel authority. Counts, 20-row pagination, source evidence, restore links and accessibility identities/actions remain available.++## Affected implementation and verification++`RecordHistoryView.swift` owns the header/list and row presentation; compare existing Work spine title/date layout before changing it. `WorkDetailView.swift`, `CharacterEditorView.swift` and `CharacterReviewView.swift` render legacy facts; hide those views without changing their models or commit authority. Existing selected-history native tests and `AssociationNotesUITests.swift` cover history refresh/edit flows. Adjust test drivers for the deliberate collapsed default while retaining their substantive assertions; add explicit disclosure toggle/reopen and hidden-fact preservation checks. Inspect inherited fact-citation/edit journeys and qualify affected replacements against the new visibility requirement rather than reporting obsolete visible-fact assertions as green.++Focused runtime selection must cover disclosure/pagination, collapse/reopen then note edit Save/Cancel, source evidence, existing-fact preservation after unrelated save, record editing and phone/iPad layout. Record exact selected/observed identifiers and warnings. Unchanged Core packages need no broad repeat. Refresh signed Mac app/extension compilation via Xcode MCP; prior Mac UI automation startup blocker remains open without a new blind retry or host-permission changes. Then install/launch the verified Development app through the established Xcode MCP route, using current Makefile phone selection and signed identity/container metadata checks.++## Risks and boundaries++DisclosureGroup can propagate identifiers to children: keep the semantic header addressable without swallowing row actions. SwiftUI list refresh can clamp scroll state: retain existing snapshot and editor authority. Hidden draft facts must remain part of the underlying Save payload; prove this with a real native preservation assertion. This amendment changes no persistence, archive format, extraction, matcher, signing or released-app identity. No merge, deletion, or new performance acceptance is authorised.
diff --git a/specs/character-chapter-associations/performance-attribution.md b/specs/character-chapter-associations/performance-attribution.mdnew file mode 100644index 00000000..fe8c6772--- /dev/null+++ b/specs/character-chapter-associations/performance-attribution.md@@ -0,0 +1,187 @@+# T-2468 measured performance attribution++The approved reliable-association implementation is continuing qualification against the unchanged original performance gates. The owner explicitly approved comparable measurements and recoverable fixes within scope, followed by the remaining publication gates, pr-pilot, merge and regular Release installation. Matched baseline/current Release runs and reviewed coarse timing are preserved below. They have not yet demonstrated a fix meeting both two-second limits.++The current 971-input original N10 remains failed: observation median **4.148841s**, settling median **6.765119s**, each against **2s**. The earlier 33-declaration dependent selection is historical; the current default 52-declaration publication gate has also failed, as recorded below. Current 970-input correctness results and the separately bound restored900 history are preserved in checkpoint.md. The inherited iPad scroll defect stays separate by the parent's prior decision, with its assertions intact.++## Current gate inventory++Source-backed preparation found that the current default `make test-performance-m4 RUNS=1` selects nine suites and 52 declarations. Historical references to “full33” describe the earlier four-suite dependent selection, whose script supplied a narrower explicit filter; they do not establish current unfiltered gate coverage. The completed current publication run retained the default selection without added selection or skip flags; the narrower 33-declaration history remains separately qualified. The current frozen-source N10 remains the original single-declaration duplicate observation/settling diagnostic selection, with all ten measured samples and both two-second assertions unchanged.++The reviewed feature and read-reuse follow-up are preserved at `9f71c5dc`; the later reviewed nine-path candidate and test-only fixture repairs are 971 inputs at `8a241a73…`, uncommitted. The current three-method diagnostic is recorded first below; earlier 970-input results retain their source bindings. Existing numerical results below belong to their explicitly recorded earlier source, not current-source acceptance. Preparation inventories remain external under `evidence/t2468-publication-ui-preparation/` and the performance preparation directory.++## Current 971-input original three-method diagnostic++After the accepted focused correctness run (94 declarations / 139 executions), the original creator-detail, duplicate observation/settling and three-state capture methods completed naturally at **2026-10-19T19:05:00Z**. Make and wrapper exited 2 after **876.105 seconds**, including **629.96 seconds** of Release compilation and **242.376 seconds** of test runtime. All 971 inputs remained `8a241a730082d22caba7df03f3494cbffeda3da1b4df2d54a9f0fe8ef9951036`. No test, fixture, threshold, sample count or known-issue scope changed. There were no timeouts, signals, tracking errors or remaining owned processes.++| Original arm | Median | Samples | Unchanged hard limit | Result |+| --- | --- | --- | --- | --- |+| Creator detail | 0.042777s | 20 | 0.050s | Pass |+| Duplicate observation | 4.148841s | 10 | 2s | Fail |+| Duplicate settling | 6.765119s | 10 | 2s | Fail |+| Capture: duplicate Site rows | 0.832219s | 20 | 0.250s | Fail |+| Capture: missing Site | 0.451331s | 20 | 0.250s | Fail |+| Capture: duplicate identity | 0.833851s | 20 | 0.250s | Fail |++All three rule-only arms passed their original 100 ms bounds. All three capture projection 100 ms expectations recorded their original known issues at line 401; all three outside 250 ms assertions still failed. Exact raw XML and terminals reconcile three declarations, five expanded executions, nine distributions, five hard issues and three known issues. All fifteen diagnostic integrity checks and nine independent root checks passed; this accepts evidence integrity, while the diagnostic remains failed. All 26 emitted compiler-warning occurrences were independently qualified against exact inherited source statements and prior diagnostics, with zero unresolved origins. The original narrower warning report, including its twelve unmatched occurrences, remains preserved; the separate qualification does not hide warnings or change the failed verdict.++The creator reader meets its original budget on this measured source. The pure mark guard has not demonstrated N10 recovery. The singleton capture change is insufficient to recover any of the three hard projection ceilings; lower observed medians are not an isolated estimate of that change. No full-52 or broader publication pass follows. Raw evidence is `/tmp/t2468-ledger-build/original-three-performance-971-8a-prepared/execution/`. The durable [`original-three-performance-971-8a`](../../../evidence/t2468-save-time-known-links/original-three-performance-971-8a/archive-integrity.json) archive contains 1,024 hash-verified files, including all 971 frozen source files; root independently verified every archived/original hash and the separate warning qualification. Further source-backed attribution is required before another candidate or run.++## Preserved 970-input full default 52-declaration performance gate++The original `make test-performance-m4 RUNS=1` completed naturally at 2026-10-19T17:58:22Z with Make exit 2 after **1,630.539 seconds**. It ran all nine default suites, **52 declarations / 55 expanded executions**, including the exact five argument starts. Sources remained the 970 inputs at `435f8236…`, preserved in `9f71c5dc`; original tests, fixtures, thresholds and known-issue scopes were unchanged. No errors, skips, missing terminals, signals or remaining owned processes occurred.++Six hard assertions failed across three declarations / five expanded executions:++| Original hard assertion | Measured median | Unchanged limit |+| --- | --- | --- |+| Creator detail | 0.161948s | 0.050s |+| Duplicate observation | 4.261136s | 2s |+| Duplicate settling | 6.778212s | 2s |+| Capture projection: duplicate Site rows | 0.915654s | 0.250s |+| Capture projection: missing Site | 0.493550s | 0.250s |+| Capture projection: duplicate identity | 0.915392s | 0.250s |++The raw output also records nine known issues inside existing lexical scopes. The original report parser missed the three capture lines because Swift Testing includes `with 1 argument state → …` before their source coordinates. A separate offline parser qualifies exactly the original three states at line 401 inside the unchanged lines 400–404 block. Their line 405 regression-ceiling failures remain hard failures. Missing, duplicate or unknown states, unsupported argument syntax, a wrong method and coordinates outside the original scope are rejected. All nine scope bodies and hashes match current frozen source and the actual pre-feature Git source. Original parser/reconciliation files are preserved; the qualified report changes no test or acceptance policy.++Independent integrity review reconciles 49 passed / three failed declarations, 50 passed / five failed expanded executions, the exact raw XML and argument multisets, all nine suite terminals, six hard issues plus nine known issues, source parity and natural process drain. The six raw XML failure elements belong to three test cases; terminal-passed declarations with known issues remain passes. Root acceptance confirms report integrity while the gate remains failed. No compiler warning was emitted from this warm existing Release cache; this is not a clean-rebuild claim. External receipts are in `/tmp/t2468-ledger-build/publication-performance-970-prepared/execution/`, including the original and qualified reconciliations and `independent-integrity-readiness.json`. The full run and focused mate are durably hash-verified in `../evidence/t2468-save-time-known-links/publication-performance-970-full52-and-focused-mate/`. **The full performance gate remains failed; no speed claim, threshold waiver or performance exception follows.**++## Current 970-input original N10 after operation-local read reuse++The reviewed repair reuses one decoder within each history load and one lazy source-presence inventory within each deletion chunk, invalidating the inventory after any source combination and recreating it for replay. All physical payload/key validation and global conflict folding remain. Focused correctness passed 95 declarations / 106 executions; the first attempt’s test-only throwing-expression compile error is retained separately, followed by an assertion-preserving correction and successful run.++The unchanged original N10 completed naturally at 2026-10-19T17:09:45Z in 788.834 seconds (623.66 seconds build; 161.107 seconds test). All 970 inputs remained `435f8236af8db352e31100ca6432ca8e7120c0b002c9b65b569301972f3fea86`. Root verified exactly one original XML declaration, ten measured samples per arm, no errors/skips/semantic failures, unchanged test/fixture/Make contract, and a certain owned-process drain. Only the two original two-second median assertions failed.++| Arm | Prior original median / p95 | Current original median / p95 | Budget verdict |+| --- | --- | --- | --- |+| Observation | 4.187959s / 4.997587s | 4.167216s / 4.983953s | Fail, 2s unchanged |+| Settling | 7.115196s / 8.291726s | 6.763732s / 7.948171s | Fail, 2s unchanged |++The prior source is the separately bound 968-input `a565…` checkpoint; its original fixture and measured production paths precede this repair, while unrelated main/P2 differences are explicitly tracked. Settling is about 0.351 seconds lower; observation is near unchanged. This is a qualified observed comparison, not an isolated decoder estimate, baseline subtraction, or budget waiver. All 26 compiler-warning occurrences match previously source-qualified inherited origins. Durable evidence: `evidence/t2468-save-time-known-links/performance-current-read-reuse-n10/`, including `root-independent-review.json`.++Measured private history breakdown and the source/lifetime review currently provide no further supported narrow repair. Fresh global physical reads/validation, Entry traversal, duplicate scans and saves remain material. The already-rejected prefetch and unsupported early-invalidation ideas remain unapplied. The original budget is an engineering blocker while independent correctness/publication checks continue.++## Prior 968-input original N10++The original single-declaration Release selection completed naturally in 805.450 seconds, including 637.47 seconds of optimized compilation and 163.984 seconds of test execution. All 968 inputs remained `a5651edc0f9306464d7ae6419916cd35d0bf5ce0df8ca737a59975b54db1c290`. Root independently matched the exact XML identifier, zero skips, ten measured samples per distribution, and exactly two failure elements: the unchanged two-second median assertions. Observation median was **4.187959s** (p95 **4.997587s**); settling median was **7.115196s** (p95 **8.291726s**). No semantic assertion failed. The gate remains failed; no baseline subtraction or threshold exception is claimed.++Completed raw log, XML, owned-process receipt and `root-independent-n10.json` remain outside Git at `/tmp/t2468-ledger-build/save-time-current-n10-a565/`, with durable copied evidence recorded separately. Eleven compiler-warning origins are retained and compared with pre-feature `39696ad`: whole unchanged files or exact inherited warning expressions/signatures establish their provenance. Current-source runtime attribution proceeds in a separate reviewed private instrumentation copy; its timings cannot certify original budgets.++## Matched unchanged baseline and selected feature++Both arms ran unprofiled Release executables with the same private driver, original public duplicate fixture and public repository call order. Each is one initial generation, including identical untimed count reads, not the original N10 benchmark. Exact baseline is `39696ad851823a235749313df92f096e68735629`; candidate Core/package inputs match selected restored900.++| Operation | Unchanged baseline A | Selected feature C |+| --- | ---: | ---: |+| Setup | 11.729157s | 11.709513s |+| Observation | 96.163457s | 2.932167s |+| Settling | 170.459822s | 5.230809s |++Both arms passed exact event multiplicity, one Site in each snapshot, physical counts, observation/settling outcomes and completion. Both exited naturally with no signals, tracking errors, uncertain ownership or remaining processes. All baseline554/current900/driver/binary integrity checks passed.++C includes the approved common NoEpisode history-session repair as well as association persistence. **A/C subtraction cannot identify association-only overhead.** Earlier repaired B is a counterfactual, not unchanged baseline; previous sampled timings are excluded. The baseline improvement is not a waiver for the original N10 failures.++The completed C synthetic-store read-only metadata oracle contains exactly750 association events: all Entry invalidations, each typed scope appearing once; zero acceptance events, pair notes, malformed payloads, lookup mismatches or validation blobs. DB/WAL hashes stayed unchanged. Required invalidation work exists even when no accepted pair is currently present.++## Directly measured association stages++A separate private timing-only C copy changes exactly five library files within the same216 Core/package inputs. Root and an independent design critic verified immutable origins on existing Work/Entry convergence, deletion and failed-chunk replay; bounded in-memory aggregates; unchanged queries, predicates, errors, validations, barriers and save order. Three snapshots occur outside timed calls; metrics are emitted only after final counts and shutdown. The external metadata oracle opens only that completed synthetic store with SQLite mode=ro/query_only after process drain.++The one instrumented generation exited naturally0 in21.494s, with all nine fixture/event checks and nine read-only oracle checks passed, zero clone errors and all source integrity checks intact. Its observation2.924649s/settling5.194230s are **excluded from budget verdicts**. Root and independent critic recomputed phase deltas directly from all three raw snapshots; no mismatches or invalid counters.++| Directly measured inclusive stage | Observation | Settling |+| --- | ---: | ---: |+| Capture, before mutation | 0.169431s | 0.426784s |+| Finish, after mutation | 0.148658s | 0.332077s |+| Endpoint inventory, within capture/finish | 0.285426s | 0.603700s |+| Source snapshot/grouping/fingerprint, within endpoint inventory | 0.209064s | 0.454735s |+| Storage inventory, within capture | 0.001757s | 0.078823s |+| Final ledger, within finish | 0.017675s | 0.044374s |+| Captured raw-event re-decoding, within finish | <0.000001s | 0.005583s |+| Actual save, shared reconciliation cost | 0.267446s | 0.671246s |++Only the **same** measured stage is summed across sequential origins. These rows overlap: do not add them, subtract child totals into invented residuals, or divide by original N10 medians. Save includes existing repository mutations and association writes; association-only database-write cost is not isolated.++Capture/finish each ran once for Work and Entry convergence in both phases, plus one deletion chunk in settling. There was no failed-chunk replay, refault or throw in this success fixture. Target-record fingerprinting was not exercised. The probe does not attribute those absent paths or prove costs for a library with accepted pairs/notes.++Source endpoint snapshot/grouping/fingerprinting is the largest measured association child. It preserves all physical endpoint copies, owner/eligibility/note coherence and typed invalidation decisions. That is not proof that a specific hash/cache rewrite is safe or sufficient. Capture already runs once per save chunk; GroupOrdering already has its singleton fast path. The duplicate raw-event decode costs5.583ms in this settling generation, so it does not justify a shipping microoptimization or another broad trial. No endpoint checks or barriers may be skipped merely because the current acceptance set is empty.++## Continuing qualification++Retain reliable saved associations and every original assertion and threshold. Continue systematic attribution of the wider duplicate-pass path, with current source-bound uninstrumented measurements before any diagnostic span comparison. Instrumented runs explain stages and never supply budget verdicts. An unchanged baseline and a counterfactual repair arm must be labeled separately; A/C subtraction cannot identify association-only overhead.++The owner authorizes recoverable performance and Mac UI qualification corrections within this scope. No performance exception, timing-budget change, assertion waiver or extra physical-device test is approved. Preserve the reviewed feature in a commit once the repository's pre-commit bar is met; incomplete publication checks alone do not stop further work. New designs with material user-facing or persisted-contract consequences still require a concrete decision.++The latest save-time addition passes current Core/native/focused phone/iPad verification and signed Mac compilation, as recorded in `save-time-known-links/implementation.md`. Those checks do not close the original performance or Mac UI gates. Current shipping inputs are bound in the external final save-time checkpoint; historical 900-input timing data below retain their own exact source and must not be relabeled as current-source acceptance.++## Evidence++- Matched pack: `/tmp/t2468-ledger-build/matched-release-attribution-v2/root-comparison.json`; manifest `ad1183cc62eb2b64f0ae00c1e45796d61871c9d2e2ee3fffe715bed01457eb35`. A receipt87144424-32f4-4e35-bbde-27dfff469124; C receipt05481b22-3b76-417b-937a-549fa9909119, including postshutdown-association-oracle-v2.json.+- Instrumented pack: `/tmp/t2468-ledger-build/coarse-association-spans-v2/`; source manifest `cd6e1df4fbe6f703263c861a596c4a91ae99b2a1fc631aa4f76882a1b9782606`, execution manifest `2e1959ad353923df692dd8184e36e99b7f9fb63b682f8ba8d248efc0157afaff`. Build51a8b099-ba9b-48f5-9a72-6946d75d60cf completed142.57s/guard144.611s with only two inherited NoEpisode warning origins. Retained binary SHA4242d3160b4e5779b4cb9d30b193e9b3365be861a3d71aa38364d6fe089c7869.+- Runtime `execution-v1/receipts/24797612-81cf-4c83-bc94-6b8aa8a25cf7/`: raw log, result, process guard, read-only oracle/DB-WAL hashes, phase-reconciliation.json, root-phase-reconciliation.json and inclusive-stage-summary.json.+- Private v1 failure remains preserved at coarse-association-spans-v1/execution-v1/receipts/1dbf8721-9c94-4d44-bf38-a0c79cb99654: package identity error before source compilation, natural guard1/2.263s, source integrity intact. V2 corrected only dependency identity/path metadata; all216 Core-copy files and driver Swift bytes stayed identical. No runtime ran on v1.++## Comparable focused creator-detail measurements++Before applying the reviewed selected-history reader, one unchanged current-source focused mate ran naturally in 20.372 seconds at 2026-10-19T18:03:59Z. All twenty original samples and fixture assertions ran; only the unchanged 50 ms median assertion failed: median **0.162372s**, p95 **0.165074s**. This closely matches the full-suite 0.161948s median. Source remained exactly 970 inputs at `435f8236…`, Make exited 2 and all owned processes drained without signals, errors or skips. Seven independent root checks passed; the warm run emitted no compiler warnings. The test selection reduces the full-suite versus one-method order confound; it does not isolate a feature mechanism.++The one exact recorded-main `47eef29f` control completed naturally at 2026-10-19T18:15:09Z after 623.891 seconds, including a 602.62-second isolated cold Release build. Its median was **0.160798s**, p95 **0.162073s**; all twenty original samples and fixture assertions ran, with only the same hard 50 ms assertion failing. Make exited 2; all 897 source inputs and all 1,393 archived Git blobs remained exact, and owned processes drained without signals or uncertainty. Only the external Make recipe added the existing `SWIFT_TEST_FLAGS` hook for private cache and XML output; original archived source/tests were unchanged. Compiler warnings were emitted and remain recorded; this was not a warning-free build.++The original report falsely detected a skip from a compiler-quoted source comment containing “the reader skipped”. A separate report-only parser uses anchored runtime terminals plus raw XML, rejecting actual Swift Testing/XCTest skips and known issues while accepting quoted source. Four offline controls and seven independent root integrity checks pass; original parser/reconciliation remain preserved. There were no actual errors or skips, and no test was rerun for the reporting correction.++| Same original creator-detail method | Median | p95 | Samples | Hard limit |+| --- | --- | --- | --- | --- |+| Current 970, full default suite | 0.161948s | 0.199572s | 20 | 0.050s |+| Current 970, focused mate | 0.162372s | 0.165074s | 20 | 0.050s |+| Recorded main `47eef29f`, focused control | 0.160798s | 0.162073s | 20 | 0.050s |++Both focused runs fail comparably. This does not establish a feature-specific regression; it supports treating the proposed selected-history read as an inherited-path repair. Different schema, generated fixture identities, cache history, run order and host conditions preclude an isolated single-mechanism causal claim. The original limit remains required. The three capture-projection failures are being compared separately before any candidate application; neither source set has been changed.++## Comparable original capture controls and admitted candidate++One unchanged focused three-state capture method ran per source, with twenty samples for each original projection/rule distribution. Current970 completed naturally in 85.545 seconds; exact recorded-main47eef completed in 87.460 seconds. Both sources remained exact and all owned processes drained without signals or uncertainty. Each ran all fixture assertions, recorded only the three original 100 ms known issues, and failed the three outside hard 250 ms projection ceilings; no errors or skips occurred. Root independently reconciled each raw XML, source inventory and complete result.++| Original capture projection state | Current970 median | Recorded-main47eef median | Hard limit |+| --- | --- | --- | --- |+| Duplicate Site rows | 0.925763s | 0.917455s | 0.250s |+| Missing Site | 0.486241s | 0.489195s | 0.250s |+| Duplicate identity | 0.906356s | 0.930358s | 0.250s |++The pure rule step passed its original 100 ms requirement on every arm. Source inspection finds no association-support or NoEpisode-history read in this timed projection graph. Both focused sources fail comparably; this does not establish feature-specific causation. Run order, schema, cache history, generated fixture identities and host conditions still prevent an isolated single-mechanism causal claim. Durable paired originals, comparison, root reviews and source proofs are hash-verified in `../evidence/t2468-save-time-known-links/capture-original-current970-recorded-main47eef-pair/`; recorded-main creator evidence is in the adjacent `creator-detail-recorded-main47eef-control/` archive.++After both controls completed, the exact reviewed nine-path candidate was applied at **971 inputs / `7f571e39`**. The selected creator reader retains every physical selected row and existing lazy history validation; global readers/writers remain global. The writer guard runs only after global history and stable-fact conflict validation and skips pure clear-set/key construction when no same-day mark exists. Capture basis specializes only a singleton physical Work bucket; duplicate buckets retain the complete original grouping and the type-directory fetch stays in place. Independent static review and concrete regression drafts are clear, but correctness and unchanged original performance qualification have not run. No speed or budget-recovery claim follows from application alone.++The first 94-declaration focused attempt on that candidate failed compilation before any tests in 81.419 seconds. Three new MainActor test seeding closures needed explicit Sendable immutable captures when entering the repository actor. The correction changes only those closure headers: production bytes, assertions, 94/139 inventory and all original performance inputs remain unchanged. Independent critique is clear; the resulting 971-input binding is `c380168f`. The failed log, before/after sources and receipt remain in `../evidence/t2468-save-time-known-links/nine-path-closure-repair-20261019/`. Corrected-source runtime qualification is pending; this compiler repair establishes no test pass or speed result.++The c380 rebound compiled and actually executed all 94 declarations / 139 expanded cases, but four new-fixture assertions failed in two declarations. The publication fixture lacked the required currentPause for hiatus, and the fallback assertion accidentally compared Optional.none instead of a present WorkIdentitySnapshot.none. Only those test details changed; the dated pause matches an existing domain fixture and the identity assertion now requires the composed row. The genuinely new Optional.none warning was corrected, while 26 inherited diagnostic occurrences were separately source-proven. Failed evidence remains archived in `../evidence/t2468-save-time-known-links/nine-path-focused-971-rebound-fixture-failure/`.++The resulting **971 / `8a241a73`** focused run completed naturally at 2026-10-19T18:42:27Z in **26.625 seconds**, with Make/wrapper 0. All 94 declarations / 139 executions, nine parameterized declarations and 54 exact argument tuples passed; no failures, errors, skips, runtime issues or warnings were emitted. All source bytes remained exact and owned processes drained. Root accepted ten independent checks, including every raw XML ID and all raw named argument lines. Warm incremental compile qualification is explicit. This proves focused correctness only; the original three-method performance diagnostic and full default gate remain owed.++## Current capture stage attribution, 2026-10-19++A separate instrumented private copy completed naturally at 19:39:33Z in 759.750 seconds, including a 679.25-second Release build. Shipping source remained exactly 971 inputs / `8a241a73`, at HEAD `9f71c5dc`. All three original states retained one warm-up, twenty measured projections and the final untimed basis request: 22 calls per state. Original fixtures, rule samples, assertions and thresholds remained intact. Make/wrapper exited 2 with no signals or uncertain cleanup; every expected trace key, branch, physical-row count and original XML identity reconciled.++All three original hard capture ceilings remain failed: duplicate Site rows **0.829127s**, missing Site **0.449733s**, duplicate identity **0.829980s**, against **0.250s**. Each also recorded the original 100 ms known issue. Pure rule application passed. This instrumented run cannot qualify the shipping budget or establish exact baseline timing equivalence.++| Instrumented measured-call stage | Duplicate Site rows | Missing Site | Duplicate identity |+| --- | --- | --- | --- |+| Initial capture basis, inclusive | 0.121208s | 0.112309s | 0.120607s |+| Global Entry fetch | 0.174399s | 0.169091s | 0.174698s |+| Entry grouping | 0.119392s | 0.118673s | 0.119064s |+| Entry URL/content walk | 0.020673s | 0.020546s | 0.020177s |+| Global source index, inclusive | 0.326091s | 0.320135s | 0.326554s |+| Chapter evidence and resolver, inclusive | 0.257334s | Not reached | 0.256953s |+| Nested capture basis, inclusive | 0.120419s | Not reached | 0.120736s |++These are medians of the same twenty instrumented calls, not additive cost allocations. Inclusive parents overlap their children; no residual is called lock wait. Clocks, Mutex recording, helper closures and new local values can change optimizer and ARC lifetimes. Source fetching is larger than grouping, and taught projection has additional substantial stages, so grouping specialization alone does not establish a sufficient repair. No further source change is admitted from these measurements.++Raw reconciliation remains rejected solely because the cold build emitted warning origins outside its narrow previously accepted warning catalog. Independent review and nine root checks separately qualify all 43 primary diagnostic occurrences, plus 43 gutter echoes: the warned statements exist in both recorded main `47eef29f` and pre-feature `39696ad`; all twelve warned files are identical between private copy and shipping. Nine files also match both baselines wholly; three retain the exact warned statements. This is source provenance, not compiler replay or warning absence. The original rejected report is preserved. All semantic, trace, source and natural-drain checks pass, so stage attribution is accepted with those qualifications while the original performance gate remains failed. Evidence remains outside Git at `/tmp/t2468-ledger-build/capture-stage-attribution-971-8a-prepared/execution/`; no retry or automatic advance occurred.+++## Recommended publication decision after bounded qualification++Preserve the reviewed feature and small repairs in a commit after strict affected phone/iPad acceptance, while keeping merge blocked on the unchanged required budgets and unfinished publication gates. The successful Devsterism test installation does not grant a performance exception.++Creator detail is now inside its original 50 ms ceiling at 42.8 ms. Matched main controls establish inherited capture cost, so further capture work belongs in a separate, explicitly scoped repair. The paused broader capture reader design is not resumed by this recommendation. Its three 250 ms ceilings still fail and remain required.++N10 remains part of this feature's unresolved performance qualification: observation 4.149 seconds and settling 6.765 seconds against 2 seconds. Association work is included, but current measurements do not isolate its causal contribution. Do not classify this result as wholly inherited, subtract overlapping timing intervals into a residual, or adopt a payload memo whose benefit has not been demonstrated. The historical decode-time envelope is not a current speedup prediction. The next recommended decision is to prioritise a bounded N10 repair plan that retains fresh physical-row inventories, current-owner checks and complete global history validation before considering a wider implementation change. No dominant narrow repair has yet been established.
diff --git a/specs/character-chapter-associations/requirements.md b/specs/character-chapter-associations/requirements.mdnew file mode 100644index 00000000..4a005325--- /dev/null+++ b/specs/character-chapter-associations/requirements.md@@ -0,0 +1,102 @@+# T-2468 — Chapter links for noted characters and places++## Introduction++Asterism will save which characters and places are mentioned in each chapter's saved note, including chapters without a URL. Each link can carry an optional reader-written note as groundwork for an alternative to extracted facts. Existing facts remain available, and a link stops being a mention association when its supporting mention is removed.++## Non-Goals++- Character/place history layouts, large-cast display design, filtering and pagination.+- Search redesign or a replacement for the current extraction/processing approach.+- A general endpoint revision graph, automatic composition of independently edited offline branches, universal identity routing, or a note-history browser.+- Reading chapter bodies, inferring story presence or retaining historical mention associations after their support is removed.+- Automatic generation of link notes or automatic conversion/removal of existing facts.+- Generic work notes or standalone non-chapter notes becoming chapter links.+- Manual mention tagging, name insertion or interpreting reference-chip taps as selection.++## Definitions++- **Record:** a character or place, with its existing kind and stable identity. The same name in the two kinds does not identify the same record.+- **Chapter:** an Entry identified as a chapter, including a URL-free authored chapter; a chapter-like title alone does not classify a standalone note as a chapter.+- **Supported spelling:** grounded text recognized by that record kind’s existing current-name, retained-name-key or accepted-alias matching rules.+- **Mention link:** an accepted association between one chapter Entry and one record, supported by a supported spelling in the current saved chapter note. It asserts note mention, not story presence.+- **Link note:** optional reader-authored text scoped to one chapter and one character or place. It is separate from the chapter note, record-wide note, and extracted facts; it is not another extraction source.+- **Evidence:** the grounded supported spelling and source revision supporting the mention. Multiple occurrences or aliases in one chapter still produce one link for that record.+- **Acceptance:** existing extraction proposal review; automatic processing proposes grounded mentions but does not itself accept them.+- **Rejection:** an explicit reader decision, distinct from removal of an unsupported association. Existing candidate-name and fact suppression retain their current kind and scope.+- **Decision order:** Existing candidate/fact suppression keeps its established ordering. Link acceptance explicitly acknowledges known equivalent rejections; an unacknowledged opposing decision or incoherent validation basis requires review. Note Clear consumes the explicitly observed parent heads, independently of later membership changes.++**Status:** Core behavior remains owner-approved. The owner approved conservative re-review of genuinely ambiguous offline association branches and authorized the simpler design and implementation on18October2026 (Decision2).++## Requirements++### 1. Meaning, identity and kinds++**User Story:** As a reader, I want chapter links to reflect the characters and places I noted, so that saved associations have a clear meaning.++**Acceptance Criteria:**++1. <a name="1.1"></a>The system SHALL identify each mention link by chapter identity, record kind and record identity, including linkless chapters, distinct chapters sharing a URL, renamed chapters and chapters without designations.+2. <a name="1.2"></a>The system SHALL retain the current supporting evidence and source revision for each accepted link without claiming the record was present in the story; a character and place with the same spelling SHALL remain separate.+3. <a name="1.3"></a>WHEN processing generic work notes or non-chapter Entries, the system SHALL preserve existing extraction/fact behavior without creating chapter mention links from those sources.++### 2. Name-only, repeat and alias mentions++**User Story:** As a reader, I want chapter links without needing new facts, so that repeat mentions of familiar characters and places are recorded.++**Acceptance Criteria:**++1. <a name="2.1"></a>WHEN a chapter note yields a grounded character or place name with no new fact, the system SHALL make its new mention available for acceptance for new and existing records.+2. <a name="2.2"></a>WHEN the same record is accepted from two chapter notes, the system SHALL retain two links; multiple occurrences, accepted aliases or facts in one chapter SHALL NOT create duplicate links for that record.+3. <a name="2.3"></a>WHEN a noted spelling matches a record's current name, retained name key or accepted alias, the system SHALL resolve it using existing matching precedence within that kind, retain the noted evidence spelling and attach it to the resolved identity. A proposed alias alone SHALL NOT redirect it onto another existing record.+4. <a name="2.4"></a>WHEN a reviewed proposal is accepted, the system SHALL save its displayed grounded mention links even if every fact is unticked; skipping the proposal SHALL NOT accept its links, and automatic extraction alone SHALL NOT accept links.+5. <a name="2.5"></a>WHERE a chapter note contains no supported spelling, the system SHALL NOT infer a mention link from a fact citation, record-wide note, link note, rating, chip interaction or empty note.++### 3. Automatic processing, acceptance and suppression++**User Story:** As a reader, I want old and new notes processed with the current workflow, so that the feature works without rewriting my notes or silently accepting model output.++**Acceptance Criteria:**++1. <a name="3.1"></a>WHEN automatic extraction processes saved chapter notes, the system SHALL make old revisions eligible for missing character/place links even if legacy fact coverage marks them processed, using the current processing approach and pass budgets. Explicit manual extraction SHALL also reconsider these notes. Relevant record creation/name/alias changes and support loss/return SHALL re-arm missing-link review for unchanged covered notes, within the existing budgets.+2. <a name="3.2"></a>WHEN undecided link proposals exist, the system SHALL preserve their review eligibility across restart and repeated processing without duplicate pending work or implicit acceptance/rejection.+3. <a name="3.3"></a>WHEN source-note revision, chapter eligibility or resolved stable record target is no longer valid at acceptance, the system SHALL refuse atomically without partial link/fact/alias writes and preserve reviewable input; harmless renames that keep the resolved target SHALL NOT alone invalidate acceptance. Stale Skip SHALL remain allowed.+4. <a name="3.4"></a>WHEN a character or place candidate has been explicitly rejected, the system SHALL preserve and honor its existing kind-scoped rejection through edits, restart, sync and backup until explicit reconsideration; Skip SHALL NOT create a record identity. Skipping evidence for an existing record SHALL NOT invent a new work-wide rejection of that record.+5. <a name="3.5"></a>WHEN the reader skips mention evidence for an existing record, automatic processing SHALL keep equivalent grounded spelling in that chapter suppressed across replay, unrelated note edits and repeated occurrences, without suppressing every future spelling of that record in that chapter; newly added different supported spelling SHALL remain eligible under ordinary review, and explicit manual extraction SHALL permit reconsideration. Evidence from other chapters SHALL remain eligible.+6. <a name="3.6"></a>WHERE extraction is unavailable, bounded out, refused or fails, the system SHALL preserve saved notes and supported accepted links; a missing or empty model result SHALL NOT prove that a mention was removed. A failed decision save SHALL NOT claim links or coverage were saved.++### 4. Current-note support and removal++**User Story:** As a reader, I want a removed mention to remove its chapter link, so that associations reflect my saved notes rather than obsolete history.++**Acceptance Criteria:**++1. <a name="4.1"></a>WHEN a saved chapter-note or record-name/alias edit removes the final supported spelling for an existing record link, the system SHALL remove that mention association and exclude obsolete evidence from current membership, retaining only compact decision/invalidation metadata needed to prevent replay, without waiting for another successful model call or retaining it as historical mention membership; an unrelated edit or removal of only one of several supporting occurrences SHALL preserve the link. For cased names, Ada → Adam removes Ada’s final complete-name support. Fully uncased names retain established literal grounding with attached particles. This observed-transition rule SHALL preserve unchanged legacy receipts; detached authored notes and explicit rejection decisions remain authoritative.+2. <a name="4.2"></a>WHEN a later saved chapter note mentions that record again, the system SHALL make the new mention eligible under ordinary acceptance/rejection rules; removal caused by absent support SHALL NOT itself reject the record or permanently suppress that chapter.+3. <a name="4.3"></a>WHEN an explicit chapter/record deletion or chapter change to non-chapter kind removes link eligibility, the system SHALL remove its live mention associations; temporarily missing sync targets or unresolved identity/content conflicts SHALL NOT be treated as an intentional removal.+4. <a name="4.4"></a>WHEN facts are edited or deleted, the system SHALL preserve supported mention links; removing an unsupported link SHALL preserve existing facts, records and record-wide notes.++### 5. Optional notes on links++**User Story:** As a reader, I want a note for one chapter's character or place link, so that I can keep chapter-specific observations alongside the existing facts.++**Acceptance Criteria:**++1. <a name="5.1"></a>The reader SHALL be able to create, read, edit and clear optional text for a chapter–character or chapter–place link independently of that record's other chapters, record-wide note, chapter note and facts. A link with no note SHALL remain valid.+2. <a name="5.2"></a>WHEN the reader edits a link note, changes SHALL commit only on Save; Cancel SHALL leave the saved note unchanged, and refused/failed saves SHALL preserve the reader's draft under existing editor behavior.+3. <a name="5.3"></a>WHEN a link note is saved, the system SHALL preserve its text as reader-authored content; it SHALL NOT generate or replace it from extraction, copy facts into it, clear facts because it exists, or use it to support or regenerate its own mention link.+4. <a name="5.4"></a>WHEN mention support, chapter eligibility or record eligibility is removed from a link with a nonempty reader-authored note, the system SHALL remove the active mention association as required by section 4 and preserve the authored text and its original chapter/record context as a recoverable detached note, without counting it as a current or historical mention association.+5. <a name="5.5"></a>WHEN the same chapter and record later regain a supported accepted link, the system SHALL make any detached note for that pair recoverable by an explicit reader choice, without automatically overwriting a newer link note. Explicitly clearing a note SHALL remain cleared under replay.++### 6. Combinations, sync and compatibility++**User Story:** As a reader, I want links and their notes to survive ordinary library operations, so that chapter-specific observations are not silently lost.++**Acceptance Criteria:**++1. <a name="6.1"></a>WHEN records or chapters are combined, or parent works merged, the system SHALL resolve links to surviving identities and deduplicate matching pairs; it SHALL preserve differing authored link-note contents for resolution rather than silently choose one, and apply the defined decision order to conflicting explicit reader decisions. Record-kind conversion SHALL preserve authored notes with their resolved target kind without presenting one record as both kinds.+2. <a name="6.2"></a>WHEN record names, aliases, chapter titles, designations or source URLs change without removing the saved note's grounded support, the system SHALL preserve link identity and authored notes; work-record copy SHALL NOT invent destination chapter links or copy their notes as destination chapter evidence.+3. <a name="6.3"></a>WHEN the app restarts, devices sync, or a backup is exported/imported, the system SHALL preserve supported links, link-note content, recoverable detached notes, and explicit rejection/clear decisions. Concurrent or reordered edits SHALL NOT silently discard differing authored note text. Coherent repeated arrival SHALL be idempotent; known removal/rejection/Clear decisions SHALL not be undone by replay. Genuinely ambiguous concurrent/offline association branches SHALL remain inactive for explicit re-review, preserving all authored text; automatic composition of those branches is not required.+4. <a name="6.4"></a>WHEN an existing supported library/archive is opened/imported, the system SHALL preserve existing characters, places, aliases, chapters, facts and their behavior without manufacturing accepted links or link notes; an export unable to preserve the new content SHALL refuse explicitly rather than claim a complete backup.++5. <a name="6.5"></a>WHEN conflicting or incomplete association metadata prevents a coherent supported result, the system SHALL expose a reviewable/inactive state and preserve raw authored notes, rather than infer acceptance or deletion. Routine coherent support-preserving edits SHALL remain automatic.
diff --git a/specs/character-chapter-associations/save-time-known-links/decision_log.md b/specs/character-chapter-associations/save-time-known-links/decision_log.mdnew file mode 100644index 00000000..3b151549--- /dev/null+++ b/specs/character-chapter-associations/save-time-known-links/decision_log.md@@ -0,0 +1,30 @@+# Save-time known links decisions++| ID | Decision | Reason |+| --- | --- | --- |+| S1 | Reuse current-name → retained-name → accepted-alias recognition tiers and existing capitalization/pronoun admission. Add complete-name boundaries, not fuzzy inference. | Preserve existing source/identity authority while preventing substring matches. |+| S2 | Extend automatic save-time linking to known places only; retain AI discovery review for new places. | Explicit owner Yes covers both known kinds. |+| S3 | Final saved note and chapter identity own one transaction, including exact pending-key settlement. | Avoid draft conflicts, partial saves, duplicate replay and stale place review rows; no whole-source completion shortcut. |+| S4 | Remove the final supported mention on an observed saved transition; preserve detached authored notes and established uncased grounding. | Explicit owner instruction settles Ada → Adam removal; a narrow before/after maintenance predicate avoids receipt-format changes and legacy revalidation. |++Scope is an incremental internal extension of the current association ledger with no new schema, archive format or public API. Clean explanation validation findings were wording/contract clarifications resolved from existing matching and save patterns. Independent design critique identified the pending-place obligation gap; S3 and explicit sibling tests address it. The owner-approved implementation instruction supplies authorization for this bounded addition and its task plan; no redundant naming/plan approval is requested.++## S5 — Original divergent-copy save boundary++Publication inspection confirmed that all three DuplicateResolution arms bypass association maintenance: supported losing-Entry links and authored notes are not rebound, losing-Work record ownership is not transferred, and same-ID name/alias choices can allow old receipt revival. This violates existing association requirement 6.1 and the design’s single-save mutation boundary. Apply existing capture/finish/rebind machinery and WorkMerge ownership helpers in those exact resolver arms, with source/target refusal, before-inactive and rollback controls. This is a necessary original-contract correction, not a new matcher policy or a blanket commitResolution hook. Independent design critic supplied concrete scenarios and scope before implementation.++## S6 — Untyped spelling ambiguity++Literal Save matching has no AI kind classification. The owner’s explicit unique-identity / ambiguity-unassigned requirement therefore applies across both typed directories for newly inferred links. A name shared by a character and place is insufficient to select either, including the same UUID under different kinds. Per-kind recognition tiers remain established; suppressed or incoherent matches are not a semantic type classifier. Preserve existing deliberately accepted links through ordinary maintenance. This corrects the draft’s independent-namespace acceptance assumption; no new owner decision is needed to enforce the explicit ambiguity constraint.++Every observed physical variant contributes its current-name, retained-key and alias claims at their existing tiers. A non-carrier spelling from a torn or ownership-incoherent group must not disappear from ambiguity checks, within a kind or across kinds. Mark those variant targets unsafe, preserving current-name precedence over a lower-tier unsafe alias and allowing unrelated torn names to remain irrelevant to the spelling under consideration.++## S4 — Final supported mention removal++The owner explicitly confirms that a character removed from mentions must not retain its source-backed link. Ada → Adam therefore removes Ada when its final supported occurrence disappears. Authored link notes remain detached; a later uniquely matched known Ada can receive a fresh association, while rejections remain authoritative. This applies to the approved shared character/place save-time maintenance contract.++Use an internal maintenance predicate: spellings with cased scalars require complete-name support; fully uncased spellings retain established literal grounding, including Korean/Japanese attached particles. Intersect this evidence with each side’s corresponding unsuppressed whole receipt. Only coherent before-active support becoming absent in coherent final endpoints proves this additional removal transition. Keep ordinary literal-loss retirement. Do not reinterpret unchanged/rating-only legacy partial receipts or create support for before-inactive roots. Missing/torn endpoints do not prove deliberate mention removal.++Ordinary captured roots retire before receipt refresh. Verified rebinds retain historical typed acceptance cores and exact authored-head transfers, but withhold unsupported final membership receipts. Whole receipt evidence, public AI grounding, immutable history, schema and archive format stay unchanged. This is a transition rule, not global validation or backfill. Cased names attached directly to uncased particles remain a conservative complete-name boundary limitation; no universal linguistic tokenization is claimed.++Independent design critique confirms this bounded approach and the before/after gate. The owner clarification resolves the earlier user-owned ambiguity; no further product approval is needed for this correction. Focused regression and current-source publication gates remain required.
diff --git a/specs/character-chapter-associations/save-time-known-links/implementation.md b/specs/character-chapter-associations/save-time-known-links/implementation.mdnew file mode 100644index 00000000..1d8633fc--- /dev/null+++ b/specs/character-chapter-associations/save-time-known-links/implementation.md@@ -0,0 +1,115 @@+# Save-time known links implementation++Current checkpoint: the save-time known character/place matcher and reviewed P2/read-reuse follow-up are committed at `9f71c5dc`. The later reviewed creator-history, mark-overlap and singleton capture-basis changes, guide clarifications and two-view day/calendar warning repair are now committed as **`a9fe5b75`**. The latest frozen source is **971 inputs / `17ec40d3`**. Fresh unfiltered Core passed **6,565 expanded executions**, fast passed **552**, and signed Development Mac/native quick passed **1,939** with zero structured runtime warnings. Native Make exited 0; wrapper 124 records cleanup of one proven-owned idle `ibtoold` helper, followed by certain empty drain, rather than a test timeout or natural signal-free exit. Strict Mac app/extension signatures, exact temporary fixture UUID and all archived source/result hashes were independently accepted. The 12-journey phone batch passed every assertion with zero runtime warnings, but its source guard failed during the separately requested physical Xcode build’s localisation extraction. That failure remains explicit. The preserved catalog has now been restored after deployment, and the fresh strict phone recovery passed all twelve exact journeys with zero warnings, failures or skips, unchanged source and natural drain. The separately admitted iPad gate then passed all four exact journeys with zero warnings, failures or skips, unchanged source and natural drain. These completed the targeted precommit bars for that twelve-path commit; full publication remains separate. The Mac-only test route remains uncommitted pending actual runtime.++Original performance qualification remains failed: creator detail recovered to **42.8 ms / 50 ms**, while N10 observation/settling remain **4.149 / 6.765 seconds / 2 seconds**, and capture remains **0.832 / 0.451 / 0.834 seconds / 0.250 seconds**. Matched main controls establish inherited creator/capture failures; association work is included in N10 and its contribution remains unresolved. Broader capture redesign is paused as separate scope. Full phone/iPad publication and human-authenticated Mac runtime remain owed; no gate is waived. The owner subsequently requested a Devsterism test installation before merge. Its signed Development build is verified and preserved, with source HEAD `9f71c5dc` plus reviewed uncommitted repairs and the reviewed generated catalog refresh (`33a479c2`). After the user confirmed unlock, a single Xcode MCP RunProject installed and launched Devsterism successfully in 11.438 seconds. The App Group library path and released Asterism metadata are unchanged; the private app-container path changed and contents were not inspected. The source catalog was then restored to exact `17ec40d3` bytes for independent qualification, without another build or device action. No push, PR or merge has occurred in this continuation. See `../checkpoint.md` for current source-bound results; later sections retain historical evidence and must not be read as acceptance of the latest source.++## Scope and design verification++The owner explicitly approved immediate save-time linking for known characters and places, followed by pr-pilot and regular Release deployment when required gates permit. The current-name → retained-name → accepted-alias recognition precedence and existing capitalization/pronoun admission remain. The added Unicode complete-name boundaries prevent embedded-word support. AI discovery/review behavior remains for new entities; the extension gains no model framework.++Clean explain-like validation and an independent design critique ran before implementation. Wording gaps were resolved in the concise spec. The pending-place critique is addressed by exact current-guard/key/target/spelling acknowledgement with no whole-source coverage shortcut and narrow held-state reconciliation. Independent code review subsequently found no new blocker in the save-time helper, boundaries, grounding, held ledger and existing save terminals; runtime qualification remains separate.++## Verified red checkpoint++The production-unchanged run exited 2 after 27.938 seconds. Exactly five declarations / 49 parameter-expanded executions ran across the new matcher, repository and held-ledger suites, with 37 expected assertion issues, no errors or skips. All 965 inputs matched before/after; excluding the three new test files matched installed baseline 962 / `933fa3196fdf8bd0057f4fd1ae86eb55cf119e0093582f1d6f95514c9cc29cff`. It demonstrates substring-name acceptance, absent immediate both-kind saved links, unacknowledged known-place obligations and a retained fulfilled held row. Manual/enrichment/ambiguous/source-guard/pending controls were retained.++Evidence is outside the repository at `../evidence/t2468-save-time-known-links/` and `/tmp/t2468-ledger-build/save-time-known-links-red/`.++## First implementation checkpoint++The first implementation attempt exited 2 before tests after 106.140 seconds: one new test placed an awaited expression inside an unsupported boolean autoclosure. Both assertions were retained when split. Its production inputs compiled; this is not a runtime pass.++The retry exited 2 after 174.967 seconds with unchanged source. Actual discovery ran 260 declarations across 20 suites / 480 expanded executions, including the Makefile-added recognition control. Six declarations reported ten assertion issues, with no errors or skips. Four test scenarios need fixture/oracle updates for the explicitly approved fresh save-time acceptance behavior; their original retirement, cancellation, barrier and history controls remain required. Two established uncased-script grounding cases exposed an overbroad production change: complete-name boundaries had been applied to all AI grounding. Their original Korean/Japanese fixtures are preserved. The stricter scanner and its maintenance policy are being scoped before another run; no failed result is relabeled green.++Review also found that independent per-kind matching could assign a spelling shared by a character and place. New inference must enforce typed uniqueness across both directories, including non-carrier spellings in torn physical copies (S6).++The focused cross-kind checkpoint first exited 2 after 2.324 seconds before compilation/tests because the enclosing sandbox denied SwiftPM’s nested manifest sandbox. The unchanged normal command was approved for elevated execution in a fresh evidence path. That retry exited 2 after 28.144 seconds: exactly 16 declarations / 43 expanded executions, two failing declarations / eight expected issues, no errors, skips or new warnings. All 967 inputs matched before/after (`b7148a6a53f41a85b074cfea40b9941ab5d25cb6e735f9aa218db254e237e3f7`). Cross-kind and same-UUID namespace cases fail; the other 14 declarations pass. The diagnostic-only first attempt remains separate from the executed regression evidence.++The independent critic confirmed that acceptance provenance is not encoded. A shared complete-support removal rule therefore also changes legacy AI/manual links which lose a standalone occurrence but retain particle-attached support. The owner subsequently clarified that final mention removal must remove the link. S4 now specifies the reviewed narrow cased/uncased before/after maintenance transition; implementation and revalidation are in progress. Established AI grounding and its original uncased-script fixtures were restored separately from the strict creation scanner.++The settled scanner/identity correction passed its focused gate in 39.239 seconds with unchanged 967 inputs (`49a876652bc97436bffc94ad10b82225da308c3b5f0cb07809b4b7c5160e919f`). All 34 selected declaration identifiers ran, with zero failures/errors/skips. Actual expansion was 187 (161 parameter invocations plus 26 nonparameter declarations), correcting a pre-run estimate of 188: original grounding expanded to 138, not 139. Root independently reconciled XML declarations and raw parameter starts. Eleven cross-kind/unsafe-copy parameter cases passed; both original uncased-script tests passed with unchanged fixtures. Only the two existing FoundationModels API deprecation origins appeared. This is a focused scanner/grounding pass; the then-held S4 removal case was explicitly outside this selection and no whole-feature green verdict follows.++## Current verification selection++Additional current-source composed Core and publication gates remain owed. Their selection includes existing capture, re-share, replay, publication, pending review, storage, history, ranking and recognised-character controls. The two app test additions are a real-factory Save/publication test and one shared phone/iPad Save→both-kind history/reference journey. Their expected selection is the complete seven-test native suite plus the new UI method on phone (8/8), then that UI method on iPad (1/1). Actual app runtime results are not yet claimed.++The complete current addition selection ran all four suites without excluding S4: 49 declarations / 235 executions in 6.773 seconds, with exact declaration IDs, unchanged 968 inputs (`e932a4a99f44f774dc928ce510c79c5479656404533895d59693b7a13375018f`), zero errors/skips/warnings and three assertions in one failing declaration. All other 48 declarations / 234 executions passed, including save/replay, rejection, cancellation, rollback, pending/held siblings and original uncased AI grounding. The open test demonstrates Ada→Adam retaining membership and its annotation, then returned Ada retaining its old head/root. This is the concrete S4 failure covered by the owner’s removal instruction, not an omitted test or a green gate. Root independently reconciled XML and raw parameter execution counts. Evidence: `full-current/` including `root-count-reconciliation.json`.++Isolated app Save/publication checks are being prepared against this frozen checkpoint as independent integration evidence. The S4 maintenance correction must receive its own affected revalidation before publication; these checks cannot waive it.++The first phone run exited 2 after 199.611 seconds without timeout or forced kill, on the dedicated simulator with unchanged 968 inputs. Exactly eight expected tests ran: the complete native publication suite passed 7/7, including real-factory Save; the UI journey failed before its first Save at the initial place-reference existence assertion. Root viewed the actual failure frame: the Form’s Chapter links heading and Alice are at the bottom, with Harbor below the viewport. The fixture intentionally seeds both pairs and the native test verifies both; exported UI Snapshot payloads were shallow roots, so no full accessibility-tree claim is made. All fifteen attachments and the recording are retained in `app-runtime-tests/phone-first/`. A bounded Entry Form reveal correction is authorized only in the new UI test, preserving every data/Save assertion. No product/fixture change or iPad run follows from this failed result.++The test-only correction now uses bounded gestures inside the actual Entry Form, reveals both initial/final references, and scans from the note editor through the existing links footer before declaring both kinds absent. Exact unsaved draft bytes and every Save/history/reference assertion remain. Root reviewed the diff; runtime is held until the maintenance correction freezes. Final selection remains seven native plus one phone journey and one iPad journey on that source.++Root separately reviewed all seventeen unique absolute source diagnostic origins in the first phone log: each three-line context exists in preserved HEAD. The raw warnings remain retained, including toolchain/runtime warnings outside that source-origin comparison. This does not turn the failed UI run green or replace a current-source no-new-warning gate. Evidence: `phone-first/root-warning-origin-review.json`.++## Original divergent-copy boundary++Independent publication inspection confirmed that manual divergent-copy resolution bypassed association capture/finish in Entry, Work and typed record arms. The necessary existing-contract repair is task 3/S5: verified loser-to-survivor rebinds, Work record ownership transfer, normal chosen-field invalidation, unsupported destinations detached, no before-inactive receipt adoption and failed-save rollback within the existing single save. The Entry resolver also saves chosen/appended chapter-note text, so the shared known-link helper must inspect its final survivor after maintenance and before the existing save. Work/record field resolution does not imply automatic backfill. Focused regression fixtures are being verified before production correction; implementation/runtime qualification remains pending.++The first three resolver attempts failed compilation before tests. The fixture repairs preserve assertions and use the actual detached-note DTO’s decoded pair/head plus immutable scalar captures under Swift 6. The first executed run (`resolution-red-retry3`) exited 2 after 23.779 seconds with unchanged 968 inputs, six declarations / sixteen executions and thirty assertion issues. Seven issues reached intended product behavior: Work typed-owner/suppression transfer (three), and typed record name round trips reviving old receipts (four). Twenty-three were fixture setup issues; they are not counted as feature regressions. Only the Work rollback arm passed. Entry fixtures incorrectly authored targets that DuplicateScan deliberately excludes from distinct-ID URL buckets, and record rollback tried an exporter which correctly refuses torn physical record copies.++The corrected Entry fixtures use existing eligible legacy URL rows. The newly proposed nonchapter cross-ID arm cannot reach this resolver under the established identity policy; it is removed from that prospective test plan, with existing chapter→note correction controls retained. No DuplicateScan policy is changed. The six-declaration plan consequently has fourteen executions. Record rollback retains physical-row multiplicity and exact association bytes through a raw synthetic-store oracle and disk reopen, rather than bypassing export refusal. Independent fixture critique confirmed actual bucket reachability, decoded note assertions and the complete raw rollback oracle before execution.++The corrected full semantic RED exited 2 after 24.544 seconds with all six intended declarations / fourteen expanded executions and fourteen product assertion failures, no setup failures/errors/skips or warnings. Root independently reconciled XML identifiers, raw parameter starts and unchanged 968 source inputs (`03cdb1f3f03c40bf9463c63a3fc411382f4d2bc594c407da86e58bfa2f1288ed`). All three rollback/reopen arms and cross-work refusal controls passed. Actual gaps are supported Entry annotation rebind (two issues), unsupported same-work detached destination lineage (two), Work link/owner/suppression transfer (three), record name round-trip receipt revival (four), and final chosen/appended note linking (three). Evidence: `resolution-semantic-red/`. The narrow resolver correction is now authorized inside its existing transaction; post-correction verification is pending.++The applied resolver correction (`83b58330f4cb5b4c4f1d063d88ba26ae467d06fa6c8d9a59c4c991d6e7aafddd`) passed the focused compatibility gate in 21.355 seconds: all 94 declarations / 102 expanded executions across twelve actual suites, zero failures/errors/skips or compiler warnings, unchanged 968 inputs (`e932a4a99f44f774dc928ce510c79c5479656404533895d59693b7a13375018f`). This includes all six new declarations / fourteen executions plus 88 existing declarations. Root independently reconciled the exact identifiers and raw parameter starts. Independent final code critique found no blocker in the three scoped capture/finish boundaries, historical head handling or Work ownership transfer. AssociationMutation remains unchanged; S4 is not implemented by this repair. Rune task 3 is complete. Evidence: `resolution-green/` including `root-count-reconciliation.json`.++## Final mention-removal correction++The owner clarified S4: removing the final supported mention must remove its source-backed association. Independent design critique approved an internal coherent before/after transition predicate, preserving public AI grounding, literal whole-receipt evidence and unchanged legacy receipt bytes. Ordinary roots retire on proven loss; verified rebinds keep historical cores and exact authored-head transfers while withholding the unsupported final receipt. No schema/provenance expansion is needed.++The test-first maintenance run exited 2 in 28.120 seconds with unchanged 968 inputs (`4dbb73d891730c8f5aa9a1a2c2f26747fa475c29189903a54b9b9ec556211277`). Root independently reconciled all 27 declaration identifiers and 71 executions: nine assertion issues in three declarations, zero errors/skips/warnings. Actual failures are ordinary Ada removal (three), character/place substring-only rebind removal (four), and rejected-alias removal (two). Fully uncased mixed→particle support, subsequent actual removal, both kinds’ unchanged mixed/substring-only legacy receipt byte controls, and existing rollback/replay controls passed. Independent fixture review found no setup blocker. Evidence: `maintenance-red/root-count-reconciliation.json`. The minimal production correction passed focused GREEN as recorded below.++The reviewed two-file correction passed the same complete 27-declaration / 71-execution selection in 43.768 seconds, exit 0, zero failures/errors/skips/warnings. All 968 source inputs stayed equal to `4969f9ae2fbf3e10aa043b1d420f888b625292a5f9c92408c0a50b25f8fc0246`. Root independently reconciled exact IDs and 63 parameter starts plus eight nonparameter executions. The ordinary removal/return, both-kind rebind detachment, suppression and legacy/uncased preservation oracles all pass. Grounding SHA `d8d2bb2c73fef3bbb658375d494482459b2a69c22e19d63ee587bb20b3a64ae9`; mutation SHA `2302d37bd8f2b89f64b6beeefe5744d7f334b21de87cc830eb17243b0c3c49bc`. Independent applied-code critique found no blocker or extra fetch/fold. Evidence: `maintenance-green/root-count-reconciliation.json`. Unfiltered Core and current-source app/publication gates remain owed.++The current-source unfiltered serial `make test-core` exited 0 in 217.520 seconds without filters or skip flags. Root reconciled all 4,093 unique expected identifiers across 378 suite owners; all 4,038 non-opt-in declarations pass across 6,490 expanded executions (2,714 parameter cases plus 3,776 nonparameter executions), with exactly the same 55 explicitly opt-in performance declarations skipped as designed. No missing/unexpected declarations, failures, errors or compiler warning lines. All 968 inputs remained `4969f9ae2fbf3e10aa043b1d420f888b625292a5f9c92408c0a50b25f8fc0246`. The inventory includes 30 task additions plus 61 other genuine additions since the 4,002-declaration checkpoint; no prior expected identifier was removed. This correctness gate does not discharge the separate original performance gate. Evidence: `unfiltered-core/root-count-reconciliation.json`. Final-source phone eight/iPad one runtime checks are admitted after this process drained; no result is yet claimed for those runs.++The final-source phone command exited 0 in 216.192 seconds with all eight expected tests passing and 968 inputs unchanged, but attachment review qualifies its rendered place-history result. The screenshot labeled place history (`827FEF2B…png`) actually displays the Alice card; root viewed it and confirmed the independent test-driver diagnosis. The old helper inspected a lazy offscreen typed Show chapters button, toggled the already-expanded place closed, and allowed Alice’s global count/source to satisfy the place assertions. Native 7/7 Save/publication and actual Entry both-kind references remain valid; no rendered both-kind pass is claimed from this receipt. Evidence: `app-runtime-tests/phone-maintenance-final/qualified-analysis.json` and retained screenshots/AX.++A test-only external proposal positively binds count, row and saved source to the native cell containing both the exact intended record heading and the selected Chapters control. The observed phone AX shows separate sibling cells for pills/cards; no entire-Work ancestor is used. Every Save/draft/history/title/date assertion remains. Its source application and phone/iPad UI reruns are held until serial fast/signed-Mac jobs drain and review clears. A subsequent UI-only change does not require repeating the unchanged Core/native checks; exact production/native input equivalence will qualify them separately.++The unchanged guarded `make test-fast` cohort exited 0 in 7.188 seconds: exact 456 manifest identifiers across 32 owners, 552 expanded executions, zero failures/errors/skips/warnings and unchanged 968 inputs. Root normalized XML parameter signatures to the manifest’s function-base-name format and independently matched every owner/name; 113 parameter-case starts match all 17 parameterized pass summaries. Evidence: `test-fast/root-count-reconciliation.json`. The signed Mac app/extension compile runs separately; no install or launch is authorized by that build.++The signed Development `make build-mac` exited 0 in 85.258 seconds with the app and embedded Mac extension present, expected identities and strict signatures verified. Initial sandbox verification could not access the trust chain; the identical read-only check under normal escalation succeeded for both bundles without security/signing changes. Five inherited compiler-warning locations across four byte-identical baseline files plus one metadata warning remain recorded. No app launch/install or Mac UI pass follows from this compile. Evidence: `signed-mac/verification.json` and `warning-provenance.json`.++Independent review cleared the typed-history test correction, applied exactly at UI-file SHA `8fdedc0754defa4e8afda2192b7c2301687d0d9b3c3f913c2490143f84204ded`. Root independently verified current 968-input manifest `a3da23199083d951538951aedf6558ce5b0b1c73abfc9536df50f6454815e889` differs from the passed `4969…` checkpoint only in this UI file; all other 967 shipping/Core/native/tool inputs remain byte-identical. Earlier native 7/7 and Core/fast/Mac qualification therefore remain separately source-bound; only phone UI1 then iPad UI1 rerun. Runtime results remain pending. Evidence: `app-runtime-tests/root-typed-history-equivalence.json`.++The corrected phone UI journey exited 0 in 186.608 seconds, exact 1/1 expected method, zero skips/expected failures, no timeout/forced kill and unchanged 968 inputs at `a3da…`. Root personally viewed the Harbor screenshot: Harbor owns Chapters (2), Return/Today and the complete exact saved source, while Alice shows its unselected Show chapters action. Root also viewed Entry detail with both Alice and Harbor references. Independent attachment review additionally verified the Alice card. This supplies the rendered both-kind evidence missing from the qualified earlier phone run; native 7/7 remains separately bound by the verified UI-only equivalence. Existing Environment<Calendar/CivilDay> runtime warnings remain retained. iPad UI1 is still pending. Evidence: `app-runtime-tests/phone-typed-history/` and original xcresult pack.++The corrected iPad UI journey exited 0 in 201.655 seconds, exact 1/1 expected method, zero skips/expected failures, no timeout/forced kill and unchanged 968 inputs at `a3da…`. Root viewed the Harbor screenshot: the correct selected card shows Chapters (2), Return/Today and the complete saved source; independent review confirmed Alice and both Entry references too. The existing return-to-Work fallback completed without an assertion failure; no route/product edit was made. Root independently reconciled exact native7, phoneUI1 and iPadUI1 identifiers/results. Evidence: `app-runtime-tests/root-current-runtime-reconciliation.json`, `ipad-typed-history/` and `root-typed-history-equivalence.json`. All three addition tasks are complete; original T-2468 publication qualifications remain open.++## Continued publication qualification++The owner explicitly requested completion through all remaining gates, pr-pilot, merge and regular Release installation, with comparable performance measurements and recoverable fixes inside scope. Thresholds and assertions remain unchanged. The current plan preserves the reviewed feature in a commit once the code-commit bar is met, while continuing performance and Mac UI diagnosis; incomplete checks alone do not end the work.++The first plain full-native command stopped before compilation/tests because the operational command repeated `-jobs`; the corrected command retained the standard signed Mac prerequisite and unfiltered native bundle. The completed retry ran exact 1,824 declarations / 1,923 expanded executions with no skips: seven executions failed across six declarations in AssociationCoverageRaceTests and NoteFirstCharacterRoutingTests. Their setup creates known records before chapter Save, so approved immediate linking changes the intended extraction-lane initial state. Original assertions are retained while a test-only setup correction is reviewed, including zero-initial-link preconditions and the concurrent same-existing-target/source-basis control. No product fix or broader green verdict follows from this failed gate. Raw completed evidence and the initial operational failure remain separate under `full-native-precommit-failed/`.++The approved two-file fixture correction preserves every original outcome assertion and adds zero-initial-link preconditions. Focused verification passed all thirteen declarations / twenty-two expanded executions, with no skips, failures or missing identifiers. All other 966 source inputs remain byte-identical; the current 968-input manifest is `a5651edc0f9306464d7ae6419916cd35d0bf5ce0df8ca737a59975b54db1c290`. Make exited zero. The wrapper separately cleaned up its owned orphaned Interface Builder helper; this was neither a test timeout nor an uncertain result. The full unfiltered retry is running with the original signed Mac prerequisite and expected 1,824 declarations / 1,923 executions. Evidence: external `native-fixture-repair-focused/reconciliation.json` and `scope-proof.json`.++The full unfiltered native retry passed all 1,824 declarations / 1,923 expanded executions, including fifty parameterized declarations and 149 argument nodes. Root independently matched the exact declaration multiset against source inventory: no missing or unexpected methods, failures, skips or expected failures. All 968 inputs remained `a565…`; Make exited zero after the signed Mac prerequisite. The owned helper cleanup was certain and separate from native success, with no timeout or remaining process. Root reconciliation is retained at external `save-time-full-native-retry2/root-independent-counts.json`; completed raw receipt and native result remain preserved.++The signed Mac prerequisite, extension embed assertion and strict signatures passed. A read-only commit audit enumerated 236 candidate feature files with no unrelated file, credential-pattern, binary or symlink finding; local evidence-path references remain pointers rather than embedded receipts. GitHub authentication is verified. At that audit no commit had been made; the reviewed feature has since been committed as recorded below.++Mac server logs identify an interactive authentication prerequisite: testmanagerd requested XCTest “Enable UI Automation,” LocalAuthentication opened its authentication flow, and startup timed out before a method executed. A bounded Development/synthetic one-test probe is prepared; human availability to approve the actual system prompt is pending. No DevToolsSecurity/TCC/signing change is made. Current Mac source inventory has eleven selected methods, including the new save-time journey; its Mac-only fixture route adaptation is prepared separately for review. Other gates continue while this interaction is pending.++## Publication assessment++GitHub authentication is healthy under network access; remote main remains `47eef29f13baaa2fa043c8fc2bbd2efca6ff120a`. The reviewed 235-file feature checkpoint is committed as `14a7d88778877e3c09c03a4a4b54a22330ee30d7`, with the root-owned changelog in `2727cbb95155fe6cb4dcbbdd6de4bf61e381d410`. All committed feature bytes matched the audited allowlist. No push, PR, merge or additional device action has occurred.++The earlier original Release N10 records observation 3.932553 seconds / settling 6.648267 seconds against unchanged 2-second limits, with full33 incomplete. Earlier Mac UI qualification did not execute its selected eight methods because automation startup timed out. Current source inventory contains eleven methods. Server logs now identify the interactive Enable UI Automation authentication flow as the startup prerequisite; the bounded synthetic probe awaits human availability. No host security setting was changed, and developer-mode status alone is not treated as the sole cause. These qualifications are not waived by the merge request. The current unfiltered native precommit gate passed as recorded above. The fresh original Release N10 completed naturally with observation 4.187959s / settling 7.115196s against unchanged two-second limits and no semantic failure; remaining full performance and unfiltered phone/iPad publication selections are still owed. No green publication verdict is claimed.++## Post-checkpoint integration and review follow-up++The feature-only rebase onto main `47eef29f13baaa2fa043c8fc2bbd2efca6ff120a` completed at feature HEAD `1c3a66a01fd09a7e794882caeb65b0b576422b57`. The recovery ref is `backup/T-2468-before-main-rebase-70444f08`. Verification found all 233 feature-only blobs unchanged, fifteen main-only blobs exact, and `AppLibraryModel` equal to the composition of both branches’ disjoint edits. Documentation conflicts retained both index/changelog additions. The canonical source became 969 inputs (`236a797f…`); previous native/Core/UI receipts retain their earlier source bindings and do not certify the rebased head.++The four static pre-push reviews found no actionable reuse or code-quality defect in the examined paths. Two concrete source-inferred efficiency findings are receiving minimal corrections: use the existing Work+Entry pending-marker index while retaining every invalid-copy/source/identity/spelling guard; and avoid character-support history reads only when already loaded raw character rows/groups are empty. These are not yet measured causes of the N10 failure. Three output-preservation/isolation regressions are planned, including contradictory pending copies and off-Work character-copy quarantine. A reviewed Mac-only test route uses Return chapter 3 from the actual association fixture; every Save/history assertion and phone/iPad branch remains. Runtime validation is pending; the separate private diagnostic does not mutate shipping source or certify original budgets.++The reviewed follow-up passed focused verification on source 969 / `dff4faa0…`: exactly 55 declarations and 124 expanded executions across five suites, including 24 parameterized declarations and 93 exact argument starts. Every expected identifier and argument-value multiset matched; there were no failures/errors/skips/issues or missing/unexpected tests. Natural Make/guard exit zero completed in 92.126 seconds with no remaining owned processes or source drift. Root independently verified XML/source IDs and all warning statements/hashes against pre-feature `39696ad`: six diagnostic occurrences are inherited, with zero changed-source warnings. Evidence remains outside Git at `efficiency-preparation/focused-runtime/attempt2/`, including root reviews. The initial sandbox process-inspection failure never reached Make and its uncertain flag is preserved alongside an independent host drain resolution; it is not a product or fixture failure.++The first full-path private diagnostic completed naturally with exact 23 calls, matching stage sums/counts and no overlap/order/replay anomalies. Its closed consistent backup matches all expected physical counts, but a WAL-mode read-only reopen failed before the already-computed source DB/WAL hashes were persisted. That run remains unaccepted for attribution. A narrowly reviewed private reader repair and warm repeat must recover complete provenance; neither retained counts alone nor an instrumented timing can certify original budgets.++The repaired private diagnostic completed naturally in 168.493 seconds, with all 23 original repository calls, exact disjoint stage sums, and no metric anomalies. Root independently read the closed synthetic backup: 5,750 Entries, 1,050 Works, one Site, 8,250 association invalidations, zero pair-note versions and 29,750 NoEpisode actions match the expected physical counts; backup bytes and recorded source DB/WAL hashes are unchanged. This accepts attribution evidence only. The original two-second median assertions still fail (observation 4.219706 seconds; settling 7.115186 seconds). Ten-sample disjoint means attribute observation primarily to duplicate processing (2.890 seconds) and pre-note reconciliation (1.222 seconds); settling adds deletion (2.599 seconds), duplicate processing (2.236 seconds), and pre/post-note reconciliation (1.095/1.104 seconds). Nested history-read timings overlap those parents and are not additive. A narrower private history-fetch/decode/fold breakdown is being prepared before any further shipping optimization. Evidence: `performance-whole-path-v2/root-independent-v2-review.json` and `stage-analysis.json`.++The narrower private diagnostic also passed integrity review after natural Make exit 2 (321.978 seconds, including 151.67 seconds of Release compilation); the only issues were the same two original median limits. All 23 calls, original semantic checks, expected counters, closed-backup physical counts and birth-aware process drain passed. Ten-sample measurements locate about 0.21–0.245 seconds per origin in global action fetching and 0.20–0.216 seconds in physical payload decoding/validation; history folding and indexing are smaller. Current-note fact traversal costs about 0.28–0.29 seconds while constructing the resulting date values costs about 0.003 seconds. The five-second owned-process sample is qualitative stack evidence and can cross phases. This does not support a civil-date cache or another already-tried Work-prefetch experiment. Review cleared a local decoder per history load and a lazy EntrySource-presence inventory per deletion chunk, invalidated after each combination and recreated for replay. An actual multi-plan combination/delete regression with failed-save replay is required before focused verification. No original budget pass or measured repair improvement is yet claimed. Evidence: `performance-note-history-breakdown/`.
diff --git a/specs/character-chapter-associations/save-time-known-links/smolspec.md b/specs/character-chapter-associations/save-time-known-links/smolspec.mdnew file mode 100644index 00000000..6f6fcd0c--- /dev/null+++ b/specs/character-chapter-associations/save-time-known-links/smolspec.md@@ -0,0 +1,40 @@+# Save-time known character and place links++Status: implemented and independently reviewed. Current source-bound results are recorded in `../checkpoint.md`: Core 6,565, fast 552, native 1,939, strict phone 12 and iPad 4 executions accepted on `17ec40d3`. The reviewed twelve-path follow-up is committed as `a9fe5b75`. Earlier phone warning/source-guard failures remain preserved. Devsterism test installation completed successfully; it does not waive required performance/Mac runtime and full publication gates, which remain open.++## Overview+Saving a chapter note immediately records supported links to known characters and places in that work. The shared repository operation serves the app, share extension and queued-capture replay; AI remains responsible for proposing new entities. The owner explicitly approved this bounded addition and resuming publication afterward.++## Requirements+- New automatic links recorded on Save MUST link only existing coherent records in their current work whose saved current names, retained keys or accepted aliases occur as complete names in the final saved note.+- Matching MUST preserve existing grounding admission (pronouns/oversized names excluded; at least one capitalised occurrence for cased spellings), canonical Unicode equivalence and case-insensitive comparison with boundaries that prevent embedded-word matches. Within each kind, existing current-name/retained-name/alias recognition precedence remains authoritative. Because the literal scanner has no kind classification, a spelling that matches multiple typed identities across characters and places MUST remain unassigned for new automatic links; ambiguity or incoherence in either kind MUST NOT silently select the other kind. Rejections MUST NOT act as a kind classifier. Existing deliberately accepted links retain normal maintenance authority.+- The operation MUST support both characters and places without creating records, aliases, facts or inferred appearances. It MUST preserve explicit rejected spelling/pair decisions and deduplicate replay, repeated names, aliases and already-active links.+- Save-time success MUST settle only pending obligations whose current source guard, original key, target and spelling are supported by the accepted known link. New, ambiguous and suppressed sibling obligations MUST remain pending; saving links alone MUST NOT certify whole-source extraction coverage.+- Note persistence and automatic link changes MUST share the existing lock and save transaction. Cancelled drafts, stale/refused requests, failures and replay races MUST NOT leave extra accepted links.+- A saved transition removing the final supported mention MUST remove its source-backed link and preserve authored annotations as detached history. For cased spellings, Ada → Adam loses complete-name support; fully uncased spellings retain established literal grounding, including attached particles. Maintenance MUST use coherent before/after unsuppressed support and preserve unchanged legacy receipts rather than globally revalidate or backfill them (S4). Returning a uniquely matched known name MAY create a fresh current association; rejected links MUST remain suppressed. Explicit generic/nonchapter notes MUST NOT acquire chapter links.+- Divergent-copy resolution MUST preserve the original association contract: chosen Entry content and verified loser IDs retain supported links/authored heads through existing typed rebinds; Work combines transfer known record ownership; same-ID record choices invalidate old receipts without adopting before-inactive roots. Unsupported destinations leave authored notes detached. These changes MUST stay inside the existing validation/save/rollback boundary.+- Extension Save, new/manual chapter capture, re-share/note edits and queued replay MUST agree on final stored content and identity. An unchanged-note successful Save MUST also fill missing supported known links. No new launch-wide backfill is added. Save-time known-place linking is the owner-approved exception to the earlier place review rule; AI-created/new-place proposals retain review.++## Implementation Approach+- Reuse the existing AssociationMutation, endpoint validation, AssociationEvent accept/retire folds, spelling rejection checks and RecordMatching recognition tiers in AsterismCore. No persisted schema, archive format or new public API is required.+- Cover ordinary capture, updateEntry, re-share, selected-existing/new chapter captures, ownership correction final-content choices and queued replay success terminals. Inspect and cover note write terminals in LibraryRepository+Capture.swift, LibraryRepository+ReparseCapture.swift, LibraryRepository+ChapterCapture.swift and existing Entry edit/ownership correction terminals; repair the independently confirmed missing original maintenance boundary in LibraryRepository+DuplicateResolution.swift using existing typed rebind and WorkMerge helpers; ShareTransport and pending replay already reach repository operations.+- Add an internal pure name-boundary scanner and an internal transaction helper as needed; the share extension continues linking Core without FoundationModels.+- Tests cover app/extension shared saves and replay, alias tiers/ambiguity, Unicode/boundaries, rejected and removed support, nonchapter notes, duplicates, cancellation and save failure. Preserve meaningful existing assertions and use isolated fixtures.+- Out of scope: new entity creation, AI-in-extension, whole-page crawling, new UX, schema changes, broad optimizations and changing timing budgets.++## Matching examples+With known Alice, Ann, O’Neil and New York: `Alice`, `(Alice)`, `ALICE` and `Alice’s` support Alice; `alice` alone follows existing lowercase-only grounding rejection. `Anna`, `Ann2`, `Ann_2` and `Ann-Marie` do not support Ann. A compound accepted name such as `O’Neil` or `New York` must match its full spelling; apostrophe/hyphen joining another name component is not a boundary. Possessive apostrophe-s and trailing possessive apostrophe are delimiters. Adjacent Unicode letters, numbers, combining marks and connector punctuation are nonboundaries, including unspaced-script letters. Canonically equivalent decomposed accents match without stripping accents. Character and place IDs remain distinct typed identities. If Harbor names both a character and a place (even with the same UUID), that spelling alone cannot create either new link. Distinct unambiguous names can link both kinds in one note.++## Risks and Assumptions+- Risk: weak boundary rules create false links | Mitigation: test adjacent letters, numbers, marks, punctuation/name joiners and canonical-equivalent text.+- Risk: a second save leaks partial state | Mitigation: one locked existing transaction, rollback/reopen tests and duplicate replay controls.+- Risk: correcting a note revives rejected support or loses annotations | Mitigation: reuse rejection and link retirement semantics and test exact state.+- Assumption: current-name, retained-name and accepted-alias precedence is already settled in note-first design; no competing identity matcher is introduced.+- Prerequisite: original Mac UI/performance and full publication gates must be assessed honestly before merge. Their existing incomplete/failing evidence is not waived.++## Later authorized qualification work++The owner's later continuation authorizes recoverable performance and Mac UI qualification repairs while retaining every original threshold and assertion. This extends the original implementation scope above; it does not change saved-association requirements. The subsequent morning checkpoint directs separation of matcher delivery from inherited performance failures and avoidance of unrelated optimization expansion. Decision7's private scoped capture-read design and partial draft are therefore paused as material scope expansion. No such shipping change or run is admitted; no budget recovery is established. Authoritative saves, refreshes and global writers remain full.++## Escalation Note+This change was scoped as a smolspec. If implementation reveals ambiguity only the user can resolve, an irreversible boundary (public API, persisted schema, auth path), or a contested architectural choice, stop and escalate to the full spec workflow rather than deciding it inline.
diff --git a/specs/character-chapter-associations/save-time-known-links/tasks.md b/specs/character-chapter-associations/save-time-known-links/tasks.mdnew file mode 100644index 00000000..8dd0cd44--- /dev/null+++ b/specs/character-chapter-associations/save-time-known-links/tasks.md@@ -0,0 +1,20 @@+---+references:+ - specs/character-chapter-associations/save-time-known-links/smolspec.md+---+# Save-time known links++## Shared save-time matching++- [x] 1. Known names and aliases produce unambiguous bounded matches with pure Unicode and rejection regression controls <!-- id:osq7exr -->++- [x] 2. All chapter-note save terminals atomically persist and maintain deduplicated character/place links with replay, cancellation, failure and removed-support regression coverage <!-- id:osq7exs -->+ - Implementation and independent review complete. Focused removal27/71 and unfiltered Core4038 declarations/6490 executions pass;55 expected opt-in perf skips. Fixedfast456/552 pass. Native publication7 plus separate corrected phoneUI1 and iPadUI1 pass; signed Mac app/extension verified. Current UI-only source equivalence recorded. Publication stays held on original performance/MacUI qualifications and remaining full gates; no merge/deployment claim. See implementation.md.+ - Blocked-by: osq7exr (Known names and aliases produce unambiguous bounded matches with pure Unicode and rejection regression controls)++## Original divergent-copy save boundary++- [x] 3. Divergent-copy saves preserve supported link and authored-note continuity, prevent old receipt revival and roll back atomically under focused regression controls+ - Independent code/fixture critique clear; semantic RED reproduced 14 product issues across 6 declarations / 14 executions+ - then exact correction passed 94 declarations / 102 executions with all rollback/reopen controls+ - no failures/errors/skips/warnings and unchanged 968 inputs. See implementation.md and external resolution-green evidence.
diff --git a/specs/character-chapter-associations/tasks.md b/specs/character-chapter-associations/tasks.mdnew file mode 100644index 00000000..12556353--- /dev/null+++ b/specs/character-chapter-associations/tasks.md@@ -0,0 +1,142 @@+---+references:+ - specs/character-chapter-associations/requirements.md+ - specs/character-chapter-associations/design.md+ - specs/character-chapter-associations/decision_log.md+---+# T-2468 Extraction-owned chapter associations++**Latest scoped UI acceptance:** full phone 246 passed / zero failed / two standard simulator skips on `25d23a0b…b023`; full iPad 33/33 on unchanged dependent source `efe8ac24…3992`. Root and independent review accepted both. Five UI-test driver repairs preserve every original semantic oracle; product/Core/native/Mac source remains the separately qualified b6de repair. Feature commit, push and draft PR preparation are authorized; broader performance and publication gates remain open.++## Current qualification++The source at 971 inputs / `b6de963d…6486` has accepted unfiltered Core (4,060 passed declarations plus 55 standard opt-in skips; 6,565 expanded executions), standard fast (456 declarations / 552 expanded passes), native quick (1,943 expanded passes), signed Mac app/extension verification, five affected iPad journeys and all thirteen Mac association journeys. The native wrapper's proven-owned post-principal helper cleanup remains qualified separately; the Mac13 run exited naturally with no cleanup. See the [scoped repair report](../bugfixes/mac-chapter-history-qualification/report.md) for exact counts, source fingerprint, warning provenance and limitations. Earlier source-specific receipts below remain historical.++The scoped product repair is preserved in `dc676a96`. Full unfiltered iPad UI then passed all 33 methods on b6de in 826.463s with zero warnings/skips/issues and natural exit0. Full unfiltered phone UI completed naturally in 9,525.721s with **241 passed executions, five failures and two standard simulator skips**. Independent source/native review accounts for all 245 declarations and 248 executions, including four actual launch variants; source stayed exact, warnings were zero and owned processes drained. The original failed result and the initial reader's launch-argument schema diagnostic are retained, not waived.++Retained native evidence supported four test-driver repairs: reveal the complete lazy Work spine before counting, scroll the UUID-ordered recovery list before reading exact text, walk the actual long review list to its controls, and let native tap operate the visible disclosure while requiring its expanded-content witness. At that stage, only four UI-test files changed; all other 967 product/test/tool inputs remained exact. Seven affected semantic journeys passed on 971 inputs / `efe8ac24…3992` in 864.299s, naturally, with no failures/skips/runtime warnings and one separately qualified inherited UI-test metadata-tool warning. Every count, exact UTF-8, 44pt control, Save/Cancel, recovery, teaching and reparse assertion remains. The complete current iPad rerun passed 33/33 in 833.333s with zero warnings/skips/issues, natural exits and exact efe8 source; its strict retained-scroll/day-reset method passed in 61.313s. The complete efe8 phone rerun finished with 245 passed, one failed and the exact two standard simulator skips across all 245 declarations / 248 executions. All five earlier failed methods passed. The new failure is the record-pill assertion in `testReviewShowsExactSavedSourceWithoutGeneratedFacts`; its earlier pass is not a waiver. The complete result and native failure attachments are retained privately. Studio transport loss left the original launcher/guard completion receipts missing, so numeric wrapper exits, hard-timeout status and continuous drain remain unverified. Separate postrun checks prove all 971 source inputs and HEAD unchanged, no relevant process remaining, and both owned simulators Shutdown; these do not replace the missing receipts. The final series-token method passed in 574.372s with retained animation-idle diagnostics.++Native video and synthesized events show the intended Ada Keep tap near the sheet header while Ada's control was above the viewport, followed by four still-pending suggestions and no accepted pill. A fifth UI-test driver repair now requires full control visibility below its owning sheet toolbar before ordinary native tap, and waits for Ada's decision row to disappear before Done. The original saved-pill, alias and no-generated-facts assertions remain. Its candidate source is 971 / `25d23a0b…b023`; all other 966 inputs remain identical to the scoped b6de product qualification, and only this one test file differs from efe8. The focused 21-journey check (19 extraction plus two outcome journeys) passed in 1,155.297s with exact source, natural Make/wrapper exit 0, no failures/skips/runtime warnings, no timeout or helper cleanup and independently accepted certain drain. One inherited metadata warning has an identical earlier tool invocation and unchanged project input; unknown warnings are zero. The original record-pill method passed in 56.424s. The complete standard phone gate on this source finished with all 245 declarations / 248 actual executions accounted for: 246 passed, zero failed and the exact two standard physical-performance simulator skips. It ran without narrowed selection or added skips in 9,591.694s, with natural Make/wrapper exit 0, no timeout/helper cleanup, certain empty process drain, zero compiler/runtime warnings/issues and all 971 inputs unchanged. The original record-pill method passed in 55.985s. Four distinct actual launch configurations are preserved from this result, rather than copied from earlier runs. Root and independent final review accepted all 19 checks and the actual native/raw inventories. Both owned simulators were already Shutdown and no restoration action was needed. The accepted efe8 full iPad result retains its original source binding: only the private CharacterExtraction test helper differs, with no affected iPad suite, shared helper, fixture or product input. Current full-phone UI acceptance is green on the new source; broader performance/publication acceptance is not claimed. Focused passes never substituted for a full gate, and both earlier failed runs remain failed historical evidence. The earlier Core/native/Mac results retain their b6de source binding and are not relabeled as full efe8 runs.++The current continuation authorizes scoped repair review and ordinary feature-branch commit, push and PR preparation. It requests no installation or merge; earlier operational authority below is historical. The required complete phone UI and both complete iPad-only suites now have accepted results on their explicitly recorded source bindings. Existing duplicate observation/settling and capture performance failures, the complete current performance inventory and broader publication review remain separate unresolved gates. No budget or assertion is waived, and no performance redesign is added here. A draft PR must state these limits and retain the earlier fixes.++### Historical qualification and authority++The feature and reviewed P2/read-reuse follow-up are preserved at `9f71c5dc`; current 970-input qualification is recorded in [checkpoint.md](checkpoint.md). Historical task notes below retain their own source, authorization and gate status. The owner subsequently authorized completing the remaining gates, pr-pilot, merge and regular Release installation when those gates pass. The current default performance inventory is 52 declarations, superseding historical references to a narrower 33-declaration selection. No failed budget or pending runtime qualification is waived. A subsequent reviewed nine-path candidate is applied at 971 inputs / `8a241a73` after test-only fixture corrections, uncommitted. Focused 94 declarations / 139 executions passed with exact source/arguments and natural drain. Current unfiltered Core subsequently passed 4,060 started declarations plus the exact 55 opt-in skips (4,115 total), with 6,565 executions, no warnings/issues and accepted source/arguments. The original three-method performance diagnostic recovered creator detail to 42.8 ms, but retained five hard duplicate/capture failures. Standard fast 456/552 and signed Mac/native quick 1,833/1,938 also passed on this source; rendered/performance publication gates remain owed.++## Implementation++- [x] 1. Red: specify minimal ledger, note-head and migration counterexamples <!-- id:utwj28a -->+ - Add pure synthetic ordering/idempotence regressions for unseen acceptance after A→B→A; noncomposable source/record receipts; routine remaining-spelling continuity; reject A/accept B and reconsider A without old-root/note revival; matching-directory coverage changes; Clear surviving retirement and excluding all note edits from membership/coverage; complete historical rebind closure+ - retired-parent replay+ - child-before-parent and conflicting destinations. Add populated recorded-V20 migration/model-inventory fixtures and declare an early hundreds-of-chapters selected-read fixture.+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [2.2](requirements.md#2.2), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.1](requirements.md#6.1), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5)++- [x] 2. Green: implement two-entity values, fold, storage and additive V21 <!-- id:utwj28b -->+ - Implement only AssociationEvent and PairNoteVersion with immutable typed codecs/folds and atomic whole validation receipts. Freeze V20+ - add live V21/lightweight migration+ - readiness/bootstrap/extension/inventory markers and archive envelope guard per schema-migration.md. Batch physical-ID validation+ - memoize historical closure/scope digests+ - and share per-Work matching signatures; no per-pair full-history scans+ - endpoint graph or old NoEpisode optimisation.+ - Blocked-by: utwj28a (Red: specify minimal ledger, note-head and migration counterexamples)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [2.2](requirements.md#2.2), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.1](requirements.md#6.1), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5)++- [x] 3. Red: cover existing extraction and selected mutation integration <!-- id:utwj28c -->+ - Add real SwiftData extraction/mutation fixtures for both kinds+ - URL-free/same-URL distinct Entries+ - all facts unticked+ - exact current evidence spelling+ - missing/ineligible Entry stale Accept+ - narrow rejection/reconsideration+ - older fact coverage/new alias eligibility+ - failures/unavailability+ - failed-save atomicity+ - capture/manual/reparse/edit/delete/merge/conversion and late unknown loser branches. Preserve existing facts/aliases and proposal budget assertions.+ - Blocked-by: utwj28b (Green: implement two-entity values, fold, storage and additive V21)+ - 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), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.5](requirements.md#6.5)++- [x] 4. Green: integrate links in the existing extraction and mutation saves <!-- id:utwj28d -->+ - Extend existing grounding/matching/assembler/review commit/coverage lane. Add selected before/after helpers in existing saves; barriers even with zero known links+ - only before-active supported roots refreshed+ - final support loss retired. Known identity operations verified-rebind only observed roots/active note heads. Composite attempt/held eligibility includes matching-directory changes. Preserve transaction/rollback boundaries and exact evidence; no second call+ - candidate reread or general proof inventory.+ - Blocked-by: utwj28c (Red: cover existing extraction and selected mutation integration)+ - 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), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.5](requirements.md#6.5)++- [x] 5. Red: cover authored-note APIs, archive replay and publication <!-- id:utwj28e -->+ - Add authored-note Save/Clear/conflict and same-pair detached recovery API tests+ - typed historical parent closure+ - raw malformed/contradictory note preservation+ - old Clear replay after retirement+ - new acceptance not attaching old notes+ - archive roundtrip/predecessor conversion/newer-local guards/physical conflicts/partial arrival. Include coherent alias-first then source-change archive restoration without artificial retirement and all Entry provider/mock/Empty Library consumers.+ - Blocked-by: utwj28d (Green: integrate links in the existing extraction and mutation saves)+ - Stream: 1+ - Requirements: [1.3](requirements.md#1.3), [3.3](requirements.md#3.3), [3.6](requirements.md#3.6), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5)++- [x] 6. Green: implement note writes, two-array archives and publication <!-- id:utwj28f -->+ - Implement value-only head-basis writes and refusal preserving drafts; explicit same-pair recovery+ - verified system cross-pair rebind only. Preserve both raw arrays+ - exact notes and whole receipt variants in archive builders/projections/import with selected staged bundle validation; retain newer-local base guards. Add both entities to inventories/diagnostics/mock publication; do not let authored notes enter extraction DTOs or matching eligibility.+ - Blocked-by: utwj28e (Red: cover authored-note APIs, archive replay and publication)+ - Stream: 1+ - Requirements: [1.3](requirements.md#1.3), [3.3](requirements.md#3.3), [3.6](requirements.md#3.6), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5)++- [-] 7. Red: add synthetic editor and rendered recovery journeys <!-- id:utwj28g -->+ - Add synthetic native editor and rendered phone/iPad/Mac journeys for Save/Clear/Cancel+ - stale basis refusal+ - conflict visibility and same-pair detached recovery after retirement/missing endpoints. Declare selected identifiers/counts and capture explicit temporary fixture root/mirroring-off before bootstrap. Verify affected Entry/provider/recovery consumers without physical devices or shared-library access.+ - Current rendered evidence: intended29 phone methods passed across source-qualified runs; root subsequently accepted Mac5 after the reviewed navigation/binding correction. Historical authentication/route failures remain retained. The inherited same-geometry iPad scroll defect is tracked separately from T-2468; no assertion waiver or feature product-contract decision is pending. Required rendered evidence and separate defect disposition remain explicit.+ - Blocked-by: utwj28f (Green: implement note writes, two-array archives and publication)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [2.4](requirements.md#2.4), [3.3](requirements.md#3.3), [3.6](requirements.md#3.6), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.5](requirements.md#6.5)++- [ ] 8. Green: wire value-draft link editor and explicit Settings recovery <!-- id:utwj28h -->+ - Wire existing value-draft Save-terminal editor and Settings recovery patterns. Preserve written drafts on refusal. Use minimal platform-conditional native/rendered test harness where required; fix bare launch tests with existing seeded fixture plus fresh UUID isolation+ - preserving every assertion/metric and full pre-push selections. No cast-list redesign+ - history browser or inferred cross-pair destination selection.+ - Source and native editor/publication implementation is present and reviewed; root accepted Mac5 and final full native correctness. Formal completion remains pending overall composed validation; the inherited iPad defect is separate from T-2468 and does not introduce a feature contract decision. No code commit is ready.+ - Blocked-by: utwj28g (Red: add synthetic editor and rendered recovery journeys)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [2.4](requirements.md#2.4), [3.3](requirements.md#3.3), [3.6](requirements.md#3.6), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.5](requirements.md#6.5)++- [ ] 9. Verify composed code with required integration and unchanged relevant gates <!-- id:utwj28i -->+ - Final restored900 root acceptance: unfiltered Core4,017 declarations =3,962 passed+55 existing opt-in skips,6,304 expanded executions; fixed fast456/552 expanded clean; signed Mac app+embedded extension and native1,791/1,871 expanded passed with zero native issues/skips. Wrapper124 only for verified post-Xcode ibtoold cleanup is explicitly accepted separately in native-root-review.json; three inherited tool warnings. Source900 unchanged. Overall status stays pending: original Release budgets/full33 and pre-push full phone/iPad UI remain open. The inherited iPad defect is separate from T-2468; no assertion waiver or feature contract decision is pending.+ - On composed source+ - run early declared selected large-Work mutation/read fixture and unchanged relevant original M4 duplicate/consumer budget selections; no threshold/sample/assertion weakening or speculative broad benchmark loops. Before one code commit run unfiltered serial Core with no new warnings+ - fast+ - signed Mac app/extension compile+ - test-quick and targeted affected synthetic phone/iPad/Mac journeys. Full unfiltered phone/iPad UI only before a push. Use Make/private caches/jobs2/one heavy job/fresh resource boundaries; report actual counts+ - provenance+ - open baseline failures and limitations. No physical install+ - merge+ - main push or personal data.+ - Before the independently authorized repair (task10), exact-baseline phase2 passed12 invariant groups/36 phase observations: at5000 rows fresh index58.443ms, anchor history0.087ms, allActions87.207ms. Both global fetch/group and decode/sort scale with unrelated history; no repair or full M4 verdict.+ - Before task10, the exact-baseline public-API diagnostic passed12 unchanged-transition checks at100/1000/5000 history rows; medians3.439/31.555/152.918ms. This identifies history-size cost only, not full M4 completion or feature-relative causality; no NoEpisode repair applied. Required gates remain open.+ - Required Core/fast/signed Mac app+extension/full native quick and targeted phone/iPad evidence is recorded. Original33 M4 first attempt was interrupted at its60-minute helper bound:1 started,0 passed,32 unstarted. The post-repair unchanged33 bounded Release run ended at its30-minute runtime bound:7 started,5 passed (including the retained known-memory export issue),1 duplicate test failed both original2s medians,1 import test was interrupted and26 were unstarted. No completed full-gate verdict; failures and interruption are retained without waiver. The Mac retry executed3 with2passes and1 Inspector Edit route failure, so the behavior gate remains open; no implementation commit/staging/push.+ - Blocked-by: utwj28h (Green: wire value-draft link editor and explicit Settings recovery)+ - 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), [2.5](requirements.md#2.5), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [3.4](requirements.md#3.4), [3.5](requirements.md#3.5), [3.6](requirements.md#3.6), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2), [5.3](requirements.md#5.3), [5.4](requirements.md#5.4), [5.5](requirements.md#5.5), [6.1](requirements.md#6.1), [6.2](requirements.md#6.2), [6.3](requirements.md#6.3), [6.4](requirements.md#6.4), [6.5](requirements.md#6.5)++- [-] 10. Repair repeated global NoEpisode history reads within existing save chunks with focused TDD <!-- id:utwj28j -->+ - Bounded matched Release attribution is complete: exact baseline39696ad observation96.163s/settling170.460s versus current matched initial generation2.932s/5.231s, both exact semantic checks passed; C includes common repairs, so no feature-only subtraction. Private inclusive spans measured settling rawRedecode5.583ms and endpoint snapshot/fingerprint454.735ms; no safe2s fix demonstrated or further optimization selected. All shipping900 inputs unchanged. Original N10 still fails6.648267s/3.932553s versus2s and full33 is open. Remains in progress pending explicit hold-on-gates or documented performance-exception decision; no waiver/commit readiness inferred. Inherited iPad defect tracked separately.+ - Final restored900 Core/fast/signed Mac/full native correctness gates are root accepted as recorded in implementation.md. This repair remains in progress because original Release2s medians/full33 are unresolved; no further optimization, blanket baseline waiver or completion/commit readiness is authorized. All worker heavy jobs drained.+ - Conditional mutation-only original Release N10 trial completed149.095s and still failed both2s medians (settling6.309745s/observation3.796133s), no semantic/count issue. Candidate901 pre/post integrity passed; natural drained guard. Root rejected trial, reviewed restore returned exact900 baseline and preserved all private evidence; no completion, full33 remains open.+ - Conditional mutation-only receipt-scope warming trial passed whole329 declarations/31 suites/442 expanded executions (all154 argument values source-reconciled), no new warning origin. Public/default warming unchanged; candidate901 was subsequently performance-tested, rejected and exactly restored to900 as recorded above. Original Release failures remain unresolved; no completion claim.+ - Conditional descriptor-only Entry.work prefetch trial passed affected88/93 correctness, but same original Release N10 still failed both2s medians (settling6.281479s/observation3.682579s;146.912s test). Runtime birth clock activated, guard naturally drained,900inputs unchanged. Root declined retention after one-shot result; both trial files restored exactly, full900 baseline and authoritative binding green verified. All evidence preserved; no completion claim.+ - Subsequent original Release single-test gate completed153.168s/n10 per arm and failed both unchanged2s medians: settling6.648267s/observation3.932553s. No semantic/count issue; full33 remains open. Guard retained building clock only (718.353s total<900), not claimed runtime-clock enforcement. All898 hashes unchanged,26 warning origins inherited; no completion/commit readiness.+ - Reviewed lazy per-Work raw-row inventory: compile RED absent seam, runtime RED exactly2 traversal-counter issues/all semantics passing; GREEN5/6expanded and broader85/90expanded passed, no warnings/skips/issues. Global physical validation unchanged, record-only inventory remains lazy, own insertions/external invalidation covered. Bounded performance comparison and original unchanged timing gates remain pending; no completion/commit readiness.+ - Subsequently parent-authorized live import Entry-chunk reuse: compile RED confirmed absent internal factory; seam-only runtime RED executed6 with10 batching-only issues and all semantics passing; perchunk GREEN6 passed0.141s/build11.28s without warnings. Broader existing importer/history correctness80 passed2.512s, exact80IDs/eight suites/84expanded executions, no warnings/skips/issues. Original timing failures and Mac route remain open; no completion or commit readiness.+ - Focused138 correctness and warning-clean11 passed. Current original initial generation completed semantically (observation3.434s/settling6.600s Debug); exact baseline observation timed out120s. Post-repair unfiltered Core3 and full native quick3/signed Mac passed. Original33 Release first test completed10 samples and failed unchanged2s budgets (settlingmedian7.630516s/observationmedian3.982454s); the run later reached its30-minute bound with7 started/5 passed/1 failed/1 interrupted/26 unstarted. The external facts-prefetch diagnostic preserves all5750 facts but saves only about0.171s total per measured call; no further repair is authorized and this task remains incomplete. No waiver or completion claim.+ - Parent-approved independent repair after exact-baseline phase diagnosis; does not complete or depend on the blocked Mac gate. Preserve global refusal reach, lazy empty guard, same-call snapshot, pending clears, raw Work moves and fresh save/rollback/replay lifecycle.+ - Stream: 1+ - Requirements: [6.1](requirements.md#6.1), [6.3](requirements.md#6.3)++### Phone deployment priority checkpoint++Owner-authorized Devsterism test installation before merge completed through one successful Xcode MCP RunProject in 11.438 seconds. The deployed generated-catalog source map `33a479c2` remains separate from `17ec40d3` correctness bindings. The source catalog was restored to exact `17ec40d3` bytes after installation, without a further build or device action. The earlier twelve-phone batch passed all assertions with zero runtime warnings but failed its source guard during extraction and remains unaccepted. The fresh strict phone recovery passed all twelve exact journeys with zero warnings and unchanged source. The separately admitted four iPad journeys also passed with zero warnings and unchanged source, completing the targeted precommit bars. The twelve reviewed paths are now preserved in `a9fe5b75`; the unverified nine-line Mac-only test route remains outside that commit. Full publication, Mac authentication and performance gates remain open; deployment does not mark those tasks complete.
diff --git a/specs/character-ranking/requirements.md b/specs/character-ranking/requirements.mdindex 3d5ea629..25282160 100644--- a/specs/character-ranking/requirements.md+++ b/specs/character-ranking/requirements.md@@ -81,3 +81,10 @@ A work's characters are listed in name order, so the protagonist can sit below a 1. <a name="4.1"></a>Given identical inputs, the ranking SHALL produce identical order regardless of the order in which characters, facts, or entries were read, and on every supported device. 2. <a name="4.2"></a>The ranking SHALL NOT add a new fetch request, a stored field, or a schema version; it MAY use the work's entry placement and first-capture fields on the share path. 3. <a name="4.3"></a>WHEN ranking 200 characters with 50 facts each over 500 live entries, the ranking function alone SHALL complete within a 10 ms budget on the host performance suite, with a 50 ms regression ceiling asserted outside any known-issue block. +++## Note-first amendment — 2026-10-19++The owner-requested [chapter-based ranking correction](../bugfixes/character-chapter-ranking/report.md) extends the evidence input after fact generation stopped. Distinct active, globally validated saved character-to-chapter Entry links supply a floor of one support unit per Entry, using max(existing Entry fact count, 1) before equal-position aggregation. Legacy facts remain historical relevance evidence, without creating current appearances. Place ranking, story-position decay, concave breadth weighting and deterministic ties remain unchanged.++This narrowly supersedes the no-added-fetch part of requirement 4.2: each Work ranking read may perform one batched association inventory without annotation bodies and one validated endpoint batch. There must be no per-character history read, stored score, new field or schema change. Optional share-note failure isolation remains intact after cast prerequisites succeed. The existing pure arithmetic budget and the outstanding project performance qualifications are not waived.
diff --git a/specs/general/TECH-IMPROVEMENTS.md b/specs/general/TECH-IMPROVEMENTS.mdnew file mode 100644index 00000000..c5a04ae9--- /dev/null+++ b/specs/general/TECH-IMPROVEMENTS.md@@ -0,0 +1,38 @@+# Technical improvement investigations++## 2026-10-18 — Efficiency review, T-2468++### Issue: captured association events are decoded twice++**Location:** `AssociationStorage.swift:85`, `AssociationMutation.swift:80`.++**Description:** Storage reads and validates every physical event copy, decoding+its captured raw bytes for the initial ledger. Mutation finish decodes those+same captured raw values again before its final fold. Capture is already once+per existing save chunk; a per-set capture diagnosis would be incorrect.++**Impact:** The duplicate decode is source-confirmed. Its elapsed contribution+is not measured, so it is not yet a selected performance fix or an explanation+of the failed two-second observation/settling budgets.++**Solution to evaluate:** Measure storage decoding and finish decoding separately+in an excluded, private Release probe. If material, retain and reuse the decoded+physical values within the existing operation-local snapshot:++```swift+// Proposed shape only; not implemented or admitted for shipping.+let decodedPhysicalEvents: [AssociationLedgerEvent]+```++**Trade-offs:** Preserve every physical variant, malformed-copy quarantine,+parent closure, endpoint read, fresh invalidation, save and rollback boundary.+Do not deduplicate by application UUID, cache across calls, or skip work merely+because no acceptance is currently active. Any change still needs semantic+counterexamples and the unchanged original performance gate. Other candidates+remain rejected; measured attribution must precede another optimization.++---++### Measured disposition, 2026-10-18++The reviewed private coarse probe measured duplicate captured-event re-decoding at <1μs in observation and5.583ms in settling. This single successful empty-acceptance fixture does **not** justify a shipping decode optimization or another broad performance trial. Keep the source finding documented but unimplemented. Source endpoint snapshot/grouping/fingerprinting was the largest measured association child at0.209064s/0.454735s; this does not establish a safe specific rewrite or2s budget closure. Full qualification and receipts: `specs/character-chapter-associations/performance-attribution.md`.
Full phone: 245 declarations / 248 launch-expanded executions, with only the two existing physical-performance simulator skips. Full iPad: all 33 methods in both wide-layout suites. Neither may be narrowed.
Duplicate observation/settling and capture budgets remain failed. The original complete performance inventory and final broader publication review remain separate. Ordinary spine-button activation and large-day rendering bounds are not inferred from the scoped repair.
The structured JUnit card contains only the retained Core gate. It ran on b6de971source with the repair working tree at6b71307d, before the later dc676a96 preservation commit. The card keeps that actual HEAD/dirty provenance; current full UI counts are reported separately. Later UI-driver changes do not relabel the earlier test snapshot.